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