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