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