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