262d5d49655affa254f6027237edd65267a969cb
[asterisk/asterisk.git] / main / audiohook.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2007, Digium, Inc.
5  *
6  * Joshua Colp <jcolp@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Audiohooks Architecture
22  *
23  * \author Joshua 'file' Colp <jcolp@digium.com>
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
30 #include <signal.h>
31
32 #include "asterisk/channel.h"
33 #include "asterisk/utils.h"
34 #include "asterisk/lock.h"
35 #include "asterisk/linkedlists.h"
36 #include "asterisk/audiohook.h"
37 #include "asterisk/slinfactory.h"
38 #include "asterisk/frame.h"
39 #include "asterisk/translate.h"
40
41 struct ast_audiohook_translate {
42         struct ast_trans_pvt *trans_pvt;
43         int format;
44 };
45
46 struct ast_audiohook_list {
47         struct ast_audiohook_translate in_translate[2];
48         struct ast_audiohook_translate out_translate[2];
49         AST_LIST_HEAD_NOLOCK(, ast_audiohook) spy_list;
50         AST_LIST_HEAD_NOLOCK(, ast_audiohook) whisper_list;
51         AST_LIST_HEAD_NOLOCK(, ast_audiohook) manipulate_list;
52 };
53
54 /*! \brief Initialize an audiohook structure
55  * \param audiohook Audiohook structure
56  * \param type
57  * \param source
58  * \return Returns 0 on success, -1 on failure
59  */
60 int ast_audiohook_init(struct ast_audiohook *audiohook, enum ast_audiohook_type type, const char *source)
61 {
62         /* Need to keep the type and source */
63         audiohook->type = type;
64         audiohook->source = source;
65
66         /* Initialize lock that protects our audiohook */
67         ast_mutex_init(&audiohook->lock);
68         ast_cond_init(&audiohook->trigger, NULL);
69
70         /* Setup the factories that are needed for this audiohook type */
71         switch (type) {
72         case AST_AUDIOHOOK_TYPE_SPY:
73                 ast_slinfactory_init(&audiohook->read_factory);
74         case AST_AUDIOHOOK_TYPE_WHISPER:
75                 ast_slinfactory_init(&audiohook->write_factory);
76                 break;
77         default:
78                 break;
79         }
80
81         /* Since we are just starting out... this audiohook is new */
82         audiohook->status = AST_AUDIOHOOK_STATUS_NEW;
83
84         return 0;
85 }
86
87 /*! \brief Destroys an audiohook structure
88  * \param audiohook Audiohook structure
89  * \return Returns 0 on success, -1 on failure
90  */
91 int ast_audiohook_destroy(struct ast_audiohook *audiohook)
92 {
93         /* Drop the factories used by this audiohook type */
94         switch (audiohook->type) {
95         case AST_AUDIOHOOK_TYPE_SPY:
96                 ast_slinfactory_destroy(&audiohook->read_factory);
97         case AST_AUDIOHOOK_TYPE_WHISPER:
98                 ast_slinfactory_destroy(&audiohook->write_factory);
99                 break;
100         default:
101                 break;
102         }
103
104         /* Destroy translation path if present */
105         if (audiohook->trans_pvt)
106                 ast_translator_free_path(audiohook->trans_pvt);
107
108         /* Lock and trigger be gone! */
109         ast_cond_destroy(&audiohook->trigger);
110         ast_mutex_destroy(&audiohook->lock);
111
112         return 0;
113 }
114
115 /*! \brief Writes a frame into the audiohook structure
116  * \param audiohook Audiohook structure
117  * \param direction Direction the audio frame came from
118  * \param frame Frame to write in
119  * \return Returns 0 on success, -1 on failure
120  */
121 int ast_audiohook_write_frame(struct ast_audiohook *audiohook, enum ast_audiohook_direction direction, struct ast_frame *frame)
122 {
123         struct ast_slinfactory *factory = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook->read_factory : &audiohook->write_factory);
124         struct ast_slinfactory *other_factory = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook->write_factory : &audiohook->read_factory);
125         struct timeval *rwtime = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook->read_time : &audiohook->write_time), previous_time = *rwtime;
126         int our_factory_ms;
127         int other_factory_samples;
128         int other_factory_ms;
129
130         /* Update last feeding time to be current */
131         *rwtime = ast_tvnow();
132
133         our_factory_ms = ast_tvdiff_ms(*rwtime, previous_time) + (ast_slinfactory_available(factory) / 8);
134         other_factory_samples = ast_slinfactory_available(other_factory);
135         other_factory_ms = other_factory_samples / 8;
136
137         if (ast_test_flag(audiohook, AST_AUDIOHOOK_TRIGGER_SYNC) && other_factory_samples && (our_factory_ms - other_factory_ms > AST_AUDIOHOOK_SYNC_TOLERANCE)) {
138                 if (option_debug)
139                         ast_log(LOG_DEBUG, "Flushing audiohook %p so it remains in sync\n", audiohook);
140                 ast_slinfactory_flush(factory);
141                 ast_slinfactory_flush(other_factory);
142         }
143
144         /* Write frame out to respective factory */
145         ast_slinfactory_feed(factory, frame);
146
147         /* If we need to notify the respective handler of this audiohook, do so */
148         if ((ast_test_flag(audiohook, AST_AUDIOHOOK_TRIGGER_MODE) == AST_AUDIOHOOK_TRIGGER_READ) && (direction == AST_AUDIOHOOK_DIRECTION_READ)) {
149                 ast_cond_signal(&audiohook->trigger);
150         } else if ((ast_test_flag(audiohook, AST_AUDIOHOOK_TRIGGER_MODE) == AST_AUDIOHOOK_TRIGGER_WRITE) && (direction == AST_AUDIOHOOK_DIRECTION_WRITE)) {
151                 ast_cond_signal(&audiohook->trigger);
152         } else if (ast_test_flag(audiohook, AST_AUDIOHOOK_TRIGGER_SYNC)) {
153                 ast_cond_signal(&audiohook->trigger);
154         }
155
156         return 0;
157 }
158
159 static struct ast_frame *audiohook_read_frame_single(struct ast_audiohook *audiohook, size_t samples, enum ast_audiohook_direction direction)
160 {
161         struct ast_slinfactory *factory = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook->read_factory : &audiohook->write_factory);
162         int vol = (direction == AST_AUDIOHOOK_DIRECTION_READ ? audiohook->options.read_volume : audiohook->options.write_volume);
163         short buf[samples];
164         struct ast_frame frame = {
165                 .frametype = AST_FRAME_VOICE,
166                 .subclass = AST_FORMAT_SLINEAR,
167                 .data.ptr = buf,
168                 .datalen = sizeof(buf),
169                 .samples = samples,
170         };
171
172         /* Ensure the factory is able to give us the samples we want */
173         if (samples > ast_slinfactory_available(factory))
174                 return NULL;
175         
176         /* Read data in from factory */
177         if (!ast_slinfactory_read(factory, buf, samples))
178                 return NULL;
179
180         /* If a volume adjustment needs to be applied apply it */
181         if (vol)
182                 ast_frame_adjust_volume(&frame, vol);
183
184         return ast_frdup(&frame);
185 }
186
187 static struct ast_frame *audiohook_read_frame_both(struct ast_audiohook *audiohook, size_t samples)
188 {
189         int i = 0, usable_read, usable_write;
190         short buf1[samples], buf2[samples], *read_buf = NULL, *write_buf = NULL, *final_buf = NULL, *data1 = NULL, *data2 = NULL;
191         struct ast_frame frame = {
192                 .frametype = AST_FRAME_VOICE,
193                 .subclass = AST_FORMAT_SLINEAR,
194                 .data.ptr = NULL,
195                 .datalen = sizeof(buf1),
196                 .samples = samples,
197         };
198
199         /* Make sure both factories have the required samples */
200         usable_read = (ast_slinfactory_available(&audiohook->read_factory) >= samples ? 1 : 0);
201         usable_write = (ast_slinfactory_available(&audiohook->write_factory) >= samples ? 1 : 0);
202
203         if (!usable_read && !usable_write) {
204                 /* If both factories are unusable bail out */
205                 ast_debug(1, "Read factory %p and write factory %p both fail to provide %zd samples\n", &audiohook->read_factory, &audiohook->write_factory, samples);
206                 return NULL;
207         }
208
209         /* If we want to provide only a read factory make sure we aren't waiting for other audio */
210         if (usable_read && !usable_write && (ast_tvdiff_ms(ast_tvnow(), audiohook->write_time) < (samples/8)*2)) {
211                 ast_debug(3, "Write factory %p was pretty quick last time, waiting for them.\n", &audiohook->write_factory);
212                 return NULL;
213         }
214
215         /* If we want to provide only a write factory make sure we aren't waiting for other audio */
216         if (usable_write && !usable_read && (ast_tvdiff_ms(ast_tvnow(), audiohook->read_time) < (samples/8)*2)) {
217                 ast_debug(3, "Read factory %p was pretty quick last time, waiting for them.\n", &audiohook->read_factory);
218                 return NULL;
219         }
220
221         /* Start with the read factory... if there are enough samples, read them in */
222         if (usable_read) {
223                 if (ast_slinfactory_read(&audiohook->read_factory, buf1, samples)) {
224                         read_buf = buf1;
225                         /* Adjust read volume if need be */
226                         if (audiohook->options.read_volume) {
227                                 int count = 0;
228                                 short adjust_value = abs(audiohook->options.read_volume);
229                                 for (count = 0; count < samples; count++) {
230                                         if (audiohook->options.read_volume > 0)
231                                                 ast_slinear_saturated_multiply(&buf1[count], &adjust_value);
232                                         else if (audiohook->options.read_volume < 0)
233                                                 ast_slinear_saturated_divide(&buf1[count], &adjust_value);
234                                 }
235                         }
236                 }
237         } else if (option_debug)
238                 ast_log(LOG_DEBUG, "Failed to get %d samples from read factory %p\n", (int)samples, &audiohook->read_factory);
239
240         /* Move on to the write factory... if there are enough samples, read them in */
241         if (usable_write) {
242                 if (ast_slinfactory_read(&audiohook->write_factory, buf2, samples)) {
243                         write_buf = buf2;
244                         /* Adjust write volume if need be */
245                         if (audiohook->options.write_volume) {
246                                 int count = 0;
247                                 short adjust_value = abs(audiohook->options.write_volume);
248                                 for (count = 0; count < samples; count++) {
249                                         if (audiohook->options.write_volume > 0)
250                                                 ast_slinear_saturated_multiply(&buf2[count], &adjust_value);
251                                         else if (audiohook->options.write_volume < 0)
252                                                 ast_slinear_saturated_divide(&buf2[count], &adjust_value);
253                                 }
254                         }
255                 }
256         } else if (option_debug)
257                 ast_log(LOG_DEBUG, "Failed to get %d samples from write factory %p\n", (int)samples, &audiohook->write_factory);
258
259         /* Basically we figure out which buffer to use... and if mixing can be done here */
260         if (!read_buf && !write_buf)
261                 return NULL;
262         else if (read_buf && write_buf) {
263                 for (i = 0, data1 = read_buf, data2 = write_buf; i < samples; i++, data1++, data2++)
264                         ast_slinear_saturated_add(data1, data2);
265                 final_buf = buf1;
266         } else if (read_buf)
267                 final_buf = buf1;
268         else if (write_buf)
269                 final_buf = buf2;
270
271         /* Make the final buffer part of the frame, so it gets duplicated fine */
272         frame.data.ptr = final_buf;
273
274         /* Yahoo, a combined copy of the audio! */
275         return ast_frdup(&frame);
276 }
277
278 /*! \brief Reads a frame in from the audiohook structure
279  * \param audiohook Audiohook structure
280  * \param samples Number of samples wanted
281  * \param direction Direction the audio frame came from
282  * \param format Format of frame remote side wants back
283  * \return Returns frame on success, NULL on failure
284  */
285 struct ast_frame *ast_audiohook_read_frame(struct ast_audiohook *audiohook, size_t samples, enum ast_audiohook_direction direction, int format)
286 {
287         struct ast_frame *read_frame = NULL, *final_frame = NULL;
288
289         if (!(read_frame = (direction == AST_AUDIOHOOK_DIRECTION_BOTH ? audiohook_read_frame_both(audiohook, samples) : audiohook_read_frame_single(audiohook, samples, direction))))
290                 return NULL;
291
292         /* If they don't want signed linear back out, we'll have to send it through the translation path */
293         if (format != AST_FORMAT_SLINEAR) {
294                 /* Rebuild translation path if different format then previously */
295                 if (audiohook->format != format) {
296                         if (audiohook->trans_pvt) {
297                                 ast_translator_free_path(audiohook->trans_pvt);
298                                 audiohook->trans_pvt = NULL;
299                         }
300                         /* Setup new translation path for this format... if we fail we can't very well return signed linear so free the frame and return nothing */
301                         if (!(audiohook->trans_pvt = ast_translator_build_path(format, AST_FORMAT_SLINEAR))) {
302                                 ast_frfree(read_frame);
303                                 return NULL;
304                         }
305                 }
306                 /* Convert to requested format, and allow the read in frame to be freed */
307                 final_frame = ast_translate(audiohook->trans_pvt, read_frame, 1);
308         } else {
309                 final_frame = read_frame;
310         }
311
312         return final_frame;
313 }
314
315 /*! \brief Attach audiohook to channel
316  * \param chan Channel
317  * \param audiohook Audiohook structure
318  * \return Returns 0 on success, -1 on failure
319  */
320 int ast_audiohook_attach(struct ast_channel *chan, struct ast_audiohook *audiohook)
321 {
322         ast_channel_lock(chan);
323
324         if (!chan->audiohooks) {
325                 /* Whoops... allocate a new structure */
326                 if (!(chan->audiohooks = ast_calloc(1, sizeof(*chan->audiohooks)))) {
327                         ast_channel_unlock(chan);
328                         return -1;
329                 }
330                 AST_LIST_HEAD_INIT_NOLOCK(&chan->audiohooks->spy_list);
331                 AST_LIST_HEAD_INIT_NOLOCK(&chan->audiohooks->whisper_list);
332                 AST_LIST_HEAD_INIT_NOLOCK(&chan->audiohooks->manipulate_list);
333         }
334
335         /* Drop into respective list */
336         if (audiohook->type == AST_AUDIOHOOK_TYPE_SPY)
337                 AST_LIST_INSERT_TAIL(&chan->audiohooks->spy_list, audiohook, list);
338         else if (audiohook->type == AST_AUDIOHOOK_TYPE_WHISPER)
339                 AST_LIST_INSERT_TAIL(&chan->audiohooks->whisper_list, audiohook, list);
340         else if (audiohook->type == AST_AUDIOHOOK_TYPE_MANIPULATE)
341                 AST_LIST_INSERT_TAIL(&chan->audiohooks->manipulate_list, audiohook, list);
342
343         /* Change status over to running since it is now attached */
344         audiohook->status = AST_AUDIOHOOK_STATUS_RUNNING;
345
346         ast_channel_unlock(chan);
347
348         return 0;
349 }
350
351 /*! \brief Detach audiohook from channel
352  * \param audiohook Audiohook structure
353  * \return Returns 0 on success, -1 on failure
354  */
355 int ast_audiohook_detach(struct ast_audiohook *audiohook)
356 {
357         if (audiohook->status == AST_AUDIOHOOK_STATUS_DONE)
358                 return 0;
359
360         audiohook->status = AST_AUDIOHOOK_STATUS_SHUTDOWN;
361
362         while (audiohook->status != AST_AUDIOHOOK_STATUS_DONE)
363                 ast_audiohook_trigger_wait(audiohook);
364
365         return 0;
366 }
367
368 /*! \brief Detach audiohooks from list and destroy said list
369  * \param audiohook_list List of audiohooks
370  * \return Returns 0 on success, -1 on failure
371  */
372 int ast_audiohook_detach_list(struct ast_audiohook_list *audiohook_list)
373 {
374         int i = 0;
375         struct ast_audiohook *audiohook = NULL;
376
377         /* Drop any spies */
378         while ((audiohook = AST_LIST_REMOVE_HEAD(&audiohook_list->spy_list, list))) {
379                 ast_audiohook_lock(audiohook);
380                 audiohook->status = AST_AUDIOHOOK_STATUS_DONE;
381                 ast_cond_signal(&audiohook->trigger);
382                 ast_audiohook_unlock(audiohook);
383         }
384
385         /* Drop any whispering sources */
386         while ((audiohook = AST_LIST_REMOVE_HEAD(&audiohook_list->whisper_list, list))) {
387                 ast_audiohook_lock(audiohook);
388                 audiohook->status = AST_AUDIOHOOK_STATUS_DONE;
389                 ast_cond_signal(&audiohook->trigger);
390                 ast_audiohook_unlock(audiohook);
391         }
392
393         /* Drop any manipulaters */
394         while ((audiohook = AST_LIST_REMOVE_HEAD(&audiohook_list->manipulate_list, list))) {
395                 ast_audiohook_lock(audiohook);
396                 audiohook->status = AST_AUDIOHOOK_STATUS_DONE;
397                 ast_audiohook_unlock(audiohook);
398                 audiohook->manipulate_callback(audiohook, NULL, NULL, 0);
399         }
400
401         /* Drop translation paths if present */
402         for (i = 0; i < 2; i++) {
403                 if (audiohook_list->in_translate[i].trans_pvt)
404                         ast_translator_free_path(audiohook_list->in_translate[i].trans_pvt);
405                 if (audiohook_list->out_translate[i].trans_pvt)
406                         ast_translator_free_path(audiohook_list->out_translate[i].trans_pvt);
407         }
408         
409         /* Free ourselves */
410         ast_free(audiohook_list);
411
412         return 0;
413 }
414
415 /*! \brief find an audiohook based on its source
416  * \param audiohook_list The list of audiohooks to search in
417  * \param source The source of the audiohook we wish to find
418  * \return Return the corresponding audiohook or NULL if it cannot be found.
419  */
420 static struct ast_audiohook *find_audiohook_by_source(struct ast_audiohook_list *audiohook_list, const char *source)
421 {
422         struct ast_audiohook *audiohook = NULL;
423
424         AST_LIST_TRAVERSE(&audiohook_list->spy_list, audiohook, list) {
425                 if (!strcasecmp(audiohook->source, source))
426                         return audiohook;
427         }
428
429         AST_LIST_TRAVERSE(&audiohook_list->whisper_list, audiohook, list) {
430                 if (!strcasecmp(audiohook->source, source))
431                         return audiohook;
432         }
433
434         AST_LIST_TRAVERSE(&audiohook_list->manipulate_list, audiohook, list) {
435                 if (!strcasecmp(audiohook->source, source))
436                         return audiohook;
437         }
438
439         return NULL;
440 }
441
442 void ast_audiohook_move_by_source(struct ast_channel *old_chan, struct ast_channel *new_chan, const char *source)
443 {
444         struct ast_audiohook *audiohook = find_audiohook_by_source(old_chan->audiohooks, source);
445
446         if (!audiohook) {
447                 return;
448         }
449         
450         /* By locking both channels and the audiohook, we can assure that
451          * another thread will not have a chance to read the audiohook's status
452          * as done, even though ast_audiohook_remove signals the trigger
453          * condition
454          */
455         ast_audiohook_lock(audiohook);
456         ast_audiohook_remove(old_chan, audiohook);
457         ast_audiohook_attach(new_chan, audiohook);
458         ast_audiohook_unlock(audiohook);
459 }
460
461 /*! \brief Detach specified source audiohook from channel
462  * \param chan Channel to detach from
463  * \param source Name of source to detach
464  * \return Returns 0 on success, -1 on failure
465  */
466 int ast_audiohook_detach_source(struct ast_channel *chan, const char *source)
467 {
468         struct ast_audiohook *audiohook = NULL;
469
470         ast_channel_lock(chan);
471
472         /* Ensure the channel has audiohooks on it */
473         if (!chan->audiohooks) {
474                 ast_channel_unlock(chan);
475                 return -1;
476         }
477
478         audiohook = find_audiohook_by_source(chan->audiohooks, source);
479
480         ast_channel_unlock(chan);
481
482         if (audiohook && audiohook->status != AST_AUDIOHOOK_STATUS_DONE)
483                 audiohook->status = AST_AUDIOHOOK_STATUS_SHUTDOWN;
484
485         return (audiohook ? 0 : -1);
486 }
487
488 /*!
489  * \brief Remove an audiohook from a specified channel
490  *
491  * \param chan Channel to remove from
492  * \param audiohook Audiohook to remove
493  *
494  * \return Returns 0 on success, -1 on failure
495  *
496  * \note The channel does not need to be locked before calling this function
497  */
498 int ast_audiohook_remove(struct ast_channel *chan, struct ast_audiohook *audiohook)
499 {
500         ast_channel_lock(chan);
501
502         if (!chan->audiohooks) {
503                 ast_channel_unlock(chan);
504                 return -1;
505         }
506
507         if (audiohook->type == AST_AUDIOHOOK_TYPE_SPY)
508                 AST_LIST_REMOVE(&chan->audiohooks->spy_list, audiohook, list);
509         else if (audiohook->type == AST_AUDIOHOOK_TYPE_WHISPER)
510                 AST_LIST_REMOVE(&chan->audiohooks->whisper_list, audiohook, list);
511         else if (audiohook->type == AST_AUDIOHOOK_TYPE_MANIPULATE)
512                 AST_LIST_REMOVE(&chan->audiohooks->manipulate_list, audiohook, list);
513
514         ast_audiohook_lock(audiohook);
515         audiohook->status = AST_AUDIOHOOK_STATUS_DONE;
516         ast_cond_signal(&audiohook->trigger);
517         ast_audiohook_unlock(audiohook);
518
519         ast_channel_unlock(chan);
520
521         return 0;
522 }
523
524 /*! \brief Pass a DTMF frame off to be handled by the audiohook core
525  * \param chan Channel that the list is coming off of
526  * \param audiohook_list List of audiohooks
527  * \param direction Direction frame is coming in from
528  * \param frame The frame itself
529  * \return Return frame on success, NULL on failure
530  */
531 static struct ast_frame *dtmf_audiohook_write_list(struct ast_channel *chan, struct ast_audiohook_list *audiohook_list, enum ast_audiohook_direction direction, struct ast_frame *frame)
532 {
533         struct ast_audiohook *audiohook = NULL;
534
535         AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->manipulate_list, audiohook, list) {
536                 ast_audiohook_lock(audiohook);
537                 if (audiohook->status != AST_AUDIOHOOK_STATUS_RUNNING) {
538                         AST_LIST_REMOVE_CURRENT(list);
539                         audiohook->status = AST_AUDIOHOOK_STATUS_DONE;
540                         ast_audiohook_unlock(audiohook);
541                         audiohook->manipulate_callback(audiohook, NULL, NULL, 0);
542                         continue;
543                 }
544                 if (ast_test_flag(audiohook, AST_AUDIOHOOK_WANTS_DTMF))
545                         audiohook->manipulate_callback(audiohook, chan, frame, direction);
546                 ast_audiohook_unlock(audiohook);
547         }
548         AST_LIST_TRAVERSE_SAFE_END;
549
550         return frame;
551 }
552
553 /*! \brief Pass an AUDIO frame off to be handled by the audiohook core
554  * \param chan Channel that the list is coming off of
555  * \param audiohook_list List of audiohooks
556  * \param direction Direction frame is coming in from
557  * \param frame The frame itself
558  * \return Return frame on success, NULL on failure
559  */
560 static struct ast_frame *audio_audiohook_write_list(struct ast_channel *chan, struct ast_audiohook_list *audiohook_list, enum ast_audiohook_direction direction, struct ast_frame *frame)
561 {
562         struct ast_audiohook_translate *in_translate = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook_list->in_translate[0] : &audiohook_list->in_translate[1]);
563         struct ast_audiohook_translate *out_translate = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook_list->out_translate[0] : &audiohook_list->out_translate[1]);
564         struct ast_frame *start_frame = frame, *middle_frame = frame, *end_frame = frame;
565         struct ast_audiohook *audiohook = NULL;
566         int samples = frame->samples;
567         
568         /* If the frame coming in is not signed linear we have to send it through the in_translate path */
569         if (frame->subclass != AST_FORMAT_SLINEAR) {
570                 if (in_translate->format != frame->subclass) {
571                         if (in_translate->trans_pvt)
572                                 ast_translator_free_path(in_translate->trans_pvt);
573                         if (!(in_translate->trans_pvt = ast_translator_build_path(AST_FORMAT_SLINEAR, frame->subclass)))
574                                 return frame;
575                         in_translate->format = frame->subclass;
576                 }
577                 if (!(middle_frame = ast_translate(in_translate->trans_pvt, frame, 0)))
578                         return frame;
579         }
580
581         /* Queue up signed linear frame to each spy */
582         AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->spy_list, audiohook, list) {
583                 ast_audiohook_lock(audiohook);
584                 if (audiohook->status != AST_AUDIOHOOK_STATUS_RUNNING) {
585                         AST_LIST_REMOVE_CURRENT(list);
586                         audiohook->status = AST_AUDIOHOOK_STATUS_DONE;
587                         ast_cond_signal(&audiohook->trigger);
588                         ast_audiohook_unlock(audiohook);
589                         continue;
590                 }
591                 ast_audiohook_write_frame(audiohook, direction, middle_frame);
592                 ast_audiohook_unlock(audiohook);
593         }
594         AST_LIST_TRAVERSE_SAFE_END
595
596         /* If this frame is being written out to the channel then we need to use whisper sources */
597         if (direction == AST_AUDIOHOOK_DIRECTION_WRITE && !AST_LIST_EMPTY(&audiohook_list->whisper_list)) {
598                 int i = 0;
599                 short read_buf[samples], combine_buf[samples], *data1 = NULL, *data2 = NULL;
600                 memset(&combine_buf, 0, sizeof(combine_buf));
601                 AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->whisper_list, audiohook, list) {
602                         ast_audiohook_lock(audiohook);
603                         if (audiohook->status != AST_AUDIOHOOK_STATUS_RUNNING) {
604                                 AST_LIST_REMOVE_CURRENT(list);
605                                 audiohook->status = AST_AUDIOHOOK_STATUS_DONE;
606                                 ast_cond_signal(&audiohook->trigger);
607                                 ast_audiohook_unlock(audiohook);
608                                 continue;
609                         }
610                         if (ast_slinfactory_available(&audiohook->write_factory) >= samples && ast_slinfactory_read(&audiohook->write_factory, read_buf, samples)) {
611                                 /* Take audio from this whisper source and combine it into our main buffer */
612                                 for (i = 0, data1 = combine_buf, data2 = read_buf; i < samples; i++, data1++, data2++)
613                                         ast_slinear_saturated_add(data1, data2);
614                         }
615                         ast_audiohook_unlock(audiohook);
616                 }
617                 AST_LIST_TRAVERSE_SAFE_END
618                 /* We take all of the combined whisper sources and combine them into the audio being written out */
619                 for (i = 0, data1 = middle_frame->data.ptr, data2 = combine_buf; i < samples; i++, data1++, data2++)
620                         ast_slinear_saturated_add(data1, data2);
621                 end_frame = middle_frame;
622         }
623
624         /* Pass off frame to manipulate audiohooks */
625         if (!AST_LIST_EMPTY(&audiohook_list->manipulate_list)) {
626                 AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->manipulate_list, audiohook, list) {
627                         ast_audiohook_lock(audiohook);
628                         if (audiohook->status != AST_AUDIOHOOK_STATUS_RUNNING) {
629                                 AST_LIST_REMOVE_CURRENT(list);
630                                 audiohook->status = AST_AUDIOHOOK_STATUS_DONE;
631                                 ast_audiohook_unlock(audiohook);
632                                 /* We basically drop all of our links to the manipulate audiohook and prod it to do it's own destructive things */
633                                 audiohook->manipulate_callback(audiohook, chan, NULL, direction);
634                                 continue;
635                         }
636                         /* Feed in frame to manipulation */
637                         audiohook->manipulate_callback(audiohook, chan, middle_frame, direction);
638                         ast_audiohook_unlock(audiohook);
639                 }
640                 AST_LIST_TRAVERSE_SAFE_END
641                 end_frame = middle_frame;
642         }
643
644         /* Now we figure out what to do with our end frame (whether to transcode or not) */
645         if (middle_frame == end_frame) {
646                 /* Middle frame was modified and became the end frame... let's see if we need to transcode */
647                 if (end_frame->subclass != start_frame->subclass) {
648                         if (out_translate->format != start_frame->subclass) {
649                                 if (out_translate->trans_pvt)
650                                         ast_translator_free_path(out_translate->trans_pvt);
651                                 if (!(out_translate->trans_pvt = ast_translator_build_path(start_frame->subclass, AST_FORMAT_SLINEAR))) {
652                                         /* We can't transcode this... drop our middle frame and return the original */
653                                         ast_frfree(middle_frame);
654                                         return start_frame;
655                                 }
656                                 out_translate->format = start_frame->subclass;
657                         }
658                         /* Transcode from our middle (signed linear) frame to new format of the frame that came in */
659                         if (!(end_frame = ast_translate(out_translate->trans_pvt, middle_frame, 0))) {
660                                 /* Failed to transcode the frame... drop it and return the original */
661                                 ast_frfree(middle_frame);
662                                 return start_frame;
663                         }
664                         /* Here's the scoop... middle frame is no longer of use to us */
665                         ast_frfree(middle_frame);
666                 }
667         } else {
668                 /* No frame was modified, we can just drop our middle frame and pass the frame we got in out */
669                 ast_frfree(middle_frame);
670         }
671
672         return end_frame;
673 }
674
675 /*! \brief Pass a frame off to be handled by the audiohook core
676  * \param chan Channel that the list is coming off of
677  * \param audiohook_list List of audiohooks
678  * \param direction Direction frame is coming in from
679  * \param frame The frame itself
680  * \return Return frame on success, NULL on failure
681  */
682 struct ast_frame *ast_audiohook_write_list(struct ast_channel *chan, struct ast_audiohook_list *audiohook_list, enum ast_audiohook_direction direction, struct ast_frame *frame)
683 {
684         /* Pass off frame to it's respective list write function */
685         if (frame->frametype == AST_FRAME_VOICE)
686                 return audio_audiohook_write_list(chan, audiohook_list, direction, frame);
687         else if (frame->frametype == AST_FRAME_DTMF)
688                 return dtmf_audiohook_write_list(chan, audiohook_list, direction, frame);
689         else
690                 return frame;
691 }
692                         
693
694 /*! \brief Wait for audiohook trigger to be triggered
695  * \param audiohook Audiohook to wait on
696  */
697 void ast_audiohook_trigger_wait(struct ast_audiohook *audiohook)
698 {
699         struct timeval wait;
700         struct timespec ts;
701
702         wait = ast_tvadd(ast_tvnow(), ast_samp2tv(50000, 1000));
703         ts.tv_sec = wait.tv_sec;
704         ts.tv_nsec = wait.tv_usec * 1000;
705         
706         ast_cond_timedwait(&audiohook->trigger, &audiohook->lock, &ts);
707         
708         return;
709 }
710
711 /* Count number of channel audiohooks by type, regardless of type */
712 int ast_channel_audiohook_count_by_source(struct ast_channel *chan, const char *source, enum ast_audiohook_type type)
713 {
714         int count = 0;
715         struct ast_audiohook *ah = NULL;
716
717         if (!chan->audiohooks)
718                 return -1;
719
720         switch (type) {
721                 case AST_AUDIOHOOK_TYPE_SPY:
722                         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->audiohooks->spy_list, ah, list) {
723                                 if (!strcmp(ah->source, source)) {
724                                         count++;
725                                 }
726                         }
727                         AST_LIST_TRAVERSE_SAFE_END;
728                         break;
729                 case AST_AUDIOHOOK_TYPE_WHISPER:
730                         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->audiohooks->whisper_list, ah, list) {
731                                 if (!strcmp(ah->source, source)) {
732                                         count++;
733                                 }
734                         }
735                         AST_LIST_TRAVERSE_SAFE_END;
736                         break;
737                 case AST_AUDIOHOOK_TYPE_MANIPULATE:
738                         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->audiohooks->manipulate_list, ah, list) {
739                                 if (!strcmp(ah->source, source)) {
740                                         count++;
741                                 }
742                         }
743                         AST_LIST_TRAVERSE_SAFE_END;
744                         break;
745                 default:
746                         ast_log(LOG_DEBUG, "Invalid audiohook type supplied, (%d)\n", type);
747                         return -1;
748         }
749
750         return count;
751 }
752
753 /* Count number of channel audiohooks by type that are running */
754 int ast_channel_audiohook_count_by_source_running(struct ast_channel *chan, const char *source, enum ast_audiohook_type type)
755 {
756         int count = 0;
757         struct ast_audiohook *ah = NULL;
758         if (!chan->audiohooks)
759                 return -1;
760
761         switch (type) {
762                 case AST_AUDIOHOOK_TYPE_SPY:
763                         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->audiohooks->spy_list, ah, list) {
764                                 if ((!strcmp(ah->source, source)) && (ah->status == AST_AUDIOHOOK_STATUS_RUNNING))
765                                         count++;
766                         }
767                         AST_LIST_TRAVERSE_SAFE_END;
768                         break;
769                 case AST_AUDIOHOOK_TYPE_WHISPER:
770                         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->audiohooks->whisper_list, ah, list) {
771                                 if ((!strcmp(ah->source, source)) && (ah->status == AST_AUDIOHOOK_STATUS_RUNNING))
772                                         count++;
773                         }
774                         AST_LIST_TRAVERSE_SAFE_END;
775                         break;
776                 case AST_AUDIOHOOK_TYPE_MANIPULATE:
777                         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->audiohooks->manipulate_list, ah, list) {
778                                 if ((!strcmp(ah->source, source)) && (ah->status == AST_AUDIOHOOK_STATUS_RUNNING))
779                                         count++;
780                         }
781                         AST_LIST_TRAVERSE_SAFE_END;
782                         break;
783                 default:
784                         ast_log(LOG_DEBUG, "Invalid audiohook type supplied, (%d)\n", type);
785                         return -1;
786         }
787         return count;
788 }
789
790 /*! \brief Audiohook volume adjustment structure */
791 struct audiohook_volume {
792         struct ast_audiohook audiohook; /*!< Audiohook attached to the channel */
793         int read_adjustment;            /*!< Value to adjust frames read from the channel by */
794         int write_adjustment;           /*!< Value to adjust frames written to the channel by */
795 };
796
797 /*! \brief Callback used to destroy the audiohook volume datastore
798  * \param data Volume information structure
799  * \return Returns nothing
800  */
801 static void audiohook_volume_destroy(void *data)
802 {
803         struct audiohook_volume *audiohook_volume = data;
804
805         /* Destroy the audiohook as it is no longer in use */
806         ast_audiohook_destroy(&audiohook_volume->audiohook);
807
808         /* Finally free ourselves, we are of no more use */
809         ast_free(audiohook_volume);
810
811         return;
812 }
813
814 /*! \brief Datastore used to store audiohook volume information */
815 static const struct ast_datastore_info audiohook_volume_datastore = {
816         .type = "Volume",
817         .destroy = audiohook_volume_destroy,
818 };
819
820 /*! \brief Helper function which actually gets called by audiohooks to perform the adjustment
821  * \param audiohook Audiohook attached to the channel
822  * \param chan Channel we are attached to
823  * \param frame Frame of audio we want to manipulate
824  * \param direction Direction the audio came in from
825  * \return Returns 0 on success, -1 on failure
826  */
827 static int audiohook_volume_callback(struct ast_audiohook *audiohook, struct ast_channel *chan, struct ast_frame *frame, enum ast_audiohook_direction direction)
828 {
829         struct ast_datastore *datastore = NULL;
830         struct audiohook_volume *audiohook_volume = NULL;
831         int *gain = NULL;
832
833         /* If the audiohook is shutting down don't even bother */
834         if (audiohook->status == AST_AUDIOHOOK_STATUS_DONE) {
835                 return 0;
836         }
837
838         /* Try to find the datastore containg adjustment information, if we can't just bail out */
839         if (!(datastore = ast_channel_datastore_find(chan, &audiohook_volume_datastore, NULL))) {
840                 return 0;
841         }
842
843         audiohook_volume = datastore->data;
844
845         /* Based on direction grab the appropriate adjustment value */
846         if (direction == AST_AUDIOHOOK_DIRECTION_READ) {
847                 gain = &audiohook_volume->read_adjustment;
848         } else if (direction == AST_AUDIOHOOK_DIRECTION_WRITE) {
849                 gain = &audiohook_volume->write_adjustment;
850         }
851
852         /* If an adjustment value is present modify the frame */
853         if (gain && *gain) {
854                 ast_frame_adjust_volume(frame, *gain);
855         }
856
857         return 0;
858 }
859
860 /*! \brief Helper function which finds and optionally creates an audiohook_volume_datastore datastore on a channel
861  * \param chan Channel to look on
862  * \param create Whether to create the datastore if not found
863  * \return Returns audiohook_volume structure on success, NULL on failure
864  */
865 static struct audiohook_volume *audiohook_volume_get(struct ast_channel *chan, int create)
866 {
867         struct ast_datastore *datastore = NULL;
868         struct audiohook_volume *audiohook_volume = NULL;
869
870         /* If we are able to find the datastore return the contents (which is actually an audiohook_volume structure) */
871         if ((datastore = ast_channel_datastore_find(chan, &audiohook_volume_datastore, NULL))) {
872                 return datastore->data;
873         }
874
875         /* If we are not allowed to create a datastore or if we fail to create a datastore, bail out now as we have nothing for them */
876         if (!create || !(datastore = ast_datastore_alloc(&audiohook_volume_datastore, NULL))) {
877                 return NULL;
878         }
879
880         /* Create a new audiohook_volume structure to contain our adjustments and audiohook */
881         if (!(audiohook_volume = ast_calloc(1, sizeof(*audiohook_volume)))) {
882                 ast_datastore_free(datastore);
883                 return NULL;
884         }
885
886         /* Setup our audiohook structure so we can manipulate the audio */
887         ast_audiohook_init(&audiohook_volume->audiohook, AST_AUDIOHOOK_TYPE_MANIPULATE, "Volume");
888         audiohook_volume->audiohook.manipulate_callback = audiohook_volume_callback;
889
890         /* Attach the audiohook_volume blob to the datastore and attach to the channel */
891         datastore->data = audiohook_volume;
892         ast_channel_datastore_add(chan, datastore);
893
894         /* All is well... put the audiohook into motion */
895         ast_audiohook_attach(chan, &audiohook_volume->audiohook);
896
897         return audiohook_volume;
898 }
899
900 /*! \brief Adjust the volume on frames read from or written to a channel
901  * \param chan Channel to muck with
902  * \param direction Direction to set on
903  * \param volume Value to adjust the volume by
904  * \return Returns 0 on success, -1 on failure
905  */
906 int ast_audiohook_volume_set(struct ast_channel *chan, enum ast_audiohook_direction direction, int volume)
907 {
908         struct audiohook_volume *audiohook_volume = NULL;
909
910         /* Attempt to find the audiohook volume information, but only create it if we are not setting the adjustment value to zero */
911         if (!(audiohook_volume = audiohook_volume_get(chan, (volume ? 1 : 0)))) {
912                 return -1;
913         }
914
915         /* Now based on the direction set the proper value */
916         if (direction == AST_AUDIOHOOK_DIRECTION_READ || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
917                 audiohook_volume->read_adjustment = volume;
918         } else if (direction == AST_AUDIOHOOK_DIRECTION_WRITE || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
919                 audiohook_volume->write_adjustment = volume;
920         }
921
922         return 0;
923 }
924
925 /*! \brief Retrieve the volume adjustment value on frames read from or written to a channel
926  * \param chan Channel to retrieve volume adjustment from
927  * \param direction Direction to retrieve
928  * \return Returns adjustment value
929  */
930 int ast_audiohook_volume_get(struct ast_channel *chan, enum ast_audiohook_direction direction)
931 {
932         struct audiohook_volume *audiohook_volume = NULL;
933         int adjustment = 0;
934
935         /* Attempt to find the audiohook volume information, but do not create it as we only want to look at the values */
936         if (!(audiohook_volume = audiohook_volume_get(chan, 0))) {
937                 return 0;
938         }
939
940         /* Grab the adjustment value based on direction given */
941         if (direction == AST_AUDIOHOOK_DIRECTION_READ) {
942                 adjustment = audiohook_volume->read_adjustment;
943         } else if (direction == AST_AUDIOHOOK_DIRECTION_WRITE) {
944                 adjustment = audiohook_volume->write_adjustment;
945         }
946
947         return adjustment;
948 }
949
950 /*! \brief Adjust the volume on frames read from or written to a channel
951  * \param chan Channel to muck with
952  * \param direction Direction to increase
953  * \param volume Value to adjust the adjustment by
954  * \return Returns 0 on success, -1 on failure
955  */
956 int ast_audiohook_volume_adjust(struct ast_channel *chan, enum ast_audiohook_direction direction, int volume)
957 {
958         struct audiohook_volume *audiohook_volume = NULL;
959
960         /* Attempt to find the audiohook volume information, and create an audiohook if none exists */
961         if (!(audiohook_volume = audiohook_volume_get(chan, 1))) {
962                 return -1;
963         }
964
965         /* Based on the direction change the specific adjustment value */
966         if (direction == AST_AUDIOHOOK_DIRECTION_READ || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
967                 audiohook_volume->read_adjustment += volume;
968         } else if (direction == AST_AUDIOHOOK_DIRECTION_WRITE || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
969                 audiohook_volume->write_adjustment += volume;
970         }
971
972         return 0;
973 }