Remove ASTERISK_REGISTER_FILE.
[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 Colp <jcolp@digium.com>
24  */
25
26 /*** MODULEINFO
27         <support_level>core</support_level>
28  ***/
29
30 #include "asterisk.h"
31
32 #include <signal.h>
33
34 #include "asterisk/channel.h"
35 #include "asterisk/utils.h"
36 #include "asterisk/lock.h"
37 #include "asterisk/linkedlists.h"
38 #include "asterisk/audiohook.h"
39 #include "asterisk/slinfactory.h"
40 #include "asterisk/frame.h"
41 #include "asterisk/translate.h"
42 #include "asterisk/format_cache.h"
43
44 #define AST_AUDIOHOOK_SYNC_TOLERANCE 100 /*!< Tolerance in milliseconds for audiohooks synchronization */
45 #define AST_AUDIOHOOK_SMALL_QUEUE_TOLERANCE 100 /*!< When small queue is enabled, this is the maximum amount of audio that can remain queued at a time. */
46 #define AST_AUDIOHOOK_LONG_QUEUE_TOLERANCE 500 /*!< Otheriwise we still don't want the queue to grow indefinitely */
47
48 #define DEFAULT_INTERNAL_SAMPLE_RATE 8000
49
50 struct ast_audiohook_translate {
51         struct ast_trans_pvt *trans_pvt;
52         struct ast_format *format;
53 };
54
55 struct ast_audiohook_list {
56         /* If all the audiohooks in this list are capable
57          * of processing slinear at any sample rate, this
58          * variable will be set and the sample rate will
59          * be preserved during ast_audiohook_write_list()*/
60         int native_slin_compatible;
61         int list_internal_samp_rate;/*!< Internal sample rate used when writing to the audiohook list */
62
63         struct ast_audiohook_translate in_translate[2];
64         struct ast_audiohook_translate out_translate[2];
65         AST_LIST_HEAD_NOLOCK(, ast_audiohook) spy_list;
66         AST_LIST_HEAD_NOLOCK(, ast_audiohook) whisper_list;
67         AST_LIST_HEAD_NOLOCK(, ast_audiohook) manipulate_list;
68 };
69
70 static int audiohook_set_internal_rate(struct ast_audiohook *audiohook, int rate, int reset)
71 {
72         struct ast_format *slin;
73
74         if (audiohook->hook_internal_samp_rate == rate) {
75                 return 0;
76         }
77
78         audiohook->hook_internal_samp_rate = rate;
79
80         slin = ast_format_cache_get_slin_by_rate(rate);
81
82         /* Setup the factories that are needed for this audiohook type */
83         switch (audiohook->type) {
84         case AST_AUDIOHOOK_TYPE_SPY:
85         case AST_AUDIOHOOK_TYPE_WHISPER:
86                 if (reset) {
87                         ast_slinfactory_destroy(&audiohook->read_factory);
88                         ast_slinfactory_destroy(&audiohook->write_factory);
89                 }
90                 ast_slinfactory_init_with_format(&audiohook->read_factory, slin);
91                 ast_slinfactory_init_with_format(&audiohook->write_factory, slin);
92                 break;
93         default:
94                 break;
95         }
96
97         return 0;
98 }
99
100 /*! \brief Initialize an audiohook structure
101  *
102  * \param audiohook Audiohook structure
103  * \param type
104  * \param source, init_flags
105  *
106  * \return Returns 0 on success, -1 on failure
107  */
108 int ast_audiohook_init(struct ast_audiohook *audiohook, enum ast_audiohook_type type, const char *source, enum ast_audiohook_init_flags init_flags)
109 {
110         /* Need to keep the type and source */
111         audiohook->type = type;
112         audiohook->source = source;
113
114         /* Initialize lock that protects our audiohook */
115         ast_mutex_init(&audiohook->lock);
116         ast_cond_init(&audiohook->trigger, NULL);
117
118         audiohook->init_flags = init_flags;
119
120         /* initialize internal rate at 8khz, this will adjust if necessary */
121         audiohook_set_internal_rate(audiohook, DEFAULT_INTERNAL_SAMPLE_RATE, 0);
122
123         /* Since we are just starting out... this audiohook is new */
124         ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_NEW);
125
126         return 0;
127 }
128
129 /*! \brief Destroys an audiohook structure
130  * \param audiohook Audiohook structure
131  * \return Returns 0 on success, -1 on failure
132  */
133 int ast_audiohook_destroy(struct ast_audiohook *audiohook)
134 {
135         /* Drop the factories used by this audiohook type */
136         switch (audiohook->type) {
137         case AST_AUDIOHOOK_TYPE_SPY:
138         case AST_AUDIOHOOK_TYPE_WHISPER:
139                 ast_slinfactory_destroy(&audiohook->read_factory);
140                 ast_slinfactory_destroy(&audiohook->write_factory);
141                 break;
142         default:
143                 break;
144         }
145
146         /* Destroy translation path if present */
147         if (audiohook->trans_pvt)
148                 ast_translator_free_path(audiohook->trans_pvt);
149
150         ao2_cleanup(audiohook->format);
151
152         /* Lock and trigger be gone! */
153         ast_cond_destroy(&audiohook->trigger);
154         ast_mutex_destroy(&audiohook->lock);
155
156         return 0;
157 }
158
159 /*! \brief Writes a frame into the audiohook structure
160  * \param audiohook Audiohook structure
161  * \param direction Direction the audio frame came from
162  * \param frame Frame to write in
163  * \return Returns 0 on success, -1 on failure
164  */
165 int ast_audiohook_write_frame(struct ast_audiohook *audiohook, enum ast_audiohook_direction direction, struct ast_frame *frame)
166 {
167         struct ast_slinfactory *factory = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook->read_factory : &audiohook->write_factory);
168         struct ast_slinfactory *other_factory = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook->write_factory : &audiohook->read_factory);
169         struct timeval *rwtime = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook->read_time : &audiohook->write_time), previous_time = *rwtime;
170         int our_factory_samples;
171         int our_factory_ms;
172         int other_factory_samples;
173         int other_factory_ms;
174         int muteme = 0;
175
176         /* Update last feeding time to be current */
177         *rwtime = ast_tvnow();
178
179         our_factory_samples = ast_slinfactory_available(factory);
180         our_factory_ms = ast_tvdiff_ms(*rwtime, previous_time) + (our_factory_samples / (audiohook->hook_internal_samp_rate / 1000));
181         other_factory_samples = ast_slinfactory_available(other_factory);
182         other_factory_ms = other_factory_samples / (audiohook->hook_internal_samp_rate / 1000);
183
184         if (ast_test_flag(audiohook, AST_AUDIOHOOK_TRIGGER_SYNC) && other_factory_samples && (our_factory_ms - other_factory_ms > AST_AUDIOHOOK_SYNC_TOLERANCE)) {
185                 ast_debug(1, "Flushing audiohook %p so it remains in sync\n", audiohook);
186                 ast_slinfactory_flush(factory);
187                 ast_slinfactory_flush(other_factory);
188         }
189
190         if (ast_test_flag(audiohook, AST_AUDIOHOOK_SMALL_QUEUE) && ((our_factory_ms > AST_AUDIOHOOK_SMALL_QUEUE_TOLERANCE) || (other_factory_ms > AST_AUDIOHOOK_SMALL_QUEUE_TOLERANCE))) {
191                 ast_debug(1, "Audiohook %p has stale audio in its factories. Flushing them both\n", audiohook);
192                 ast_slinfactory_flush(factory);
193                 ast_slinfactory_flush(other_factory);
194         } else if ((our_factory_ms > AST_AUDIOHOOK_LONG_QUEUE_TOLERANCE) || (other_factory_ms > AST_AUDIOHOOK_LONG_QUEUE_TOLERANCE)) {
195                 ast_debug(1, "Audiohook %p has stale audio in its factories. Flushing them both\n", audiohook);
196                 ast_slinfactory_flush(factory);
197                 ast_slinfactory_flush(other_factory);
198         }
199
200         /* swap frame data for zeros if mute is required */
201         if ((ast_test_flag(audiohook, AST_AUDIOHOOK_MUTE_READ) && (direction == AST_AUDIOHOOK_DIRECTION_READ)) ||
202                 (ast_test_flag(audiohook, AST_AUDIOHOOK_MUTE_WRITE) && (direction == AST_AUDIOHOOK_DIRECTION_WRITE)) ||
203                 (ast_test_flag(audiohook, AST_AUDIOHOOK_MUTE_READ | AST_AUDIOHOOK_MUTE_WRITE) == (AST_AUDIOHOOK_MUTE_READ | AST_AUDIOHOOK_MUTE_WRITE))) {
204                         muteme = 1;
205         }
206
207         if (muteme && frame->datalen > 0) {
208                 ast_frame_clear(frame);
209         }
210
211         /* Write frame out to respective factory */
212         ast_slinfactory_feed(factory, frame);
213
214         /* If we need to notify the respective handler of this audiohook, do so */
215         if ((ast_test_flag(audiohook, AST_AUDIOHOOK_TRIGGER_MODE) == AST_AUDIOHOOK_TRIGGER_READ) && (direction == AST_AUDIOHOOK_DIRECTION_READ)) {
216                 ast_cond_signal(&audiohook->trigger);
217         } else if ((ast_test_flag(audiohook, AST_AUDIOHOOK_TRIGGER_MODE) == AST_AUDIOHOOK_TRIGGER_WRITE) && (direction == AST_AUDIOHOOK_DIRECTION_WRITE)) {
218                 ast_cond_signal(&audiohook->trigger);
219         } else if (ast_test_flag(audiohook, AST_AUDIOHOOK_TRIGGER_SYNC)) {
220                 ast_cond_signal(&audiohook->trigger);
221         }
222
223         return 0;
224 }
225
226 static struct ast_frame *audiohook_read_frame_single(struct ast_audiohook *audiohook, size_t samples, enum ast_audiohook_direction direction)
227 {
228         struct ast_slinfactory *factory = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook->read_factory : &audiohook->write_factory);
229         int vol = (direction == AST_AUDIOHOOK_DIRECTION_READ ? audiohook->options.read_volume : audiohook->options.write_volume);
230         short buf[samples];
231         struct ast_frame frame = {
232                 .frametype = AST_FRAME_VOICE,
233                 .subclass.format = ast_format_cache_get_slin_by_rate(audiohook->hook_internal_samp_rate),
234                 .data.ptr = buf,
235                 .datalen = sizeof(buf),
236                 .samples = samples,
237         };
238
239         /* Ensure the factory is able to give us the samples we want */
240         if (samples > ast_slinfactory_available(factory)) {
241                 return NULL;
242         }
243
244         /* Read data in from factory */
245         if (!ast_slinfactory_read(factory, buf, samples)) {
246                 return NULL;
247         }
248
249         /* If a volume adjustment needs to be applied apply it */
250         if (vol) {
251                 ast_frame_adjust_volume(&frame, vol);
252         }
253
254         return ast_frdup(&frame);
255 }
256
257 static struct ast_frame *audiohook_read_frame_both(struct ast_audiohook *audiohook, size_t samples, struct ast_frame **read_reference, struct ast_frame **write_reference)
258 {
259         int count;
260         int usable_read;
261         int usable_write;
262         short adjust_value;
263         short buf1[samples];
264         short buf2[samples];
265         short *read_buf = NULL;
266         short *write_buf = NULL;
267         struct ast_frame frame = {
268                 .frametype = AST_FRAME_VOICE,
269                 .datalen = sizeof(buf1),
270                 .samples = samples,
271         };
272
273         /* Make sure both factories have the required samples */
274         usable_read = (ast_slinfactory_available(&audiohook->read_factory) >= samples ? 1 : 0);
275         usable_write = (ast_slinfactory_available(&audiohook->write_factory) >= samples ? 1 : 0);
276
277         if (!usable_read && !usable_write) {
278                 /* If both factories are unusable bail out */
279                 ast_debug(1, "Read factory %p and write factory %p both fail to provide %zu samples\n", &audiohook->read_factory, &audiohook->write_factory, samples);
280                 return NULL;
281         }
282
283         /* If we want to provide only a read factory make sure we aren't waiting for other audio */
284         if (usable_read && !usable_write && (ast_tvdiff_ms(ast_tvnow(), audiohook->write_time) < (samples/8)*2)) {
285                 ast_debug(3, "Write factory %p was pretty quick last time, waiting for them.\n", &audiohook->write_factory);
286                 return NULL;
287         }
288
289         /* If we want to provide only a write factory make sure we aren't waiting for other audio */
290         if (usable_write && !usable_read && (ast_tvdiff_ms(ast_tvnow(), audiohook->read_time) < (samples/8)*2)) {
291                 ast_debug(3, "Read factory %p was pretty quick last time, waiting for them.\n", &audiohook->read_factory);
292                 return NULL;
293         }
294
295         /* Start with the read factory... if there are enough samples, read them in */
296         if (usable_read) {
297                 if (ast_slinfactory_read(&audiohook->read_factory, buf1, samples)) {
298                         read_buf = buf1;
299                         /* Adjust read volume if need be */
300                         if (audiohook->options.read_volume) {
301                                 adjust_value = abs(audiohook->options.read_volume);
302                                 for (count = 0; count < samples; count++) {
303                                         if (audiohook->options.read_volume > 0) {
304                                                 ast_slinear_saturated_multiply(&buf1[count], &adjust_value);
305                                         } else if (audiohook->options.read_volume < 0) {
306                                                 ast_slinear_saturated_divide(&buf1[count], &adjust_value);
307                                         }
308                                 }
309                         }
310                 }
311         } else {
312                 ast_debug(1, "Failed to get %d samples from read factory %p\n", (int)samples, &audiohook->read_factory);
313         }
314
315         /* Move on to the write factory... if there are enough samples, read them in */
316         if (usable_write) {
317                 if (ast_slinfactory_read(&audiohook->write_factory, buf2, samples)) {
318                         write_buf = buf2;
319                         /* Adjust write volume if need be */
320                         if (audiohook->options.write_volume) {
321                                 adjust_value = abs(audiohook->options.write_volume);
322                                 for (count = 0; count < samples; count++) {
323                                         if (audiohook->options.write_volume > 0) {
324                                                 ast_slinear_saturated_multiply(&buf2[count], &adjust_value);
325                                         } else if (audiohook->options.write_volume < 0) {
326                                                 ast_slinear_saturated_divide(&buf2[count], &adjust_value);
327                                         }
328                                 }
329                         }
330                 }
331         } else {
332                 ast_debug(1, "Failed to get %d samples from write factory %p\n", (int)samples, &audiohook->write_factory);
333         }
334
335         frame.subclass.format = ast_format_cache_get_slin_by_rate(audiohook->hook_internal_samp_rate);
336
337         /* Basically we figure out which buffer to use... and if mixing can be done here */
338         if (read_buf && read_reference) {
339                 frame.data.ptr = read_buf;
340                 *read_reference = ast_frdup(&frame);
341         }
342         if (write_buf && write_reference) {
343                 frame.data.ptr = write_buf;
344                 *write_reference = ast_frdup(&frame);
345         }
346
347         /* Make the correct buffer part of the built frame, so it gets duplicated. */
348         if (read_buf) {
349                 frame.data.ptr = read_buf;
350                 if (write_buf) {
351                         for (count = 0; count < samples; count++) {
352                                 ast_slinear_saturated_add(read_buf++, write_buf++);
353                         }
354                 }
355         } else if (write_buf) {
356                 frame.data.ptr = write_buf;
357         } else {
358                 return NULL;
359         }
360
361         /* Yahoo, a combined copy of the audio! */
362         return ast_frdup(&frame);
363 }
364
365 static struct ast_frame *audiohook_read_frame_helper(struct ast_audiohook *audiohook, size_t samples, enum ast_audiohook_direction direction, struct ast_format *format, struct ast_frame **read_reference, struct ast_frame **write_reference)
366 {
367         struct ast_frame *read_frame = NULL, *final_frame = NULL;
368         struct ast_format *slin;
369
370         /*
371          * Update the rate if compatibility mode is turned off or if it is
372          * turned on and the format rate is higher than the current rate.
373          *
374          * This makes it so any unnecessary rate switching/resetting does
375          * not take place and also any associated audiohook_list's internal
376          * sample rate maintains the highest sample rate between hooks.
377          */
378         if (!ast_test_flag(audiohook, AST_AUDIOHOOK_COMPATIBLE) ||
379             (ast_test_flag(audiohook, AST_AUDIOHOOK_COMPATIBLE) &&
380               ast_format_get_sample_rate(format) > audiohook->hook_internal_samp_rate)) {
381                 audiohook_set_internal_rate(audiohook, ast_format_get_sample_rate(format), 1);
382         }
383
384         /* If the sample rate of the requested format differs from that of the underlying audiohook
385          * sample rate determine how many samples we actually need to get from the audiohook. This
386          * needs to occur as the signed linear factory stores them at the rate of the audiohook.
387          * We do this by determining the duration of audio they've requested and then determining
388          * how many samples that would be in the audiohook format.
389          */
390         if (ast_format_get_sample_rate(format) != audiohook->hook_internal_samp_rate) {
391                 samples = (audiohook->hook_internal_samp_rate / 1000) * (samples / (ast_format_get_sample_rate(format) / 1000));
392         }
393
394         if (!(read_frame = (direction == AST_AUDIOHOOK_DIRECTION_BOTH ?
395                 audiohook_read_frame_both(audiohook, samples, read_reference, write_reference) :
396                 audiohook_read_frame_single(audiohook, samples, direction)))) {
397                 return NULL;
398         }
399
400         slin = ast_format_cache_get_slin_by_rate(audiohook->hook_internal_samp_rate);
401
402         /* If they don't want signed linear back out, we'll have to send it through the translation path */
403         if (ast_format_cmp(format, slin) != AST_FORMAT_CMP_EQUAL) {
404                 /* Rebuild translation path if different format then previously */
405                 if (ast_format_cmp(format, audiohook->format) == AST_FORMAT_CMP_NOT_EQUAL) {
406                         if (audiohook->trans_pvt) {
407                                 ast_translator_free_path(audiohook->trans_pvt);
408                                 audiohook->trans_pvt = NULL;
409                         }
410
411                         /* 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 */
412                         if (!(audiohook->trans_pvt = ast_translator_build_path(format, slin))) {
413                                 ast_frfree(read_frame);
414                                 return NULL;
415                         }
416                         ao2_replace(audiohook->format, format);
417                 }
418                 /* Convert to requested format, and allow the read in frame to be freed */
419                 final_frame = ast_translate(audiohook->trans_pvt, read_frame, 1);
420         } else {
421                 final_frame = read_frame;
422         }
423
424         return final_frame;
425 }
426
427 /*! \brief Reads a frame in from the audiohook structure
428  * \param audiohook Audiohook structure
429  * \param samples Number of samples wanted in requested output format
430  * \param direction Direction the audio frame came from
431  * \param format Format of frame remote side wants back
432  * \return Returns frame on success, NULL on failure
433  */
434 struct ast_frame *ast_audiohook_read_frame(struct ast_audiohook *audiohook, size_t samples, enum ast_audiohook_direction direction, struct ast_format *format)
435 {
436         return audiohook_read_frame_helper(audiohook, samples, direction, format, NULL, NULL);
437 }
438
439 /*! \brief Reads a frame in from the audiohook structure
440  * \param audiohook Audiohook structure
441  * \param samples Number of samples wanted
442  * \param direction Direction the audio frame came from
443  * \param format Format of frame remote side wants back
444  * \param read_frame frame pointer for copying read frame data
445  * \param write_frame frame pointer for copying write frame data
446  * \return Returns frame on success, NULL on failure
447  */
448 struct ast_frame *ast_audiohook_read_frame_all(struct ast_audiohook *audiohook, size_t samples, struct ast_format *format, struct ast_frame **read_frame, struct ast_frame **write_frame)
449 {
450         return audiohook_read_frame_helper(audiohook, samples, AST_AUDIOHOOK_DIRECTION_BOTH, format, read_frame, write_frame);
451 }
452
453 static void audiohook_list_set_samplerate_compatibility(struct ast_audiohook_list *audiohook_list)
454 {
455         struct ast_audiohook *ah = NULL;
456
457         /*
458          * Anytime the samplerate compatibility is set (attach/remove an audiohook) the
459          * list's internal sample rate needs to be reset so that the next time processing
460          * through write_list, if needed, it will get updated to the correct rate.
461          *
462          * A list's internal rate always chooses the higher between its own rate and a
463          * given rate. If the current rate is being driven by an audiohook that wanted a
464          * higher rate then when this audiohook is removed the list's rate would remain
465          * at that level when it should be lower, and with no way to lower it since any
466          * rate compared against it would be lower.
467          *
468          * By setting it back to the lowest rate it can recalulate the new highest rate.
469          */
470         audiohook_list->list_internal_samp_rate = DEFAULT_INTERNAL_SAMPLE_RATE;
471
472         audiohook_list->native_slin_compatible = 1;
473         AST_LIST_TRAVERSE(&audiohook_list->manipulate_list, ah, list) {
474                 if (!(ah->init_flags & AST_AUDIOHOOK_MANIPULATE_ALL_RATES)) {
475                         audiohook_list->native_slin_compatible = 0;
476                         return;
477                 }
478         }
479 }
480
481 /*! \brief Attach audiohook to channel
482  * \param chan Channel
483  * \param audiohook Audiohook structure
484  * \return Returns 0 on success, -1 on failure
485  */
486 int ast_audiohook_attach(struct ast_channel *chan, struct ast_audiohook *audiohook)
487 {
488         ast_channel_lock(chan);
489
490         if (!ast_channel_audiohooks(chan)) {
491                 struct ast_audiohook_list *ahlist;
492                 /* Whoops... allocate a new structure */
493                 if (!(ahlist = ast_calloc(1, sizeof(*ahlist)))) {
494                         ast_channel_unlock(chan);
495                         return -1;
496                 }
497                 ast_channel_audiohooks_set(chan, ahlist);
498                 AST_LIST_HEAD_INIT_NOLOCK(&ast_channel_audiohooks(chan)->spy_list);
499                 AST_LIST_HEAD_INIT_NOLOCK(&ast_channel_audiohooks(chan)->whisper_list);
500                 AST_LIST_HEAD_INIT_NOLOCK(&ast_channel_audiohooks(chan)->manipulate_list);
501                 /* This sample rate will adjust as necessary when writing to the list. */
502                 ast_channel_audiohooks(chan)->list_internal_samp_rate = DEFAULT_INTERNAL_SAMPLE_RATE;
503         }
504
505         /* Drop into respective list */
506         if (audiohook->type == AST_AUDIOHOOK_TYPE_SPY) {
507                 AST_LIST_INSERT_TAIL(&ast_channel_audiohooks(chan)->spy_list, audiohook, list);
508         } else if (audiohook->type == AST_AUDIOHOOK_TYPE_WHISPER) {
509                 AST_LIST_INSERT_TAIL(&ast_channel_audiohooks(chan)->whisper_list, audiohook, list);
510         } else if (audiohook->type == AST_AUDIOHOOK_TYPE_MANIPULATE) {
511                 AST_LIST_INSERT_TAIL(&ast_channel_audiohooks(chan)->manipulate_list, audiohook, list);
512         }
513
514         /*
515          * Initialize the audiohook's rate to the default. If it needs to be,
516          * it will get updated later.
517          */
518         audiohook_set_internal_rate(audiohook, DEFAULT_INTERNAL_SAMPLE_RATE, 1);
519         audiohook_list_set_samplerate_compatibility(ast_channel_audiohooks(chan));
520
521         /* Change status over to running since it is now attached */
522         ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_RUNNING);
523
524         if (ast_channel_is_bridged(chan)) {
525                 ast_channel_set_unbridged_nolock(chan, 1);
526         }
527
528         ast_channel_unlock(chan);
529
530         return 0;
531 }
532
533 /*! \brief Update audiohook's status
534  * \param audiohook Audiohook structure
535  * \param status Audiohook status enum
536  *
537  * \note once status is updated to DONE, this function can not be used to set the
538  * status back to any other setting.  Setting DONE effectively locks the status as such.
539  */
540
541 void ast_audiohook_update_status(struct ast_audiohook *audiohook, enum ast_audiohook_status status)
542 {
543         ast_audiohook_lock(audiohook);
544         if (audiohook->status != AST_AUDIOHOOK_STATUS_DONE) {
545                 audiohook->status = status;
546                 ast_cond_signal(&audiohook->trigger);
547         }
548         ast_audiohook_unlock(audiohook);
549 }
550
551 /*! \brief Detach audiohook from channel
552  * \param audiohook Audiohook structure
553  * \return Returns 0 on success, -1 on failure
554  */
555 int ast_audiohook_detach(struct ast_audiohook *audiohook)
556 {
557         if (audiohook->status == AST_AUDIOHOOK_STATUS_NEW || audiohook->status == AST_AUDIOHOOK_STATUS_DONE) {
558                 return 0;
559         }
560
561         ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_SHUTDOWN);
562
563         while (audiohook->status != AST_AUDIOHOOK_STATUS_DONE) {
564                 ast_audiohook_trigger_wait(audiohook);
565         }
566
567         return 0;
568 }
569
570 void ast_audiohook_detach_list(struct ast_audiohook_list *audiohook_list)
571 {
572         int i;
573         struct ast_audiohook *audiohook;
574
575         if (!audiohook_list) {
576                 return;
577         }
578
579         /* Drop any spies */
580         while ((audiohook = AST_LIST_REMOVE_HEAD(&audiohook_list->spy_list, list))) {
581                 ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
582         }
583
584         /* Drop any whispering sources */
585         while ((audiohook = AST_LIST_REMOVE_HEAD(&audiohook_list->whisper_list, list))) {
586                 ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
587         }
588
589         /* Drop any manipulaters */
590         while ((audiohook = AST_LIST_REMOVE_HEAD(&audiohook_list->manipulate_list, list))) {
591                 ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
592                 audiohook->manipulate_callback(audiohook, NULL, NULL, 0);
593         }
594
595         /* Drop translation paths if present */
596         for (i = 0; i < 2; i++) {
597                 if (audiohook_list->in_translate[i].trans_pvt) {
598                         ast_translator_free_path(audiohook_list->in_translate[i].trans_pvt);
599                         ao2_cleanup(audiohook_list->in_translate[i].format);
600                 }
601                 if (audiohook_list->out_translate[i].trans_pvt) {
602                         ast_translator_free_path(audiohook_list->out_translate[i].trans_pvt);
603                         ao2_cleanup(audiohook_list->in_translate[i].format);
604                 }
605         }
606
607         /* Free ourselves */
608         ast_free(audiohook_list);
609 }
610
611 /*! \brief find an audiohook based on its source
612  * \param audiohook_list The list of audiohooks to search in
613  * \param source The source of the audiohook we wish to find
614  * \return Return the corresponding audiohook or NULL if it cannot be found.
615  */
616 static struct ast_audiohook *find_audiohook_by_source(struct ast_audiohook_list *audiohook_list, const char *source)
617 {
618         struct ast_audiohook *audiohook = NULL;
619
620         AST_LIST_TRAVERSE(&audiohook_list->spy_list, audiohook, list) {
621                 if (!strcasecmp(audiohook->source, source)) {
622                         return audiohook;
623                 }
624         }
625
626         AST_LIST_TRAVERSE(&audiohook_list->whisper_list, audiohook, list) {
627                 if (!strcasecmp(audiohook->source, source)) {
628                         return audiohook;
629                 }
630         }
631
632         AST_LIST_TRAVERSE(&audiohook_list->manipulate_list, audiohook, list) {
633                 if (!strcasecmp(audiohook->source, source)) {
634                         return audiohook;
635                 }
636         }
637
638         return NULL;
639 }
640
641 static void audiohook_move(struct ast_channel *old_chan, struct ast_channel *new_chan, struct ast_audiohook *audiohook)
642 {
643         enum ast_audiohook_status oldstatus;
644
645         /* By locking both channels and the audiohook, we can assure that
646          * another thread will not have a chance to read the audiohook's status
647          * as done, even though ast_audiohook_remove signals the trigger
648          * condition.
649          */
650         ast_audiohook_lock(audiohook);
651         oldstatus = audiohook->status;
652
653         ast_audiohook_remove(old_chan, audiohook);
654         ast_audiohook_attach(new_chan, audiohook);
655
656         audiohook->status = oldstatus;
657         ast_audiohook_unlock(audiohook);
658 }
659
660 void ast_audiohook_move_by_source(struct ast_channel *old_chan, struct ast_channel *new_chan, const char *source)
661 {
662         struct ast_audiohook *audiohook;
663
664         if (!ast_channel_audiohooks(old_chan)) {
665                 return;
666         }
667
668         audiohook = find_audiohook_by_source(ast_channel_audiohooks(old_chan), source);
669         if (!audiohook) {
670                 return;
671         }
672
673         audiohook_move(old_chan, new_chan, audiohook);
674 }
675
676 void ast_audiohook_move_all(struct ast_channel *old_chan, struct ast_channel *new_chan)
677 {
678         struct ast_audiohook *audiohook;
679         struct ast_audiohook_list *audiohook_list;
680
681         audiohook_list = ast_channel_audiohooks(old_chan);
682         if (!audiohook_list) {
683                 return;
684         }
685
686         AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->spy_list, audiohook, list) {
687                 audiohook_move(old_chan, new_chan, audiohook);
688         }
689         AST_LIST_TRAVERSE_SAFE_END;
690
691         AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->whisper_list, audiohook, list) {
692                 audiohook_move(old_chan, new_chan, audiohook);
693         }
694         AST_LIST_TRAVERSE_SAFE_END;
695
696         AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->manipulate_list, audiohook, list) {
697                 audiohook_move(old_chan, new_chan, audiohook);
698         }
699         AST_LIST_TRAVERSE_SAFE_END;
700 }
701
702 /*! \brief Detach specified source audiohook from channel
703  * \param chan Channel to detach from
704  * \param source Name of source to detach
705  * \return Returns 0 on success, -1 on failure
706  */
707 int ast_audiohook_detach_source(struct ast_channel *chan, const char *source)
708 {
709         struct ast_audiohook *audiohook = NULL;
710
711         ast_channel_lock(chan);
712
713         /* Ensure the channel has audiohooks on it */
714         if (!ast_channel_audiohooks(chan)) {
715                 ast_channel_unlock(chan);
716                 return -1;
717         }
718
719         audiohook = find_audiohook_by_source(ast_channel_audiohooks(chan), source);
720
721         ast_channel_unlock(chan);
722
723         if (audiohook && audiohook->status != AST_AUDIOHOOK_STATUS_DONE) {
724                 ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_SHUTDOWN);
725         }
726
727         return (audiohook ? 0 : -1);
728 }
729
730 /*!
731  * \brief Remove an audiohook from a specified channel
732  *
733  * \param chan Channel to remove from
734  * \param audiohook Audiohook to remove
735  *
736  * \return Returns 0 on success, -1 on failure
737  *
738  * \note The channel does not need to be locked before calling this function
739  */
740 int ast_audiohook_remove(struct ast_channel *chan, struct ast_audiohook *audiohook)
741 {
742         ast_channel_lock(chan);
743
744         if (!ast_channel_audiohooks(chan)) {
745                 ast_channel_unlock(chan);
746                 return -1;
747         }
748
749         if (audiohook->type == AST_AUDIOHOOK_TYPE_SPY) {
750                 AST_LIST_REMOVE(&ast_channel_audiohooks(chan)->spy_list, audiohook, list);
751         } else if (audiohook->type == AST_AUDIOHOOK_TYPE_WHISPER) {
752                 AST_LIST_REMOVE(&ast_channel_audiohooks(chan)->whisper_list, audiohook, list);
753         } else if (audiohook->type == AST_AUDIOHOOK_TYPE_MANIPULATE) {
754                 AST_LIST_REMOVE(&ast_channel_audiohooks(chan)->manipulate_list, audiohook, list);
755         }
756
757         audiohook_list_set_samplerate_compatibility(ast_channel_audiohooks(chan));
758         ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
759
760         if (ast_channel_is_bridged(chan)) {
761                 ast_channel_set_unbridged_nolock(chan, 1);
762         }
763
764         ast_channel_unlock(chan);
765
766         return 0;
767 }
768
769 /*! \brief Pass a DTMF frame off to be handled by the audiohook core
770  * \param chan Channel that the list is coming off of
771  * \param audiohook_list List of audiohooks
772  * \param direction Direction frame is coming in from
773  * \param frame The frame itself
774  * \return Return frame on success, NULL on failure
775  */
776 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)
777 {
778         struct ast_audiohook *audiohook = NULL;
779         int removed = 0;
780
781         AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->manipulate_list, audiohook, list) {
782                 ast_audiohook_lock(audiohook);
783                 if (audiohook->status != AST_AUDIOHOOK_STATUS_RUNNING) {
784                         AST_LIST_REMOVE_CURRENT(list);
785                         removed = 1;
786                         ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
787                         ast_audiohook_unlock(audiohook);
788                         audiohook->manipulate_callback(audiohook, NULL, NULL, 0);
789                         if (ast_channel_is_bridged(chan)) {
790                                 ast_channel_set_unbridged_nolock(chan, 1);
791                         }
792                         continue;
793                 }
794                 if (ast_test_flag(audiohook, AST_AUDIOHOOK_WANTS_DTMF)) {
795                         audiohook->manipulate_callback(audiohook, chan, frame, direction);
796                 }
797                 ast_audiohook_unlock(audiohook);
798         }
799         AST_LIST_TRAVERSE_SAFE_END;
800
801         /* if an audiohook got removed, reset samplerate compatibility */
802         if (removed) {
803                 audiohook_list_set_samplerate_compatibility(audiohook_list);
804         }
805         return frame;
806 }
807
808 static struct ast_frame *audiohook_list_translate_to_slin(struct ast_audiohook_list *audiohook_list,
809         enum ast_audiohook_direction direction, struct ast_frame *frame)
810 {
811         struct ast_audiohook_translate *in_translate = (direction == AST_AUDIOHOOK_DIRECTION_READ ?
812                 &audiohook_list->in_translate[0] : &audiohook_list->in_translate[1]);
813         struct ast_frame *new_frame = frame;
814         struct ast_format *slin;
815
816         /*
817          * If we are capable of sample rates other that 8khz, update the internal
818          * audiohook_list's rate and higher sample rate audio arrives. If native
819          * slin compatibility is turned on all audiohooks in the list will be
820          * updated as well during read/write processing.
821          */
822         audiohook_list->list_internal_samp_rate =
823                 MAX(ast_format_get_sample_rate(frame->subclass.format), audiohook_list->list_internal_samp_rate);
824
825         slin = ast_format_cache_get_slin_by_rate(audiohook_list->list_internal_samp_rate);
826         if (ast_format_cmp(frame->subclass.format, slin) == AST_FORMAT_CMP_EQUAL) {
827                 return new_frame;
828         }
829
830         if (!in_translate->format ||
831                 ast_format_cmp(frame->subclass.format, in_translate->format) != AST_FORMAT_CMP_EQUAL) {
832                 struct ast_trans_pvt *new_trans;
833
834                 new_trans = ast_translator_build_path(slin, frame->subclass.format);
835                 if (!new_trans) {
836                         return NULL;
837                 }
838
839                 if (in_translate->trans_pvt) {
840                         ast_translator_free_path(in_translate->trans_pvt);
841                 }
842                 in_translate->trans_pvt = new_trans;
843
844                 ao2_replace(in_translate->format, frame->subclass.format);
845         }
846
847         if (!(new_frame = ast_translate(in_translate->trans_pvt, frame, 0))) {
848                 return NULL;
849         }
850
851         return new_frame;
852 }
853
854 static struct ast_frame *audiohook_list_translate_to_native(struct ast_audiohook_list *audiohook_list,
855         enum ast_audiohook_direction direction, struct ast_frame *slin_frame, struct ast_format *outformat)
856 {
857         struct ast_audiohook_translate *out_translate = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook_list->out_translate[0] : &audiohook_list->out_translate[1]);
858         struct ast_frame *outframe = NULL;
859         if (ast_format_cmp(slin_frame->subclass.format, outformat) == AST_FORMAT_CMP_NOT_EQUAL) {
860                 /* rebuild translators if necessary */
861                 if (ast_format_cmp(out_translate->format, outformat) == AST_FORMAT_CMP_NOT_EQUAL) {
862                         if (out_translate->trans_pvt) {
863                                 ast_translator_free_path(out_translate->trans_pvt);
864                         }
865                         if (!(out_translate->trans_pvt = ast_translator_build_path(outformat, slin_frame->subclass.format))) {
866                                 return NULL;
867                         }
868                         ao2_replace(out_translate->format, outformat);
869                 }
870                 /* translate back to the format the frame came in as. */
871                 if (!(outframe = ast_translate(out_translate->trans_pvt, slin_frame, 0))) {
872                         return NULL;
873                 }
874         }
875         return outframe;
876 }
877
878 /*!
879  *\brief Set the audiohook's internal sample rate to the audiohook_list's rate,
880  *       but only when native slin compatibility is turned on.
881  *
882  * \param audiohook_list audiohook_list data object
883  * \param audiohook the audiohook to update
884  * \param rate the current max internal sample rate
885  */
886 static void audiohook_list_set_hook_rate(struct ast_audiohook_list *audiohook_list,
887                                          struct ast_audiohook *audiohook, int *rate)
888 {
889         /* The rate should always be the max between itself and the hook */
890         if (audiohook->hook_internal_samp_rate > *rate) {
891                 *rate = audiohook->hook_internal_samp_rate;
892         }
893
894         /*
895          * If native slin compatibility is turned on then update the audiohook
896          * with the audiohook_list's current rate. Note, the audiohook's rate is
897          * set to the audiohook_list's rate and not the given rate. If there is
898          * a change in rate the hook's rate is changed on its next check.
899          */
900         if (audiohook_list->native_slin_compatible) {
901                 ast_set_flag(audiohook, AST_AUDIOHOOK_COMPATIBLE);
902                 audiohook_set_internal_rate(audiohook, audiohook_list->list_internal_samp_rate, 1);
903         } else {
904                 ast_clear_flag(audiohook, AST_AUDIOHOOK_COMPATIBLE);
905         }
906 }
907
908 /*!
909  * \brief Pass an AUDIO frame off to be handled by the audiohook core
910  *
911  * \details
912  * This function has 3 ast_frames and 3 parts to handle each.  At the beginning of this
913  * function all 3 frames, start_frame, middle_frame, and end_frame point to the initial
914  * input frame.
915  *
916  * Part_1: Translate the start_frame into SLINEAR audio if it is not already in that
917  *         format.  The result of this part is middle_frame is guaranteed to be in
918  *         SLINEAR format for Part_2.
919  * Part_2: Send middle_frame off to spies and manipulators.  At this point middle_frame is
920  *         either a new frame as result of the translation, or points directly to the start_frame
921  *         because no translation to SLINEAR audio was required.
922  * Part_3: Translate end_frame's audio back into the format of start frame if necessary.  This
923  *         is only necessary if manipulation of middle_frame occurred.
924  *
925  * \param chan Channel that the list is coming off of
926  * \param audiohook_list List of audiohooks
927  * \param direction Direction frame is coming in from
928  * \param frame The frame itself
929  * \return Return frame on success, NULL on failure
930  */
931 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)
932 {
933         struct ast_frame *start_frame = frame, *middle_frame = frame, *end_frame = frame;
934         struct ast_audiohook *audiohook = NULL;
935         int samples;
936         int middle_frame_manipulated = 0;
937         int removed = 0;
938         int internal_sample_rate;
939
940         /* ---Part_1. translate start_frame to SLINEAR if necessary. */
941         if (!(middle_frame = audiohook_list_translate_to_slin(audiohook_list, direction, start_frame))) {
942                 return frame;
943         }
944         samples = middle_frame->samples;
945
946         /*
947          * While processing each audiohook check to see if the internal sample rate needs
948          * to be adjusted (it should be the highest rate specified between formats and
949          * hooks). The given audiohook_list's internal sample rate is then set to the
950          * updated value before returning.
951          *
952          * If slin compatibility mode is turned on then an audiohook's internal sample
953          * rate is set to its audiohook_list's rate. If an audiohook_list's rate is
954          * adjusted during this pass then the change is picked up by the audiohooks
955          * on the next pass.
956          */
957         internal_sample_rate = audiohook_list->list_internal_samp_rate;
958
959         /* ---Part_2: Send middle_frame to spy and manipulator lists.  middle_frame is guaranteed to be SLINEAR here.*/
960         /* Queue up signed linear frame to each spy */
961         AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->spy_list, audiohook, list) {
962                 ast_audiohook_lock(audiohook);
963                 if (audiohook->status != AST_AUDIOHOOK_STATUS_RUNNING) {
964                         AST_LIST_REMOVE_CURRENT(list);
965                         removed = 1;
966                         ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
967                         ast_audiohook_unlock(audiohook);
968                         if (ast_channel_is_bridged(chan)) {
969                                 ast_channel_set_unbridged_nolock(chan, 1);
970                         }
971                         continue;
972                 }
973                 audiohook_list_set_hook_rate(audiohook_list, audiohook, &internal_sample_rate);
974                 ast_audiohook_write_frame(audiohook, direction, middle_frame);
975                 ast_audiohook_unlock(audiohook);
976         }
977         AST_LIST_TRAVERSE_SAFE_END;
978
979         /* If this frame is being written out to the channel then we need to use whisper sources */
980         if (!AST_LIST_EMPTY(&audiohook_list->whisper_list)) {
981                 int i = 0;
982                 short read_buf[samples], combine_buf[samples], *data1 = NULL, *data2 = NULL;
983                 memset(&combine_buf, 0, sizeof(combine_buf));
984                 AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->whisper_list, audiohook, list) {
985                         struct ast_slinfactory *factory = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook->read_factory : &audiohook->write_factory);
986                         ast_audiohook_lock(audiohook);
987                         if (audiohook->status != AST_AUDIOHOOK_STATUS_RUNNING) {
988                                 AST_LIST_REMOVE_CURRENT(list);
989                                 removed = 1;
990                                 ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
991                                 ast_audiohook_unlock(audiohook);
992                                 if (ast_channel_is_bridged(chan)) {
993                                         ast_channel_set_unbridged_nolock(chan, 1);
994                                 }
995                                 continue;
996                         }
997                         audiohook_list_set_hook_rate(audiohook_list, audiohook, &internal_sample_rate);
998                         if (ast_slinfactory_available(factory) >= samples && ast_slinfactory_read(factory, read_buf, samples)) {
999                                 /* Take audio from this whisper source and combine it into our main buffer */
1000                                 for (i = 0, data1 = combine_buf, data2 = read_buf; i < samples; i++, data1++, data2++) {
1001                                         ast_slinear_saturated_add(data1, data2);
1002                                 }
1003                         }
1004                         ast_audiohook_unlock(audiohook);
1005                 }
1006                 AST_LIST_TRAVERSE_SAFE_END;
1007                 /* We take all of the combined whisper sources and combine them into the audio being written out */
1008                 for (i = 0, data1 = middle_frame->data.ptr, data2 = combine_buf; i < samples; i++, data1++, data2++) {
1009                         ast_slinear_saturated_add(data1, data2);
1010                 }
1011                 middle_frame_manipulated = 1;
1012         }
1013
1014         /* Pass off frame to manipulate audiohooks */
1015         if (!AST_LIST_EMPTY(&audiohook_list->manipulate_list)) {
1016                 AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->manipulate_list, audiohook, list) {
1017                         ast_audiohook_lock(audiohook);
1018                         if (audiohook->status != AST_AUDIOHOOK_STATUS_RUNNING) {
1019                                 AST_LIST_REMOVE_CURRENT(list);
1020                                 removed = 1;
1021                                 ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
1022                                 ast_audiohook_unlock(audiohook);
1023                                 /* We basically drop all of our links to the manipulate audiohook and prod it to do it's own destructive things */
1024                                 audiohook->manipulate_callback(audiohook, chan, NULL, direction);
1025                                 if (ast_channel_is_bridged(chan)) {
1026                                         ast_channel_set_unbridged_nolock(chan, 1);
1027                                 }
1028                                 continue;
1029                         }
1030                         audiohook_list_set_hook_rate(audiohook_list, audiohook, &internal_sample_rate);
1031                         /*
1032                          * Feed in frame to manipulation.
1033                          */
1034                         if (!audiohook->manipulate_callback(audiohook, chan, middle_frame, direction)) {
1035                                 /*
1036                                  * XXX FAILURES ARE IGNORED XXX
1037                                  * If the manipulation fails then the frame will be returned in its original state.
1038                                  * Since there are potentially more manipulator callbacks in the list, no action should
1039                                  * be taken here to exit early.
1040                                  */
1041                                 middle_frame_manipulated = 1;
1042                         }
1043                         ast_audiohook_unlock(audiohook);
1044                 }
1045                 AST_LIST_TRAVERSE_SAFE_END;
1046         }
1047
1048         /* ---Part_3: Decide what to do with the end_frame (whether to transcode or not) */
1049         if (middle_frame_manipulated) {
1050                 if (!(end_frame = audiohook_list_translate_to_native(audiohook_list, direction, middle_frame, start_frame->subclass.format))) {
1051                         /* translation failed, so just pass back the input frame */
1052                         end_frame = start_frame;
1053                 }
1054         } else {
1055                 end_frame = start_frame;
1056         }
1057         /* clean up our middle_frame if required */
1058         if (middle_frame != end_frame) {
1059                 ast_frfree(middle_frame);
1060                 middle_frame = NULL;
1061         }
1062
1063         /* Before returning, if an audiohook got removed, reset samplerate compatibility */
1064         if (removed) {
1065                 audiohook_list_set_samplerate_compatibility(audiohook_list);
1066         } else {
1067                 /*
1068                  * Set the audiohook_list's rate to the updated rate. Note that if a hook
1069                  * was removed then the list's internal rate is reset to the default.
1070                  */
1071                 audiohook_list->list_internal_samp_rate = internal_sample_rate;
1072         }
1073
1074         return end_frame;
1075 }
1076
1077 int ast_audiohook_write_list_empty(struct ast_audiohook_list *audiohook_list)
1078 {
1079         return !audiohook_list
1080                 || (AST_LIST_EMPTY(&audiohook_list->spy_list)
1081                         && AST_LIST_EMPTY(&audiohook_list->whisper_list)
1082                         && AST_LIST_EMPTY(&audiohook_list->manipulate_list));
1083 }
1084
1085 /*! \brief Pass a frame off to be handled by the audiohook core
1086  * \param chan Channel that the list is coming off of
1087  * \param audiohook_list List of audiohooks
1088  * \param direction Direction frame is coming in from
1089  * \param frame The frame itself
1090  * \return Return frame on success, NULL on failure
1091  */
1092 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)
1093 {
1094         /* Pass off frame to it's respective list write function */
1095         if (frame->frametype == AST_FRAME_VOICE) {
1096                 return audio_audiohook_write_list(chan, audiohook_list, direction, frame);
1097         } else if (frame->frametype == AST_FRAME_DTMF) {
1098                 return dtmf_audiohook_write_list(chan, audiohook_list, direction, frame);
1099         } else {
1100                 return frame;
1101         }
1102 }
1103
1104 /*! \brief Wait for audiohook trigger to be triggered
1105  * \param audiohook Audiohook to wait on
1106  */
1107 void ast_audiohook_trigger_wait(struct ast_audiohook *audiohook)
1108 {
1109         struct timeval wait;
1110         struct timespec ts;
1111
1112         wait = ast_tvadd(ast_tvnow(), ast_samp2tv(50000, 1000));
1113         ts.tv_sec = wait.tv_sec;
1114         ts.tv_nsec = wait.tv_usec * 1000;
1115
1116         ast_cond_timedwait(&audiohook->trigger, &audiohook->lock, &ts);
1117
1118         return;
1119 }
1120
1121 /* Count number of channel audiohooks by type, regardless of type */
1122 int ast_channel_audiohook_count_by_source(struct ast_channel *chan, const char *source, enum ast_audiohook_type type)
1123 {
1124         int count = 0;
1125         struct ast_audiohook *ah = NULL;
1126
1127         if (!ast_channel_audiohooks(chan)) {
1128                 return -1;
1129         }
1130
1131         switch (type) {
1132                 case AST_AUDIOHOOK_TYPE_SPY:
1133                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->spy_list, ah, list) {
1134                                 if (!strcmp(ah->source, source)) {
1135                                         count++;
1136                                 }
1137                         }
1138                         break;
1139                 case AST_AUDIOHOOK_TYPE_WHISPER:
1140                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->whisper_list, ah, list) {
1141                                 if (!strcmp(ah->source, source)) {
1142                                         count++;
1143                                 }
1144                         }
1145                         break;
1146                 case AST_AUDIOHOOK_TYPE_MANIPULATE:
1147                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->manipulate_list, ah, list) {
1148                                 if (!strcmp(ah->source, source)) {
1149                                         count++;
1150                                 }
1151                         }
1152                         break;
1153                 default:
1154                         ast_debug(1, "Invalid audiohook type supplied, (%u)\n", type);
1155                         return -1;
1156         }
1157
1158         return count;
1159 }
1160
1161 /* Count number of channel audiohooks by type that are running */
1162 int ast_channel_audiohook_count_by_source_running(struct ast_channel *chan, const char *source, enum ast_audiohook_type type)
1163 {
1164         int count = 0;
1165         struct ast_audiohook *ah = NULL;
1166         if (!ast_channel_audiohooks(chan))
1167                 return -1;
1168
1169         switch (type) {
1170                 case AST_AUDIOHOOK_TYPE_SPY:
1171                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->spy_list, ah, list) {
1172                                 if ((!strcmp(ah->source, source)) && (ah->status == AST_AUDIOHOOK_STATUS_RUNNING))
1173                                         count++;
1174                         }
1175                         break;
1176                 case AST_AUDIOHOOK_TYPE_WHISPER:
1177                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->whisper_list, ah, list) {
1178                                 if ((!strcmp(ah->source, source)) && (ah->status == AST_AUDIOHOOK_STATUS_RUNNING))
1179                                         count++;
1180                         }
1181                         break;
1182                 case AST_AUDIOHOOK_TYPE_MANIPULATE:
1183                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->manipulate_list, ah, list) {
1184                                 if ((!strcmp(ah->source, source)) && (ah->status == AST_AUDIOHOOK_STATUS_RUNNING))
1185                                         count++;
1186                         }
1187                         break;
1188                 default:
1189                         ast_debug(1, "Invalid audiohook type supplied, (%u)\n", type);
1190                         return -1;
1191         }
1192         return count;
1193 }
1194
1195 /*! \brief Audiohook volume adjustment structure */
1196 struct audiohook_volume {
1197         struct ast_audiohook audiohook; /*!< Audiohook attached to the channel */
1198         int read_adjustment;            /*!< Value to adjust frames read from the channel by */
1199         int write_adjustment;           /*!< Value to adjust frames written to the channel by */
1200 };
1201
1202 /*! \brief Callback used to destroy the audiohook volume datastore
1203  * \param data Volume information structure
1204  * \return Returns nothing
1205  */
1206 static void audiohook_volume_destroy(void *data)
1207 {
1208         struct audiohook_volume *audiohook_volume = data;
1209
1210         /* Destroy the audiohook as it is no longer in use */
1211         ast_audiohook_destroy(&audiohook_volume->audiohook);
1212
1213         /* Finally free ourselves, we are of no more use */
1214         ast_free(audiohook_volume);
1215
1216         return;
1217 }
1218
1219 /*! \brief Datastore used to store audiohook volume information */
1220 static const struct ast_datastore_info audiohook_volume_datastore = {
1221         .type = "Volume",
1222         .destroy = audiohook_volume_destroy,
1223 };
1224
1225 /*! \brief Helper function which actually gets called by audiohooks to perform the adjustment
1226  * \param audiohook Audiohook attached to the channel
1227  * \param chan Channel we are attached to
1228  * \param frame Frame of audio we want to manipulate
1229  * \param direction Direction the audio came in from
1230  * \return Returns 0 on success, -1 on failure
1231  */
1232 static int audiohook_volume_callback(struct ast_audiohook *audiohook, struct ast_channel *chan, struct ast_frame *frame, enum ast_audiohook_direction direction)
1233 {
1234         struct ast_datastore *datastore = NULL;
1235         struct audiohook_volume *audiohook_volume = NULL;
1236         int *gain = NULL;
1237
1238         /* If the audiohook is shutting down don't even bother */
1239         if (audiohook->status == AST_AUDIOHOOK_STATUS_DONE) {
1240                 return 0;
1241         }
1242
1243         /* Try to find the datastore containg adjustment information, if we can't just bail out */
1244         if (!(datastore = ast_channel_datastore_find(chan, &audiohook_volume_datastore, NULL))) {
1245                 return 0;
1246         }
1247
1248         audiohook_volume = datastore->data;
1249
1250         /* Based on direction grab the appropriate adjustment value */
1251         if (direction == AST_AUDIOHOOK_DIRECTION_READ) {
1252                 gain = &audiohook_volume->read_adjustment;
1253         } else if (direction == AST_AUDIOHOOK_DIRECTION_WRITE) {
1254                 gain = &audiohook_volume->write_adjustment;
1255         }
1256
1257         /* If an adjustment value is present modify the frame */
1258         if (gain && *gain) {
1259                 ast_frame_adjust_volume(frame, *gain);
1260         }
1261
1262         return 0;
1263 }
1264
1265 /*! \brief Helper function which finds and optionally creates an audiohook_volume_datastore datastore on a channel
1266  * \param chan Channel to look on
1267  * \param create Whether to create the datastore if not found
1268  * \return Returns audiohook_volume structure on success, NULL on failure
1269  */
1270 static struct audiohook_volume *audiohook_volume_get(struct ast_channel *chan, int create)
1271 {
1272         struct ast_datastore *datastore = NULL;
1273         struct audiohook_volume *audiohook_volume = NULL;
1274
1275         /* If we are able to find the datastore return the contents (which is actually an audiohook_volume structure) */
1276         if ((datastore = ast_channel_datastore_find(chan, &audiohook_volume_datastore, NULL))) {
1277                 return datastore->data;
1278         }
1279
1280         /* 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 */
1281         if (!create || !(datastore = ast_datastore_alloc(&audiohook_volume_datastore, NULL))) {
1282                 return NULL;
1283         }
1284
1285         /* Create a new audiohook_volume structure to contain our adjustments and audiohook */
1286         if (!(audiohook_volume = ast_calloc(1, sizeof(*audiohook_volume)))) {
1287                 ast_datastore_free(datastore);
1288                 return NULL;
1289         }
1290
1291         /* Setup our audiohook structure so we can manipulate the audio */
1292         ast_audiohook_init(&audiohook_volume->audiohook, AST_AUDIOHOOK_TYPE_MANIPULATE, "Volume", AST_AUDIOHOOK_MANIPULATE_ALL_RATES);
1293         audiohook_volume->audiohook.manipulate_callback = audiohook_volume_callback;
1294
1295         /* Attach the audiohook_volume blob to the datastore and attach to the channel */
1296         datastore->data = audiohook_volume;
1297         ast_channel_datastore_add(chan, datastore);
1298
1299         /* All is well... put the audiohook into motion */
1300         ast_audiohook_attach(chan, &audiohook_volume->audiohook);
1301
1302         return audiohook_volume;
1303 }
1304
1305 /*! \brief Adjust the volume on frames read from or written to a channel
1306  * \param chan Channel to muck with
1307  * \param direction Direction to set on
1308  * \param volume Value to adjust the volume by
1309  * \return Returns 0 on success, -1 on failure
1310  */
1311 int ast_audiohook_volume_set(struct ast_channel *chan, enum ast_audiohook_direction direction, int volume)
1312 {
1313         struct audiohook_volume *audiohook_volume = NULL;
1314
1315         /* Attempt to find the audiohook volume information, but only create it if we are not setting the adjustment value to zero */
1316         if (!(audiohook_volume = audiohook_volume_get(chan, (volume ? 1 : 0)))) {
1317                 return -1;
1318         }
1319
1320         /* Now based on the direction set the proper value */
1321         if (direction == AST_AUDIOHOOK_DIRECTION_READ || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
1322                 audiohook_volume->read_adjustment = volume;
1323         }
1324         if (direction == AST_AUDIOHOOK_DIRECTION_WRITE || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
1325                 audiohook_volume->write_adjustment = volume;
1326         }
1327
1328         return 0;
1329 }
1330
1331 /*! \brief Retrieve the volume adjustment value on frames read from or written to a channel
1332  * \param chan Channel to retrieve volume adjustment from
1333  * \param direction Direction to retrieve
1334  * \return Returns adjustment value
1335  */
1336 int ast_audiohook_volume_get(struct ast_channel *chan, enum ast_audiohook_direction direction)
1337 {
1338         struct audiohook_volume *audiohook_volume = NULL;
1339         int adjustment = 0;
1340
1341         /* Attempt to find the audiohook volume information, but do not create it as we only want to look at the values */
1342         if (!(audiohook_volume = audiohook_volume_get(chan, 0))) {
1343                 return 0;
1344         }
1345
1346         /* Grab the adjustment value based on direction given */
1347         if (direction == AST_AUDIOHOOK_DIRECTION_READ) {
1348                 adjustment = audiohook_volume->read_adjustment;
1349         } else if (direction == AST_AUDIOHOOK_DIRECTION_WRITE) {
1350                 adjustment = audiohook_volume->write_adjustment;
1351         }
1352
1353         return adjustment;
1354 }
1355
1356 /*! \brief Adjust the volume on frames read from or written to a channel
1357  * \param chan Channel to muck with
1358  * \param direction Direction to increase
1359  * \param volume Value to adjust the adjustment by
1360  * \return Returns 0 on success, -1 on failure
1361  */
1362 int ast_audiohook_volume_adjust(struct ast_channel *chan, enum ast_audiohook_direction direction, int volume)
1363 {
1364         struct audiohook_volume *audiohook_volume = NULL;
1365
1366         /* Attempt to find the audiohook volume information, and create an audiohook if none exists */
1367         if (!(audiohook_volume = audiohook_volume_get(chan, 1))) {
1368                 return -1;
1369         }
1370
1371         /* Based on the direction change the specific adjustment value */
1372         if (direction == AST_AUDIOHOOK_DIRECTION_READ || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
1373                 audiohook_volume->read_adjustment += volume;
1374         }
1375         if (direction == AST_AUDIOHOOK_DIRECTION_WRITE || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
1376                 audiohook_volume->write_adjustment += volume;
1377         }
1378
1379         return 0;
1380 }
1381
1382 /*! \brief Mute frames read from or written to a channel
1383  * \param chan Channel to muck with
1384  * \param source Type of audiohook
1385  * \param flag which flag to set / clear
1386  * \param clear set or clear
1387  * \return Returns 0 on success, -1 on failure
1388  */
1389 int ast_audiohook_set_mute(struct ast_channel *chan, const char *source, enum ast_audiohook_flags flag, int clear)
1390 {
1391         struct ast_audiohook *audiohook = NULL;
1392
1393         ast_channel_lock(chan);
1394
1395         /* Ensure the channel has audiohooks on it */
1396         if (!ast_channel_audiohooks(chan)) {
1397                 ast_channel_unlock(chan);
1398                 return -1;
1399         }
1400
1401         audiohook = find_audiohook_by_source(ast_channel_audiohooks(chan), source);
1402
1403         if (audiohook) {
1404                 if (clear) {
1405                         ast_clear_flag(audiohook, flag);
1406                 } else {
1407                         ast_set_flag(audiohook, flag);
1408                 }
1409         }
1410
1411         ast_channel_unlock(chan);
1412
1413         return (audiohook ? 0 : -1);
1414 }