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