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