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