audiohook.c: Simplify variable usage in audiohook_read_frame_both().
[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 (ast_format_cmp(frame->subclass.format, in_translate->format) == AST_FORMAT_CMP_NOT_EQUAL) {
828                 if (in_translate->trans_pvt) {
829                         ast_translator_free_path(in_translate->trans_pvt);
830                 }
831                 if (!(in_translate->trans_pvt = ast_translator_build_path(slin, frame->subclass.format))) {
832                         return NULL;
833                 }
834                 ao2_replace(in_translate->format, frame->subclass.format);
835         }
836
837         if (!(new_frame = ast_translate(in_translate->trans_pvt, frame, 0))) {
838                 return NULL;
839         }
840
841         return new_frame;
842 }
843
844 static struct ast_frame *audiohook_list_translate_to_native(struct ast_audiohook_list *audiohook_list,
845         enum ast_audiohook_direction direction, struct ast_frame *slin_frame, struct ast_format *outformat)
846 {
847         struct ast_audiohook_translate *out_translate = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook_list->out_translate[0] : &audiohook_list->out_translate[1]);
848         struct ast_frame *outframe = NULL;
849         if (ast_format_cmp(slin_frame->subclass.format, outformat) == AST_FORMAT_CMP_NOT_EQUAL) {
850                 /* rebuild translators if necessary */
851                 if (ast_format_cmp(out_translate->format, outformat) == AST_FORMAT_CMP_NOT_EQUAL) {
852                         if (out_translate->trans_pvt) {
853                                 ast_translator_free_path(out_translate->trans_pvt);
854                         }
855                         if (!(out_translate->trans_pvt = ast_translator_build_path(outformat, slin_frame->subclass.format))) {
856                                 return NULL;
857                         }
858                         ao2_replace(out_translate->format, outformat);
859                 }
860                 /* translate back to the format the frame came in as. */
861                 if (!(outframe = ast_translate(out_translate->trans_pvt, slin_frame, 0))) {
862                         return NULL;
863                 }
864         }
865         return outframe;
866 }
867
868 /*!
869  *\brief Set the audiohook's internal sample rate to the audiohook_list's rate,
870  *       but only when native slin compatibility is turned on.
871  *
872  * \param audiohook_list audiohook_list data object
873  * \param audiohook the audiohook to update
874  * \param rate the current max internal sample rate
875  */
876 static void audiohook_list_set_hook_rate(struct ast_audiohook_list *audiohook_list,
877                                          struct ast_audiohook *audiohook, int *rate)
878 {
879         /* The rate should always be the max between itself and the hook */
880         if (audiohook->hook_internal_samp_rate > *rate) {
881                 *rate = audiohook->hook_internal_samp_rate;
882         }
883
884         /*
885          * If native slin compatibility is turned on then update the audiohook
886          * with the audiohook_list's current rate. Note, the audiohook's rate is
887          * set to the audiohook_list's rate and not the given rate. If there is
888          * a change in rate the hook's rate is changed on its next check.
889          */
890         if (audiohook_list->native_slin_compatible) {
891                 ast_set_flag(audiohook, AST_AUDIOHOOK_COMPATIBLE);
892                 audiohook_set_internal_rate(audiohook, audiohook_list->list_internal_samp_rate, 1);
893         } else {
894                 ast_clear_flag(audiohook, AST_AUDIOHOOK_COMPATIBLE);
895         }
896 }
897
898 /*!
899  * \brief Pass an AUDIO frame off to be handled by the audiohook core
900  *
901  * \details
902  * This function has 3 ast_frames and 3 parts to handle each.  At the beginning of this
903  * function all 3 frames, start_frame, middle_frame, and end_frame point to the initial
904  * input frame.
905  *
906  * Part_1: Translate the start_frame into SLINEAR audio if it is not already in that
907  *         format.  The result of this part is middle_frame is guaranteed to be in
908  *         SLINEAR format for Part_2.
909  * Part_2: Send middle_frame off to spies and manipulators.  At this point middle_frame is
910  *         either a new frame as result of the translation, or points directly to the start_frame
911  *         because no translation to SLINEAR audio was required.
912  * Part_3: Translate end_frame's audio back into the format of start frame if necessary.  This
913  *         is only necessary if manipulation of middle_frame occurred.
914  *
915  * \param chan Channel that the list is coming off of
916  * \param audiohook_list List of audiohooks
917  * \param direction Direction frame is coming in from
918  * \param frame The frame itself
919  * \return Return frame on success, NULL on failure
920  */
921 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)
922 {
923         struct ast_frame *start_frame = frame, *middle_frame = frame, *end_frame = frame;
924         struct ast_audiohook *audiohook = NULL;
925         int samples;
926         int middle_frame_manipulated = 0;
927         int removed = 0;
928         int internal_sample_rate;
929
930         /* ---Part_1. translate start_frame to SLINEAR if necessary. */
931         if (!(middle_frame = audiohook_list_translate_to_slin(audiohook_list, direction, start_frame))) {
932                 return frame;
933         }
934         samples = middle_frame->samples;
935
936         /*
937          * While processing each audiohook check to see if the internal sample rate needs
938          * to be adjusted (it should be the highest rate specified between formats and
939          * hooks). The given audiohook_list's internal sample rate is then set to the
940          * updated value before returning.
941          *
942          * If slin compatibility mode is turned on then an audiohook's internal sample
943          * rate is set to its audiohook_list's rate. If an audiohook_list's rate is
944          * adjusted during this pass then the change is picked up by the audiohooks
945          * on the next pass.
946          */
947         internal_sample_rate = audiohook_list->list_internal_samp_rate;
948
949         /* ---Part_2: Send middle_frame to spy and manipulator lists.  middle_frame is guaranteed to be SLINEAR here.*/
950         /* Queue up signed linear frame to each spy */
951         AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->spy_list, audiohook, list) {
952                 ast_audiohook_lock(audiohook);
953                 if (audiohook->status != AST_AUDIOHOOK_STATUS_RUNNING) {
954                         AST_LIST_REMOVE_CURRENT(list);
955                         removed = 1;
956                         ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
957                         ast_audiohook_unlock(audiohook);
958                         if (ast_channel_is_bridged(chan)) {
959                                 ast_channel_set_unbridged_nolock(chan, 1);
960                         }
961                         continue;
962                 }
963                 audiohook_list_set_hook_rate(audiohook_list, audiohook, &internal_sample_rate);
964                 ast_audiohook_write_frame(audiohook, direction, middle_frame);
965                 ast_audiohook_unlock(audiohook);
966         }
967         AST_LIST_TRAVERSE_SAFE_END;
968
969         /* If this frame is being written out to the channel then we need to use whisper sources */
970         if (!AST_LIST_EMPTY(&audiohook_list->whisper_list)) {
971                 int i = 0;
972                 short read_buf[samples], combine_buf[samples], *data1 = NULL, *data2 = NULL;
973                 memset(&combine_buf, 0, sizeof(combine_buf));
974                 AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->whisper_list, audiohook, list) {
975                         struct ast_slinfactory *factory = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook->read_factory : &audiohook->write_factory);
976                         ast_audiohook_lock(audiohook);
977                         if (audiohook->status != AST_AUDIOHOOK_STATUS_RUNNING) {
978                                 AST_LIST_REMOVE_CURRENT(list);
979                                 removed = 1;
980                                 ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
981                                 ast_audiohook_unlock(audiohook);
982                                 if (ast_channel_is_bridged(chan)) {
983                                         ast_channel_set_unbridged_nolock(chan, 1);
984                                 }
985                                 continue;
986                         }
987                         audiohook_list_set_hook_rate(audiohook_list, audiohook, &internal_sample_rate);
988                         if (ast_slinfactory_available(factory) >= samples && ast_slinfactory_read(factory, read_buf, samples)) {
989                                 /* Take audio from this whisper source and combine it into our main buffer */
990                                 for (i = 0, data1 = combine_buf, data2 = read_buf; i < samples; i++, data1++, data2++) {
991                                         ast_slinear_saturated_add(data1, data2);
992                                 }
993                         }
994                         ast_audiohook_unlock(audiohook);
995                 }
996                 AST_LIST_TRAVERSE_SAFE_END;
997                 /* We take all of the combined whisper sources and combine them into the audio being written out */
998                 for (i = 0, data1 = middle_frame->data.ptr, data2 = combine_buf; i < samples; i++, data1++, data2++) {
999                         ast_slinear_saturated_add(data1, data2);
1000                 }
1001                 middle_frame_manipulated = 1;
1002         }
1003
1004         /* Pass off frame to manipulate audiohooks */
1005         if (!AST_LIST_EMPTY(&audiohook_list->manipulate_list)) {
1006                 AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->manipulate_list, audiohook, list) {
1007                         ast_audiohook_lock(audiohook);
1008                         if (audiohook->status != AST_AUDIOHOOK_STATUS_RUNNING) {
1009                                 AST_LIST_REMOVE_CURRENT(list);
1010                                 removed = 1;
1011                                 ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
1012                                 ast_audiohook_unlock(audiohook);
1013                                 /* We basically drop all of our links to the manipulate audiohook and prod it to do it's own destructive things */
1014                                 audiohook->manipulate_callback(audiohook, chan, NULL, direction);
1015                                 if (ast_channel_is_bridged(chan)) {
1016                                         ast_channel_set_unbridged_nolock(chan, 1);
1017                                 }
1018                                 continue;
1019                         }
1020                         audiohook_list_set_hook_rate(audiohook_list, audiohook, &internal_sample_rate);
1021                         /*
1022                          * Feed in frame to manipulation.
1023                          */
1024                         if (!audiohook->manipulate_callback(audiohook, chan, middle_frame, direction)) {
1025                                 /*
1026                                  * XXX FAILURES ARE IGNORED XXX
1027                                  * If the manipulation fails then the frame will be returned in its original state.
1028                                  * Since there are potentially more manipulator callbacks in the list, no action should
1029                                  * be taken here to exit early.
1030                                  */
1031                                 middle_frame_manipulated = 1;
1032                         }
1033                         ast_audiohook_unlock(audiohook);
1034                 }
1035                 AST_LIST_TRAVERSE_SAFE_END;
1036         }
1037
1038         /* ---Part_3: Decide what to do with the end_frame (whether to transcode or not) */
1039         if (middle_frame_manipulated) {
1040                 if (!(end_frame = audiohook_list_translate_to_native(audiohook_list, direction, middle_frame, start_frame->subclass.format))) {
1041                         /* translation failed, so just pass back the input frame */
1042                         end_frame = start_frame;
1043                 }
1044         } else {
1045                 end_frame = start_frame;
1046         }
1047         /* clean up our middle_frame if required */
1048         if (middle_frame != end_frame) {
1049                 ast_frfree(middle_frame);
1050                 middle_frame = NULL;
1051         }
1052
1053         /* Before returning, if an audiohook got removed, reset samplerate compatibility */
1054         if (removed) {
1055                 audiohook_list_set_samplerate_compatibility(audiohook_list);
1056         } else {
1057                 /*
1058                  * Set the audiohook_list's rate to the updated rate. Note that if a hook
1059                  * was removed then the list's internal rate is reset to the default.
1060                  */
1061                 audiohook_list->list_internal_samp_rate = internal_sample_rate;
1062         }
1063
1064         return end_frame;
1065 }
1066
1067 int ast_audiohook_write_list_empty(struct ast_audiohook_list *audiohook_list)
1068 {
1069         return !audiohook_list
1070                 || (AST_LIST_EMPTY(&audiohook_list->spy_list)
1071                         && AST_LIST_EMPTY(&audiohook_list->whisper_list)
1072                         && AST_LIST_EMPTY(&audiohook_list->manipulate_list));
1073 }
1074
1075 /*! \brief Pass a frame off to be handled by the audiohook core
1076  * \param chan Channel that the list is coming off of
1077  * \param audiohook_list List of audiohooks
1078  * \param direction Direction frame is coming in from
1079  * \param frame The frame itself
1080  * \return Return frame on success, NULL on failure
1081  */
1082 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)
1083 {
1084         /* Pass off frame to it's respective list write function */
1085         if (frame->frametype == AST_FRAME_VOICE) {
1086                 return audio_audiohook_write_list(chan, audiohook_list, direction, frame);
1087         } else if (frame->frametype == AST_FRAME_DTMF) {
1088                 return dtmf_audiohook_write_list(chan, audiohook_list, direction, frame);
1089         } else {
1090                 return frame;
1091         }
1092 }
1093
1094 /*! \brief Wait for audiohook trigger to be triggered
1095  * \param audiohook Audiohook to wait on
1096  */
1097 void ast_audiohook_trigger_wait(struct ast_audiohook *audiohook)
1098 {
1099         struct timeval wait;
1100         struct timespec ts;
1101
1102         wait = ast_tvadd(ast_tvnow(), ast_samp2tv(50000, 1000));
1103         ts.tv_sec = wait.tv_sec;
1104         ts.tv_nsec = wait.tv_usec * 1000;
1105
1106         ast_cond_timedwait(&audiohook->trigger, &audiohook->lock, &ts);
1107
1108         return;
1109 }
1110
1111 /* Count number of channel audiohooks by type, regardless of type */
1112 int ast_channel_audiohook_count_by_source(struct ast_channel *chan, const char *source, enum ast_audiohook_type type)
1113 {
1114         int count = 0;
1115         struct ast_audiohook *ah = NULL;
1116
1117         if (!ast_channel_audiohooks(chan)) {
1118                 return -1;
1119         }
1120
1121         switch (type) {
1122                 case AST_AUDIOHOOK_TYPE_SPY:
1123                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->spy_list, ah, list) {
1124                                 if (!strcmp(ah->source, source)) {
1125                                         count++;
1126                                 }
1127                         }
1128                         break;
1129                 case AST_AUDIOHOOK_TYPE_WHISPER:
1130                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->whisper_list, ah, list) {
1131                                 if (!strcmp(ah->source, source)) {
1132                                         count++;
1133                                 }
1134                         }
1135                         break;
1136                 case AST_AUDIOHOOK_TYPE_MANIPULATE:
1137                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->manipulate_list, ah, list) {
1138                                 if (!strcmp(ah->source, source)) {
1139                                         count++;
1140                                 }
1141                         }
1142                         break;
1143                 default:
1144                         ast_debug(1, "Invalid audiohook type supplied, (%u)\n", type);
1145                         return -1;
1146         }
1147
1148         return count;
1149 }
1150
1151 /* Count number of channel audiohooks by type that are running */
1152 int ast_channel_audiohook_count_by_source_running(struct ast_channel *chan, const char *source, enum ast_audiohook_type type)
1153 {
1154         int count = 0;
1155         struct ast_audiohook *ah = NULL;
1156         if (!ast_channel_audiohooks(chan))
1157                 return -1;
1158
1159         switch (type) {
1160                 case AST_AUDIOHOOK_TYPE_SPY:
1161                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->spy_list, ah, list) {
1162                                 if ((!strcmp(ah->source, source)) && (ah->status == AST_AUDIOHOOK_STATUS_RUNNING))
1163                                         count++;
1164                         }
1165                         break;
1166                 case AST_AUDIOHOOK_TYPE_WHISPER:
1167                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->whisper_list, ah, list) {
1168                                 if ((!strcmp(ah->source, source)) && (ah->status == AST_AUDIOHOOK_STATUS_RUNNING))
1169                                         count++;
1170                         }
1171                         break;
1172                 case AST_AUDIOHOOK_TYPE_MANIPULATE:
1173                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->manipulate_list, ah, list) {
1174                                 if ((!strcmp(ah->source, source)) && (ah->status == AST_AUDIOHOOK_STATUS_RUNNING))
1175                                         count++;
1176                         }
1177                         break;
1178                 default:
1179                         ast_debug(1, "Invalid audiohook type supplied, (%u)\n", type);
1180                         return -1;
1181         }
1182         return count;
1183 }
1184
1185 /*! \brief Audiohook volume adjustment structure */
1186 struct audiohook_volume {
1187         struct ast_audiohook audiohook; /*!< Audiohook attached to the channel */
1188         int read_adjustment;            /*!< Value to adjust frames read from the channel by */
1189         int write_adjustment;           /*!< Value to adjust frames written to the channel by */
1190 };
1191
1192 /*! \brief Callback used to destroy the audiohook volume datastore
1193  * \param data Volume information structure
1194  * \return Returns nothing
1195  */
1196 static void audiohook_volume_destroy(void *data)
1197 {
1198         struct audiohook_volume *audiohook_volume = data;
1199
1200         /* Destroy the audiohook as it is no longer in use */
1201         ast_audiohook_destroy(&audiohook_volume->audiohook);
1202
1203         /* Finally free ourselves, we are of no more use */
1204         ast_free(audiohook_volume);
1205
1206         return;
1207 }
1208
1209 /*! \brief Datastore used to store audiohook volume information */
1210 static const struct ast_datastore_info audiohook_volume_datastore = {
1211         .type = "Volume",
1212         .destroy = audiohook_volume_destroy,
1213 };
1214
1215 /*! \brief Helper function which actually gets called by audiohooks to perform the adjustment
1216  * \param audiohook Audiohook attached to the channel
1217  * \param chan Channel we are attached to
1218  * \param frame Frame of audio we want to manipulate
1219  * \param direction Direction the audio came in from
1220  * \return Returns 0 on success, -1 on failure
1221  */
1222 static int audiohook_volume_callback(struct ast_audiohook *audiohook, struct ast_channel *chan, struct ast_frame *frame, enum ast_audiohook_direction direction)
1223 {
1224         struct ast_datastore *datastore = NULL;
1225         struct audiohook_volume *audiohook_volume = NULL;
1226         int *gain = NULL;
1227
1228         /* If the audiohook is shutting down don't even bother */
1229         if (audiohook->status == AST_AUDIOHOOK_STATUS_DONE) {
1230                 return 0;
1231         }
1232
1233         /* Try to find the datastore containg adjustment information, if we can't just bail out */
1234         if (!(datastore = ast_channel_datastore_find(chan, &audiohook_volume_datastore, NULL))) {
1235                 return 0;
1236         }
1237
1238         audiohook_volume = datastore->data;
1239
1240         /* Based on direction grab the appropriate adjustment value */
1241         if (direction == AST_AUDIOHOOK_DIRECTION_READ) {
1242                 gain = &audiohook_volume->read_adjustment;
1243         } else if (direction == AST_AUDIOHOOK_DIRECTION_WRITE) {
1244                 gain = &audiohook_volume->write_adjustment;
1245         }
1246
1247         /* If an adjustment value is present modify the frame */
1248         if (gain && *gain) {
1249                 ast_frame_adjust_volume(frame, *gain);
1250         }
1251
1252         return 0;
1253 }
1254
1255 /*! \brief Helper function which finds and optionally creates an audiohook_volume_datastore datastore on a channel
1256  * \param chan Channel to look on
1257  * \param create Whether to create the datastore if not found
1258  * \return Returns audiohook_volume structure on success, NULL on failure
1259  */
1260 static struct audiohook_volume *audiohook_volume_get(struct ast_channel *chan, int create)
1261 {
1262         struct ast_datastore *datastore = NULL;
1263         struct audiohook_volume *audiohook_volume = NULL;
1264
1265         /* If we are able to find the datastore return the contents (which is actually an audiohook_volume structure) */
1266         if ((datastore = ast_channel_datastore_find(chan, &audiohook_volume_datastore, NULL))) {
1267                 return datastore->data;
1268         }
1269
1270         /* 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 */
1271         if (!create || !(datastore = ast_datastore_alloc(&audiohook_volume_datastore, NULL))) {
1272                 return NULL;
1273         }
1274
1275         /* Create a new audiohook_volume structure to contain our adjustments and audiohook */
1276         if (!(audiohook_volume = ast_calloc(1, sizeof(*audiohook_volume)))) {
1277                 ast_datastore_free(datastore);
1278                 return NULL;
1279         }
1280
1281         /* Setup our audiohook structure so we can manipulate the audio */
1282         ast_audiohook_init(&audiohook_volume->audiohook, AST_AUDIOHOOK_TYPE_MANIPULATE, "Volume", AST_AUDIOHOOK_MANIPULATE_ALL_RATES);
1283         audiohook_volume->audiohook.manipulate_callback = audiohook_volume_callback;
1284
1285         /* Attach the audiohook_volume blob to the datastore and attach to the channel */
1286         datastore->data = audiohook_volume;
1287         ast_channel_datastore_add(chan, datastore);
1288
1289         /* All is well... put the audiohook into motion */
1290         ast_audiohook_attach(chan, &audiohook_volume->audiohook);
1291
1292         return audiohook_volume;
1293 }
1294
1295 /*! \brief Adjust the volume on frames read from or written to a channel
1296  * \param chan Channel to muck with
1297  * \param direction Direction to set on
1298  * \param volume Value to adjust the volume by
1299  * \return Returns 0 on success, -1 on failure
1300  */
1301 int ast_audiohook_volume_set(struct ast_channel *chan, enum ast_audiohook_direction direction, int volume)
1302 {
1303         struct audiohook_volume *audiohook_volume = NULL;
1304
1305         /* Attempt to find the audiohook volume information, but only create it if we are not setting the adjustment value to zero */
1306         if (!(audiohook_volume = audiohook_volume_get(chan, (volume ? 1 : 0)))) {
1307                 return -1;
1308         }
1309
1310         /* Now based on the direction set the proper value */
1311         if (direction == AST_AUDIOHOOK_DIRECTION_READ || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
1312                 audiohook_volume->read_adjustment = volume;
1313         }
1314         if (direction == AST_AUDIOHOOK_DIRECTION_WRITE || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
1315                 audiohook_volume->write_adjustment = volume;
1316         }
1317
1318         return 0;
1319 }
1320
1321 /*! \brief Retrieve the volume adjustment value on frames read from or written to a channel
1322  * \param chan Channel to retrieve volume adjustment from
1323  * \param direction Direction to retrieve
1324  * \return Returns adjustment value
1325  */
1326 int ast_audiohook_volume_get(struct ast_channel *chan, enum ast_audiohook_direction direction)
1327 {
1328         struct audiohook_volume *audiohook_volume = NULL;
1329         int adjustment = 0;
1330
1331         /* Attempt to find the audiohook volume information, but do not create it as we only want to look at the values */
1332         if (!(audiohook_volume = audiohook_volume_get(chan, 0))) {
1333                 return 0;
1334         }
1335
1336         /* Grab the adjustment value based on direction given */
1337         if (direction == AST_AUDIOHOOK_DIRECTION_READ) {
1338                 adjustment = audiohook_volume->read_adjustment;
1339         } else if (direction == AST_AUDIOHOOK_DIRECTION_WRITE) {
1340                 adjustment = audiohook_volume->write_adjustment;
1341         }
1342
1343         return adjustment;
1344 }
1345
1346 /*! \brief Adjust the volume on frames read from or written to a channel
1347  * \param chan Channel to muck with
1348  * \param direction Direction to increase
1349  * \param volume Value to adjust the adjustment by
1350  * \return Returns 0 on success, -1 on failure
1351  */
1352 int ast_audiohook_volume_adjust(struct ast_channel *chan, enum ast_audiohook_direction direction, int volume)
1353 {
1354         struct audiohook_volume *audiohook_volume = NULL;
1355
1356         /* Attempt to find the audiohook volume information, and create an audiohook if none exists */
1357         if (!(audiohook_volume = audiohook_volume_get(chan, 1))) {
1358                 return -1;
1359         }
1360
1361         /* Based on the direction change the specific adjustment value */
1362         if (direction == AST_AUDIOHOOK_DIRECTION_READ || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
1363                 audiohook_volume->read_adjustment += volume;
1364         }
1365         if (direction == AST_AUDIOHOOK_DIRECTION_WRITE || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
1366                 audiohook_volume->write_adjustment += volume;
1367         }
1368
1369         return 0;
1370 }
1371
1372 /*! \brief Mute frames read from or written to a channel
1373  * \param chan Channel to muck with
1374  * \param source Type of audiohook
1375  * \param flag which flag to set / clear
1376  * \param clear set or clear
1377  * \return Returns 0 on success, -1 on failure
1378  */
1379 int ast_audiohook_set_mute(struct ast_channel *chan, const char *source, enum ast_audiohook_flags flag, int clear)
1380 {
1381         struct ast_audiohook *audiohook = NULL;
1382
1383         ast_channel_lock(chan);
1384
1385         /* Ensure the channel has audiohooks on it */
1386         if (!ast_channel_audiohooks(chan)) {
1387                 ast_channel_unlock(chan);
1388                 return -1;
1389         }
1390
1391         audiohook = find_audiohook_by_source(ast_channel_audiohooks(chan), source);
1392
1393         if (audiohook) {
1394                 if (clear) {
1395                         ast_clear_flag(audiohook, flag);
1396                 } else {
1397                         ast_set_flag(audiohook, flag);
1398                 }
1399         }
1400
1401         ast_channel_unlock(chan);
1402
1403         return (audiohook ? 0 : -1);
1404 }