Doxygen Updates Janitor Work
[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 /*! \brief Detach audiohooks from list and destroy said list
516  * \param audiohook_list List of audiohooks
517  * \return Returns 0 on success, -1 on failure
518  */
519 int ast_audiohook_detach_list(struct ast_audiohook_list *audiohook_list)
520 {
521         int i = 0;
522         struct ast_audiohook *audiohook = NULL;
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         return 0;
552 }
553
554 /*! \brief find an audiohook based on its source
555  * \param audiohook_list The list of audiohooks to search in
556  * \param source The source of the audiohook we wish to find
557  * \return Return the corresponding audiohook or NULL if it cannot be found.
558  */
559 static struct ast_audiohook *find_audiohook_by_source(struct ast_audiohook_list *audiohook_list, const char *source)
560 {
561         struct ast_audiohook *audiohook = NULL;
562
563         AST_LIST_TRAVERSE(&audiohook_list->spy_list, audiohook, list) {
564                 if (!strcasecmp(audiohook->source, source))
565                         return audiohook;
566         }
567
568         AST_LIST_TRAVERSE(&audiohook_list->whisper_list, audiohook, list) {
569                 if (!strcasecmp(audiohook->source, source))
570                         return audiohook;
571         }
572
573         AST_LIST_TRAVERSE(&audiohook_list->manipulate_list, audiohook, list) {
574                 if (!strcasecmp(audiohook->source, source))
575                         return audiohook;
576         }
577
578         return NULL;
579 }
580
581 void ast_audiohook_move_by_source(struct ast_channel *old_chan, struct ast_channel *new_chan, const char *source)
582 {
583         struct ast_audiohook *audiohook;
584         enum ast_audiohook_status oldstatus;
585
586         if (!ast_channel_audiohooks(old_chan) || !(audiohook = find_audiohook_by_source(ast_channel_audiohooks(old_chan), source))) {
587                 return;
588         }
589
590         /* By locking both channels and the audiohook, we can assure that
591          * another thread will not have a chance to read the audiohook's status
592          * as done, even though ast_audiohook_remove signals the trigger
593          * condition.
594          */
595         ast_audiohook_lock(audiohook);
596         oldstatus = audiohook->status;
597
598         ast_audiohook_remove(old_chan, audiohook);
599         ast_audiohook_attach(new_chan, audiohook);
600
601         audiohook->status = oldstatus;
602         ast_audiohook_unlock(audiohook);
603 }
604
605 /*! \brief Detach specified source audiohook from channel
606  * \param chan Channel to detach from
607  * \param source Name of source to detach
608  * \return Returns 0 on success, -1 on failure
609  */
610 int ast_audiohook_detach_source(struct ast_channel *chan, const char *source)
611 {
612         struct ast_audiohook *audiohook = NULL;
613
614         ast_channel_lock(chan);
615
616         /* Ensure the channel has audiohooks on it */
617         if (!ast_channel_audiohooks(chan)) {
618                 ast_channel_unlock(chan);
619                 return -1;
620         }
621
622         audiohook = find_audiohook_by_source(ast_channel_audiohooks(chan), source);
623
624         ast_channel_unlock(chan);
625
626         if (audiohook && audiohook->status != AST_AUDIOHOOK_STATUS_DONE)
627                 ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_SHUTDOWN);
628
629         return (audiohook ? 0 : -1);
630 }
631
632 /*!
633  * \brief Remove an audiohook from a specified channel
634  *
635  * \param chan Channel to remove from
636  * \param audiohook Audiohook to remove
637  *
638  * \return Returns 0 on success, -1 on failure
639  *
640  * \note The channel does not need to be locked before calling this function
641  */
642 int ast_audiohook_remove(struct ast_channel *chan, struct ast_audiohook *audiohook)
643 {
644         ast_channel_lock(chan);
645
646         if (!ast_channel_audiohooks(chan)) {
647                 ast_channel_unlock(chan);
648                 return -1;
649         }
650
651         if (audiohook->type == AST_AUDIOHOOK_TYPE_SPY)
652                 AST_LIST_REMOVE(&ast_channel_audiohooks(chan)->spy_list, audiohook, list);
653         else if (audiohook->type == AST_AUDIOHOOK_TYPE_WHISPER)
654                 AST_LIST_REMOVE(&ast_channel_audiohooks(chan)->whisper_list, audiohook, list);
655         else if (audiohook->type == AST_AUDIOHOOK_TYPE_MANIPULATE)
656                 AST_LIST_REMOVE(&ast_channel_audiohooks(chan)->manipulate_list, audiohook, list);
657
658         audiohook_list_set_samplerate_compatibility(ast_channel_audiohooks(chan));
659         ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
660
661         ast_channel_unlock(chan);
662
663         return 0;
664 }
665
666 /*! \brief Pass a DTMF frame off to be handled by the audiohook core
667  * \param chan Channel that the list is coming off of
668  * \param audiohook_list List of audiohooks
669  * \param direction Direction frame is coming in from
670  * \param frame The frame itself
671  * \return Return frame on success, NULL on failure
672  */
673 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)
674 {
675         struct ast_audiohook *audiohook = NULL;
676         int removed = 0;
677
678         AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->manipulate_list, audiohook, list) {
679                 ast_audiohook_lock(audiohook);
680                 if (audiohook->status != AST_AUDIOHOOK_STATUS_RUNNING) {
681                         AST_LIST_REMOVE_CURRENT(list);
682                         removed = 1;
683                         ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
684                         ast_audiohook_unlock(audiohook);
685                         audiohook->manipulate_callback(audiohook, NULL, NULL, 0);
686                         continue;
687                 }
688                 if (ast_test_flag(audiohook, AST_AUDIOHOOK_WANTS_DTMF))
689                         audiohook->manipulate_callback(audiohook, chan, frame, direction);
690                 ast_audiohook_unlock(audiohook);
691         }
692         AST_LIST_TRAVERSE_SAFE_END;
693
694         /* if an audiohook got removed, reset samplerate compatibility */
695         if (removed) {
696                 audiohook_list_set_samplerate_compatibility(audiohook_list);
697         }
698         return frame;
699 }
700
701 static struct ast_frame *audiohook_list_translate_to_slin(struct ast_audiohook_list *audiohook_list,
702         enum ast_audiohook_direction direction, struct ast_frame *frame)
703 {
704         struct ast_audiohook_translate *in_translate = (direction == AST_AUDIOHOOK_DIRECTION_READ ?
705                 &audiohook_list->in_translate[0] : &audiohook_list->in_translate[1]);
706         struct ast_frame *new_frame = frame;
707         struct ast_format tmp_fmt;
708         enum ast_format_id slin_id;
709
710         /* If we are capable of maintaining doing samplerates other that 8khz, update
711          * the internal audiohook_list's rate and higher samplerate audio arrives. By
712          * updating the list's rate, all the audiohooks in the list will be updated as well
713          * as the are written and read from. */
714         if (audiohook_list->native_slin_compatible) {
715                 audiohook_list->list_internal_samp_rate =
716                         MAX(ast_format_rate(&frame->subclass.format), audiohook_list->list_internal_samp_rate);
717         }
718
719         slin_id = ast_format_slin_by_rate(audiohook_list->list_internal_samp_rate);
720
721         if (frame->subclass.format.id == slin_id) {
722                 return new_frame;
723         }
724
725         if (ast_format_cmp(&frame->subclass.format, &in_translate->format) == AST_FORMAT_CMP_NOT_EQUAL) {
726                 if (in_translate->trans_pvt) {
727                         ast_translator_free_path(in_translate->trans_pvt);
728                 }
729                 if (!(in_translate->trans_pvt = ast_translator_build_path(ast_format_set(&tmp_fmt, slin_id, 0), &frame->subclass.format))) {
730                         return NULL;
731                 }
732                 ast_format_copy(&in_translate->format, &frame->subclass.format);
733         }
734         if (!(new_frame = ast_translate(in_translate->trans_pvt, frame, 0))) {
735                 return NULL;
736         }
737
738         return new_frame;
739 }
740
741 static struct ast_frame *audiohook_list_translate_to_native(struct ast_audiohook_list *audiohook_list,
742         enum ast_audiohook_direction direction, struct ast_frame *slin_frame, struct ast_format *outformat)
743 {
744         struct ast_audiohook_translate *out_translate = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook_list->out_translate[0] : &audiohook_list->out_translate[1]);
745         struct ast_frame *outframe = NULL;
746         if (ast_format_cmp(&slin_frame->subclass.format, outformat) == AST_FORMAT_CMP_NOT_EQUAL) {
747                 /* rebuild translators if necessary */
748                 if (ast_format_cmp(&out_translate->format, outformat) == AST_FORMAT_CMP_NOT_EQUAL) {
749                         if (out_translate->trans_pvt) {
750                                 ast_translator_free_path(out_translate->trans_pvt);
751                         }
752                         if (!(out_translate->trans_pvt = ast_translator_build_path(outformat, &slin_frame->subclass.format))) {
753                                 return NULL;
754                         }
755                         ast_format_copy(&out_translate->format, outformat);
756                 }
757                 /* translate back to the format the frame came in as. */
758                 if (!(outframe = ast_translate(out_translate->trans_pvt, slin_frame, 0))) {
759                         return NULL;
760                 }
761         }
762         return outframe;
763 }
764
765 /*!
766  * \brief Pass an AUDIO frame off to be handled by the audiohook core
767  *
768  * \details
769  * This function has 3 ast_frames and 3 parts to handle each.  At the beginning of this
770  * function all 3 frames, start_frame, middle_frame, and end_frame point to the initial
771  * input frame.
772  *
773  * Part_1: Translate the start_frame into SLINEAR audio if it is not already in that
774  *         format.  The result of this part is middle_frame is guaranteed to be in
775  *         SLINEAR format for Part_2.
776  * Part_2: Send middle_frame off to spies and manipulators.  At this point middle_frame is
777  *         either a new frame as result of the translation, or points directly to the start_frame
778  *         because no translation to SLINEAR audio was required.
779  * Part_3: Translate end_frame's audio back into the format of start frame if necessary.  This
780  *         is only necessary if manipulation of middle_frame occurred.
781  *
782  * \param chan Channel that the list is coming off of
783  * \param audiohook_list List of audiohooks
784  * \param direction Direction frame is coming in from
785  * \param frame The frame itself
786  * \return Return frame on success, NULL on failure
787  */
788 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)
789 {
790         struct ast_frame *start_frame = frame, *middle_frame = frame, *end_frame = frame;
791         struct ast_audiohook *audiohook = NULL;
792         int samples;
793         int middle_frame_manipulated = 0;
794         int removed = 0;
795
796         /* ---Part_1. translate start_frame to SLINEAR if necessary. */
797         if (!(middle_frame = audiohook_list_translate_to_slin(audiohook_list, direction, start_frame))) {
798                 return frame;
799         }
800         samples = middle_frame->samples;
801
802         /* ---Part_2: Send middle_frame to spy and manipulator lists.  middle_frame is guaranteed to be SLINEAR here.*/
803         /* Queue up signed linear frame to each spy */
804         AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->spy_list, audiohook, list) {
805                 ast_audiohook_lock(audiohook);
806                 if (audiohook->status != AST_AUDIOHOOK_STATUS_RUNNING) {
807                         AST_LIST_REMOVE_CURRENT(list);
808                         removed = 1;
809                         ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
810                         ast_audiohook_unlock(audiohook);
811                         continue;
812                 }
813                 audiohook_set_internal_rate(audiohook, audiohook_list->list_internal_samp_rate, 1);
814                 ast_audiohook_write_frame(audiohook, direction, middle_frame);
815                 ast_audiohook_unlock(audiohook);
816         }
817         AST_LIST_TRAVERSE_SAFE_END;
818
819         /* If this frame is being written out to the channel then we need to use whisper sources */
820         if (direction == AST_AUDIOHOOK_DIRECTION_WRITE && !AST_LIST_EMPTY(&audiohook_list->whisper_list)) {
821                 int i = 0;
822                 short read_buf[samples], combine_buf[samples], *data1 = NULL, *data2 = NULL;
823                 memset(&combine_buf, 0, sizeof(combine_buf));
824                 AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->whisper_list, audiohook, list) {
825                         ast_audiohook_lock(audiohook);
826                         if (audiohook->status != AST_AUDIOHOOK_STATUS_RUNNING) {
827                                 AST_LIST_REMOVE_CURRENT(list);
828                                 removed = 1;
829                                 ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
830                                 ast_audiohook_unlock(audiohook);
831                                 continue;
832                         }
833                         audiohook_set_internal_rate(audiohook, audiohook_list->list_internal_samp_rate, 1);
834                         if (ast_slinfactory_available(&audiohook->write_factory) >= samples && ast_slinfactory_read(&audiohook->write_factory, read_buf, samples)) {
835                                 /* Take audio from this whisper source and combine it into our main buffer */
836                                 for (i = 0, data1 = combine_buf, data2 = read_buf; i < samples; i++, data1++, data2++)
837                                         ast_slinear_saturated_add(data1, data2);
838                         }
839                         ast_audiohook_unlock(audiohook);
840                 }
841                 AST_LIST_TRAVERSE_SAFE_END;
842                 /* We take all of the combined whisper sources and combine them into the audio being written out */
843                 for (i = 0, data1 = middle_frame->data.ptr, data2 = combine_buf; i < samples; i++, data1++, data2++) {
844                         ast_slinear_saturated_add(data1, data2);
845                 }
846                 middle_frame_manipulated = 1;
847         }
848
849         /* Pass off frame to manipulate audiohooks */
850         if (!AST_LIST_EMPTY(&audiohook_list->manipulate_list)) {
851                 AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->manipulate_list, audiohook, list) {
852                         ast_audiohook_lock(audiohook);
853                         if (audiohook->status != AST_AUDIOHOOK_STATUS_RUNNING) {
854                                 AST_LIST_REMOVE_CURRENT(list);
855                                 removed = 1;
856                                 ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
857                                 ast_audiohook_unlock(audiohook);
858                                 /* We basically drop all of our links to the manipulate audiohook and prod it to do it's own destructive things */
859                                 audiohook->manipulate_callback(audiohook, chan, NULL, direction);
860                                 continue;
861                         }
862                         audiohook_set_internal_rate(audiohook, audiohook_list->list_internal_samp_rate, 1);
863                         /* Feed in frame to manipulation. */
864                         if (audiohook->manipulate_callback(audiohook, chan, middle_frame, direction)) {
865                                 /* XXX IGNORE FAILURE */
866
867                                 /* If the manipulation fails then the frame will be returned in its original state.
868                                  * Since there are potentially more manipulator callbacks in the list, no action should
869                                  * be taken here to exit early. */
870                         }
871                         ast_audiohook_unlock(audiohook);
872                 }
873                 AST_LIST_TRAVERSE_SAFE_END;
874                 middle_frame_manipulated = 1;
875         }
876
877         /* ---Part_3: Decide what to do with the end_frame (whether to transcode or not) */
878         if (middle_frame_manipulated) {
879                 if (!(end_frame = audiohook_list_translate_to_native(audiohook_list, direction, middle_frame, &start_frame->subclass.format))) {
880                         /* translation failed, so just pass back the input frame */
881                         end_frame = start_frame;
882                 }
883         } else {
884                 end_frame = start_frame;
885         }
886         /* clean up our middle_frame if required */
887         if (middle_frame != end_frame) {
888                 ast_frfree(middle_frame);
889                 middle_frame = NULL;
890         }
891
892         /* Before returning, if an audiohook got removed, reset samplerate compatibility */
893         if (removed) {
894                 audiohook_list_set_samplerate_compatibility(audiohook_list);
895         }
896
897         return end_frame;
898 }
899
900 int ast_audiohook_write_list_empty(struct ast_audiohook_list *audiohook_list)
901 {
902         if (AST_LIST_EMPTY(&audiohook_list->spy_list) &&
903                 AST_LIST_EMPTY(&audiohook_list->whisper_list) &&
904                 AST_LIST_EMPTY(&audiohook_list->manipulate_list)) {
905
906                 return 1;
907         }
908         return 0;
909 }
910
911 /*! \brief Pass a frame off to be handled by the audiohook core
912  * \param chan Channel that the list is coming off of
913  * \param audiohook_list List of audiohooks
914  * \param direction Direction frame is coming in from
915  * \param frame The frame itself
916  * \return Return frame on success, NULL on failure
917  */
918 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)
919 {
920         /* Pass off frame to it's respective list write function */
921         if (frame->frametype == AST_FRAME_VOICE)
922                 return audio_audiohook_write_list(chan, audiohook_list, direction, frame);
923         else if (frame->frametype == AST_FRAME_DTMF)
924                 return dtmf_audiohook_write_list(chan, audiohook_list, direction, frame);
925         else
926                 return frame;
927 }
928
929 /*! \brief Wait for audiohook trigger to be triggered
930  * \param audiohook Audiohook to wait on
931  */
932 void ast_audiohook_trigger_wait(struct ast_audiohook *audiohook)
933 {
934         struct timeval wait;
935         struct timespec ts;
936
937         wait = ast_tvadd(ast_tvnow(), ast_samp2tv(50000, 1000));
938         ts.tv_sec = wait.tv_sec;
939         ts.tv_nsec = wait.tv_usec * 1000;
940
941         ast_cond_timedwait(&audiohook->trigger, &audiohook->lock, &ts);
942
943         return;
944 }
945
946 /* Count number of channel audiohooks by type, regardless of type */
947 int ast_channel_audiohook_count_by_source(struct ast_channel *chan, const char *source, enum ast_audiohook_type type)
948 {
949         int count = 0;
950         struct ast_audiohook *ah = NULL;
951
952         if (!ast_channel_audiohooks(chan))
953                 return -1;
954
955         switch (type) {
956                 case AST_AUDIOHOOK_TYPE_SPY:
957                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->spy_list, ah, list) {
958                                 if (!strcmp(ah->source, source)) {
959                                         count++;
960                                 }
961                         }
962                         break;
963                 case AST_AUDIOHOOK_TYPE_WHISPER:
964                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->whisper_list, ah, list) {
965                                 if (!strcmp(ah->source, source)) {
966                                         count++;
967                                 }
968                         }
969                         break;
970                 case AST_AUDIOHOOK_TYPE_MANIPULATE:
971                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->manipulate_list, ah, list) {
972                                 if (!strcmp(ah->source, source)) {
973                                         count++;
974                                 }
975                         }
976                         break;
977                 default:
978                         ast_debug(1, "Invalid audiohook type supplied, (%d)\n", type);
979                         return -1;
980         }
981
982         return count;
983 }
984
985 /* Count number of channel audiohooks by type that are running */
986 int ast_channel_audiohook_count_by_source_running(struct ast_channel *chan, const char *source, enum ast_audiohook_type type)
987 {
988         int count = 0;
989         struct ast_audiohook *ah = NULL;
990         if (!ast_channel_audiohooks(chan))
991                 return -1;
992
993         switch (type) {
994                 case AST_AUDIOHOOK_TYPE_SPY:
995                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->spy_list, ah, list) {
996                                 if ((!strcmp(ah->source, source)) && (ah->status == AST_AUDIOHOOK_STATUS_RUNNING))
997                                         count++;
998                         }
999                         break;
1000                 case AST_AUDIOHOOK_TYPE_WHISPER:
1001                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->whisper_list, ah, list) {
1002                                 if ((!strcmp(ah->source, source)) && (ah->status == AST_AUDIOHOOK_STATUS_RUNNING))
1003                                         count++;
1004                         }
1005                         break;
1006                 case AST_AUDIOHOOK_TYPE_MANIPULATE:
1007                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->manipulate_list, ah, list) {
1008                                 if ((!strcmp(ah->source, source)) && (ah->status == AST_AUDIOHOOK_STATUS_RUNNING))
1009                                         count++;
1010                         }
1011                         break;
1012                 default:
1013                         ast_debug(1, "Invalid audiohook type supplied, (%d)\n", type);
1014                         return -1;
1015         }
1016         return count;
1017 }
1018
1019 /*! \brief Audiohook volume adjustment structure */
1020 struct audiohook_volume {
1021         struct ast_audiohook audiohook; /*!< Audiohook attached to the channel */
1022         int read_adjustment;            /*!< Value to adjust frames read from the channel by */
1023         int write_adjustment;           /*!< Value to adjust frames written to the channel by */
1024 };
1025
1026 /*! \brief Callback used to destroy the audiohook volume datastore
1027  * \param data Volume information structure
1028  * \return Returns nothing
1029  */
1030 static void audiohook_volume_destroy(void *data)
1031 {
1032         struct audiohook_volume *audiohook_volume = data;
1033
1034         /* Destroy the audiohook as it is no longer in use */
1035         ast_audiohook_destroy(&audiohook_volume->audiohook);
1036
1037         /* Finally free ourselves, we are of no more use */
1038         ast_free(audiohook_volume);
1039
1040         return;
1041 }
1042
1043 /*! \brief Datastore used to store audiohook volume information */
1044 static const struct ast_datastore_info audiohook_volume_datastore = {
1045         .type = "Volume",
1046         .destroy = audiohook_volume_destroy,
1047 };
1048
1049 /*! \brief Helper function which actually gets called by audiohooks to perform the adjustment
1050  * \param audiohook Audiohook attached to the channel
1051  * \param chan Channel we are attached to
1052  * \param frame Frame of audio we want to manipulate
1053  * \param direction Direction the audio came in from
1054  * \return Returns 0 on success, -1 on failure
1055  */
1056 static int audiohook_volume_callback(struct ast_audiohook *audiohook, struct ast_channel *chan, struct ast_frame *frame, enum ast_audiohook_direction direction)
1057 {
1058         struct ast_datastore *datastore = NULL;
1059         struct audiohook_volume *audiohook_volume = NULL;
1060         int *gain = NULL;
1061
1062         /* If the audiohook is shutting down don't even bother */
1063         if (audiohook->status == AST_AUDIOHOOK_STATUS_DONE) {
1064                 return 0;
1065         }
1066
1067         /* Try to find the datastore containg adjustment information, if we can't just bail out */
1068         if (!(datastore = ast_channel_datastore_find(chan, &audiohook_volume_datastore, NULL))) {
1069                 return 0;
1070         }
1071
1072         audiohook_volume = datastore->data;
1073
1074         /* Based on direction grab the appropriate adjustment value */
1075         if (direction == AST_AUDIOHOOK_DIRECTION_READ) {
1076                 gain = &audiohook_volume->read_adjustment;
1077         } else if (direction == AST_AUDIOHOOK_DIRECTION_WRITE) {
1078                 gain = &audiohook_volume->write_adjustment;
1079         }
1080
1081         /* If an adjustment value is present modify the frame */
1082         if (gain && *gain) {
1083                 ast_frame_adjust_volume(frame, *gain);
1084         }
1085
1086         return 0;
1087 }
1088
1089 /*! \brief Helper function which finds and optionally creates an audiohook_volume_datastore datastore on a channel
1090  * \param chan Channel to look on
1091  * \param create Whether to create the datastore if not found
1092  * \return Returns audiohook_volume structure on success, NULL on failure
1093  */
1094 static struct audiohook_volume *audiohook_volume_get(struct ast_channel *chan, int create)
1095 {
1096         struct ast_datastore *datastore = NULL;
1097         struct audiohook_volume *audiohook_volume = NULL;
1098
1099         /* If we are able to find the datastore return the contents (which is actually an audiohook_volume structure) */
1100         if ((datastore = ast_channel_datastore_find(chan, &audiohook_volume_datastore, NULL))) {
1101                 return datastore->data;
1102         }
1103
1104         /* 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 */
1105         if (!create || !(datastore = ast_datastore_alloc(&audiohook_volume_datastore, NULL))) {
1106                 return NULL;
1107         }
1108
1109         /* Create a new audiohook_volume structure to contain our adjustments and audiohook */
1110         if (!(audiohook_volume = ast_calloc(1, sizeof(*audiohook_volume)))) {
1111                 ast_datastore_free(datastore);
1112                 return NULL;
1113         }
1114
1115         /* Setup our audiohook structure so we can manipulate the audio */
1116         ast_audiohook_init(&audiohook_volume->audiohook, AST_AUDIOHOOK_TYPE_MANIPULATE, "Volume", AST_AUDIOHOOK_MANIPULATE_ALL_RATES);
1117         audiohook_volume->audiohook.manipulate_callback = audiohook_volume_callback;
1118
1119         /* Attach the audiohook_volume blob to the datastore and attach to the channel */
1120         datastore->data = audiohook_volume;
1121         ast_channel_datastore_add(chan, datastore);
1122
1123         /* All is well... put the audiohook into motion */
1124         ast_audiohook_attach(chan, &audiohook_volume->audiohook);
1125
1126         return audiohook_volume;
1127 }
1128
1129 /*! \brief Adjust the volume on frames read from or written to a channel
1130  * \param chan Channel to muck with
1131  * \param direction Direction to set on
1132  * \param volume Value to adjust the volume by
1133  * \return Returns 0 on success, -1 on failure
1134  */
1135 int ast_audiohook_volume_set(struct ast_channel *chan, enum ast_audiohook_direction direction, int volume)
1136 {
1137         struct audiohook_volume *audiohook_volume = NULL;
1138
1139         /* Attempt to find the audiohook volume information, but only create it if we are not setting the adjustment value to zero */
1140         if (!(audiohook_volume = audiohook_volume_get(chan, (volume ? 1 : 0)))) {
1141                 return -1;
1142         }
1143
1144         /* Now based on the direction set the proper value */
1145         if (direction == AST_AUDIOHOOK_DIRECTION_READ || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
1146                 audiohook_volume->read_adjustment = volume;
1147         }
1148         if (direction == AST_AUDIOHOOK_DIRECTION_WRITE || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
1149                 audiohook_volume->write_adjustment = volume;
1150         }
1151
1152         return 0;
1153 }
1154
1155 /*! \brief Retrieve the volume adjustment value on frames read from or written to a channel
1156  * \param chan Channel to retrieve volume adjustment from
1157  * \param direction Direction to retrieve
1158  * \return Returns adjustment value
1159  */
1160 int ast_audiohook_volume_get(struct ast_channel *chan, enum ast_audiohook_direction direction)
1161 {
1162         struct audiohook_volume *audiohook_volume = NULL;
1163         int adjustment = 0;
1164
1165         /* Attempt to find the audiohook volume information, but do not create it as we only want to look at the values */
1166         if (!(audiohook_volume = audiohook_volume_get(chan, 0))) {
1167                 return 0;
1168         }
1169
1170         /* Grab the adjustment value based on direction given */
1171         if (direction == AST_AUDIOHOOK_DIRECTION_READ) {
1172                 adjustment = audiohook_volume->read_adjustment;
1173         } else if (direction == AST_AUDIOHOOK_DIRECTION_WRITE) {
1174                 adjustment = audiohook_volume->write_adjustment;
1175         }
1176
1177         return adjustment;
1178 }
1179
1180 /*! \brief Adjust the volume on frames read from or written to a channel
1181  * \param chan Channel to muck with
1182  * \param direction Direction to increase
1183  * \param volume Value to adjust the adjustment by
1184  * \return Returns 0 on success, -1 on failure
1185  */
1186 int ast_audiohook_volume_adjust(struct ast_channel *chan, enum ast_audiohook_direction direction, int volume)
1187 {
1188         struct audiohook_volume *audiohook_volume = NULL;
1189
1190         /* Attempt to find the audiohook volume information, and create an audiohook if none exists */
1191         if (!(audiohook_volume = audiohook_volume_get(chan, 1))) {
1192                 return -1;
1193         }
1194
1195         /* Based on the direction change the specific adjustment value */
1196         if (direction == AST_AUDIOHOOK_DIRECTION_READ || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
1197                 audiohook_volume->read_adjustment += volume;
1198         }
1199         if (direction == AST_AUDIOHOOK_DIRECTION_WRITE || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
1200                 audiohook_volume->write_adjustment += volume;
1201         }
1202
1203         return 0;
1204 }
1205
1206 /*! \brief Mute frames read from or written to a channel
1207  * \param chan Channel to muck with
1208  * \param source Type of audiohook
1209  * \param flag which flag to set / clear
1210  * \param clear set or clear
1211  * \return Returns 0 on success, -1 on failure
1212  */
1213 int ast_audiohook_set_mute(struct ast_channel *chan, const char *source, enum ast_audiohook_flags flag, int clear)
1214 {
1215         struct ast_audiohook *audiohook = NULL;
1216
1217         ast_channel_lock(chan);
1218
1219         /* Ensure the channel has audiohooks on it */
1220         if (!ast_channel_audiohooks(chan)) {
1221                 ast_channel_unlock(chan);
1222                 return -1;
1223         }
1224
1225         audiohook = find_audiohook_by_source(ast_channel_audiohooks(chan), source);
1226
1227         if (audiohook) {
1228                 if (clear) {
1229                         ast_clear_flag(audiohook, flag);
1230                 } else {
1231                         ast_set_flag(audiohook, flag);
1232                 }
1233         }
1234
1235         ast_channel_unlock(chan);
1236
1237         return (audiohook ? 0 : -1);
1238 }