Clean up doxygen warnings
[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  * \param audiohook Audiohook structure
101  * \param type
102  * \param init, source, init_flags
103  * \return Returns 0 on success, -1 on failure
104  */
105 int ast_audiohook_init(struct ast_audiohook *audiohook, enum ast_audiohook_type type, const char *source, enum ast_audiohook_init_flags init_flags)
106 {
107         /* Need to keep the type and source */
108         audiohook->type = type;
109         audiohook->source = source;
110
111         /* Initialize lock that protects our audiohook */
112         ast_mutex_init(&audiohook->lock);
113         ast_cond_init(&audiohook->trigger, NULL);
114
115         audiohook->init_flags = init_flags;
116
117         /* initialize internal rate at 8khz, this will adjust if necessary */
118         audiohook_set_internal_rate(audiohook, 8000, 0);
119
120         /* Since we are just starting out... this audiohook is new */
121         ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_NEW);
122
123         return 0;
124 }
125
126 /*! \brief Destroys an audiohook structure
127  * \param audiohook Audiohook structure
128  * \return Returns 0 on success, -1 on failure
129  */
130 int ast_audiohook_destroy(struct ast_audiohook *audiohook)
131 {
132         /* Drop the factories used by this audiohook type */
133         switch (audiohook->type) {
134         case AST_AUDIOHOOK_TYPE_SPY:
135                 ast_slinfactory_destroy(&audiohook->read_factory);
136         case AST_AUDIOHOOK_TYPE_WHISPER:
137                 ast_slinfactory_destroy(&audiohook->write_factory);
138                 break;
139         default:
140                 break;
141         }
142
143         /* Destroy translation path if present */
144         if (audiohook->trans_pvt)
145                 ast_translator_free_path(audiohook->trans_pvt);
146
147         /* Lock and trigger be gone! */
148         ast_cond_destroy(&audiohook->trigger);
149         ast_mutex_destroy(&audiohook->lock);
150
151         return 0;
152 }
153
154 /*! \brief Writes a frame into the audiohook structure
155  * \param audiohook Audiohook structure
156  * \param direction Direction the audio frame came from
157  * \param frame Frame to write in
158  * \return Returns 0 on success, -1 on failure
159  */
160 int ast_audiohook_write_frame(struct ast_audiohook *audiohook, enum ast_audiohook_direction direction, struct ast_frame *frame)
161 {
162         struct ast_slinfactory *factory = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook->read_factory : &audiohook->write_factory);
163         struct ast_slinfactory *other_factory = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook->write_factory : &audiohook->read_factory);
164         struct timeval *rwtime = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook->read_time : &audiohook->write_time), previous_time = *rwtime;
165         int our_factory_samples;
166         int our_factory_ms;
167         int other_factory_samples;
168         int other_factory_ms;
169         int muteme = 0;
170
171         /* Update last feeding time to be current */
172         *rwtime = ast_tvnow();
173
174         our_factory_samples = ast_slinfactory_available(factory);
175         our_factory_ms = ast_tvdiff_ms(*rwtime, previous_time) + (our_factory_samples / (audiohook->hook_internal_samp_rate / 1000));
176         other_factory_samples = ast_slinfactory_available(other_factory);
177         other_factory_ms = other_factory_samples / (audiohook->hook_internal_samp_rate / 1000);
178
179         if (ast_test_flag(audiohook, AST_AUDIOHOOK_TRIGGER_SYNC) && other_factory_samples && (our_factory_ms - other_factory_ms > AST_AUDIOHOOK_SYNC_TOLERANCE)) {
180                 ast_debug(1, "Flushing audiohook %p so it remains in sync\n", audiohook);
181                 ast_slinfactory_flush(factory);
182                 ast_slinfactory_flush(other_factory);
183         }
184
185         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))) {
186                 ast_debug(1, "Audiohook %p has stale audio in its factories. Flushing them both\n", audiohook);
187                 ast_slinfactory_flush(factory);
188                 ast_slinfactory_flush(other_factory);
189         }
190
191         /* swap frame data for zeros if mute is required */
192         if ((ast_test_flag(audiohook, AST_AUDIOHOOK_MUTE_READ) && (direction == AST_AUDIOHOOK_DIRECTION_READ)) ||
193                 (ast_test_flag(audiohook, AST_AUDIOHOOK_MUTE_WRITE) && (direction == AST_AUDIOHOOK_DIRECTION_WRITE)) ||
194                 (ast_test_flag(audiohook, AST_AUDIOHOOK_MUTE_READ | AST_AUDIOHOOK_MUTE_WRITE) == (AST_AUDIOHOOK_MUTE_READ | AST_AUDIOHOOK_MUTE_WRITE))) {
195                         muteme = 1;
196         }
197
198         if (muteme && frame->datalen > 0) {
199                 ast_frame_clear(frame);
200         }
201
202         /* Write frame out to respective factory */
203         ast_slinfactory_feed(factory, frame);
204
205         /* If we need to notify the respective handler of this audiohook, do so */
206         if ((ast_test_flag(audiohook, AST_AUDIOHOOK_TRIGGER_MODE) == AST_AUDIOHOOK_TRIGGER_READ) && (direction == AST_AUDIOHOOK_DIRECTION_READ)) {
207                 ast_cond_signal(&audiohook->trigger);
208         } else if ((ast_test_flag(audiohook, AST_AUDIOHOOK_TRIGGER_MODE) == AST_AUDIOHOOK_TRIGGER_WRITE) && (direction == AST_AUDIOHOOK_DIRECTION_WRITE)) {
209                 ast_cond_signal(&audiohook->trigger);
210         } else if (ast_test_flag(audiohook, AST_AUDIOHOOK_TRIGGER_SYNC)) {
211                 ast_cond_signal(&audiohook->trigger);
212         }
213
214         return 0;
215 }
216
217 static struct ast_frame *audiohook_read_frame_single(struct ast_audiohook *audiohook, size_t samples, enum ast_audiohook_direction direction)
218 {
219         struct ast_slinfactory *factory = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook->read_factory : &audiohook->write_factory);
220         int vol = (direction == AST_AUDIOHOOK_DIRECTION_READ ? audiohook->options.read_volume : audiohook->options.write_volume);
221         short buf[samples];
222         struct ast_frame frame = {
223                 .frametype = AST_FRAME_VOICE,
224                 .data.ptr = buf,
225                 .datalen = sizeof(buf),
226                 .samples = samples,
227         };
228         ast_format_set(&frame.subclass.format, ast_format_slin_by_rate(audiohook->hook_internal_samp_rate), 0);
229
230         /* Ensure the factory is able to give us the samples we want */
231         if (samples > ast_slinfactory_available(factory))
232                 return NULL;
233
234         /* Read data in from factory */
235         if (!ast_slinfactory_read(factory, buf, samples))
236                 return NULL;
237
238         /* If a volume adjustment needs to be applied apply it */
239         if (vol)
240                 ast_frame_adjust_volume(&frame, vol);
241
242         return ast_frdup(&frame);
243 }
244
245 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)
246 {
247         int i = 0, usable_read, usable_write;
248         short buf1[samples], buf2[samples], *read_buf = NULL, *write_buf = NULL, *final_buf = NULL, *data1 = NULL, *data2 = NULL;
249         struct ast_frame frame = {
250                 .frametype = AST_FRAME_VOICE,
251                 .data.ptr = NULL,
252                 .datalen = sizeof(buf1),
253                 .samples = samples,
254         };
255         ast_format_set(&frame.subclass.format, ast_format_slin_by_rate(audiohook->hook_internal_samp_rate), 0);
256
257         /* Make sure both factories have the required samples */
258         usable_read = (ast_slinfactory_available(&audiohook->read_factory) >= samples ? 1 : 0);
259         usable_write = (ast_slinfactory_available(&audiohook->write_factory) >= samples ? 1 : 0);
260
261         if (!usable_read && !usable_write) {
262                 /* If both factories are unusable bail out */
263                 ast_debug(1, "Read factory %p and write factory %p both fail to provide %zd samples\n", &audiohook->read_factory, &audiohook->write_factory, samples);
264                 return NULL;
265         }
266
267         /* If we want to provide only a read factory make sure we aren't waiting for other audio */
268         if (usable_read && !usable_write && (ast_tvdiff_ms(ast_tvnow(), audiohook->write_time) < (samples/8)*2)) {
269                 ast_debug(3, "Write factory %p was pretty quick last time, waiting for them.\n", &audiohook->write_factory);
270                 return NULL;
271         }
272
273         /* If we want to provide only a write factory make sure we aren't waiting for other audio */
274         if (usable_write && !usable_read && (ast_tvdiff_ms(ast_tvnow(), audiohook->read_time) < (samples/8)*2)) {
275                 ast_debug(3, "Read factory %p was pretty quick last time, waiting for them.\n", &audiohook->read_factory);
276                 return NULL;
277         }
278
279         /* Start with the read factory... if there are enough samples, read them in */
280         if (usable_read) {
281                 if (ast_slinfactory_read(&audiohook->read_factory, buf1, samples)) {
282                         read_buf = buf1;
283                         /* Adjust read volume if need be */
284                         if (audiohook->options.read_volume) {
285                                 int count = 0;
286                                 short adjust_value = abs(audiohook->options.read_volume);
287                                 for (count = 0; count < samples; count++) {
288                                         if (audiohook->options.read_volume > 0)
289                                                 ast_slinear_saturated_multiply(&buf1[count], &adjust_value);
290                                         else if (audiohook->options.read_volume < 0)
291                                                 ast_slinear_saturated_divide(&buf1[count], &adjust_value);
292                                 }
293                         }
294                 }
295         } else {
296                 ast_debug(1, "Failed to get %d samples from read factory %p\n", (int)samples, &audiohook->read_factory);
297         }
298
299         /* Move on to the write factory... if there are enough samples, read them in */
300         if (usable_write) {
301                 if (ast_slinfactory_read(&audiohook->write_factory, buf2, samples)) {
302                         write_buf = buf2;
303                         /* Adjust write volume if need be */
304                         if (audiohook->options.write_volume) {
305                                 int count = 0;
306                                 short adjust_value = abs(audiohook->options.write_volume);
307                                 for (count = 0; count < samples; count++) {
308                                         if (audiohook->options.write_volume > 0)
309                                                 ast_slinear_saturated_multiply(&buf2[count], &adjust_value);
310                                         else if (audiohook->options.write_volume < 0)
311                                                 ast_slinear_saturated_divide(&buf2[count], &adjust_value);
312                                 }
313                         }
314                 }
315         } else {
316                 ast_debug(1, "Failed to get %d samples from write factory %p\n", (int)samples, &audiohook->write_factory);
317         }
318
319         /* Basically we figure out which buffer to use... and if mixing can be done here */
320         if (read_buf && read_reference) {
321                 frame.data.ptr = buf1;
322                 *read_reference = ast_frdup(&frame);
323         }
324         if (write_buf && write_reference) {
325                 frame.data.ptr = buf2;
326                 *write_reference = ast_frdup(&frame);
327         }
328
329         if (read_buf && write_buf) {
330                 for (i = 0, data1 = read_buf, data2 = write_buf; i < samples; i++, data1++, data2++) {
331                         ast_slinear_saturated_add(data1, data2);
332                 }
333                 final_buf = buf1;
334         } else if (read_buf) {
335                 final_buf = buf1;
336         } else if (write_buf) {
337                 final_buf = buf2;
338         } else {
339                 return NULL;
340         }
341
342         /* Make the final buffer part of the frame, so it gets duplicated fine */
343         frame.data.ptr = final_buf;
344
345         /* Yahoo, a combined copy of the audio! */
346         return ast_frdup(&frame);
347 }
348
349 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)
350 {
351         struct ast_frame *read_frame = NULL, *final_frame = NULL;
352         struct ast_format tmp_fmt;
353         int samples_converted;
354
355         /* the number of samples requested is based on the format they are requesting.  Inorder
356          * to process this correctly samples must be converted to our internal sample rate */
357         if (audiohook->hook_internal_samp_rate == ast_format_rate(format)) {
358                 samples_converted = samples;
359         } else if (audiohook->hook_internal_samp_rate > ast_format_rate(format)) {
360                 samples_converted = samples * (audiohook->hook_internal_samp_rate / (float) ast_format_rate(format));
361         } else {
362                 samples_converted = samples * (ast_format_rate(format) / (float) audiohook->hook_internal_samp_rate);
363         }
364
365         if (!(read_frame = (direction == AST_AUDIOHOOK_DIRECTION_BOTH ?
366                 audiohook_read_frame_both(audiohook, samples_converted, read_reference, write_reference) :
367                 audiohook_read_frame_single(audiohook, samples_converted, direction)))) {
368                 return NULL;
369         }
370
371         /* If they don't want signed linear back out, we'll have to send it through the translation path */
372         if (format->id != ast_format_slin_by_rate(audiohook->hook_internal_samp_rate)) {
373                 /* Rebuild translation path if different format then previously */
374                 if (ast_format_cmp(format, &audiohook->format) == AST_FORMAT_CMP_NOT_EQUAL) {
375                         if (audiohook->trans_pvt) {
376                                 ast_translator_free_path(audiohook->trans_pvt);
377                                 audiohook->trans_pvt = NULL;
378                         }
379
380                         /* 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 */
381                         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)))) {
382                                 ast_frfree(read_frame);
383                                 return NULL;
384                         }
385                         ast_format_copy(&audiohook->format, format);
386                 }
387                 /* Convert to requested format, and allow the read in frame to be freed */
388                 final_frame = ast_translate(audiohook->trans_pvt, read_frame, 1);
389         } else {
390                 final_frame = read_frame;
391         }
392
393         return final_frame;
394 }
395
396 /*! \brief Reads a frame in from the audiohook structure
397  * \param audiohook Audiohook structure
398  * \param samples Number of samples wanted in requested output format
399  * \param direction Direction the audio frame came from
400  * \param format Format of frame remote side wants back
401  * \return Returns frame on success, NULL on failure
402  */
403 struct ast_frame *ast_audiohook_read_frame(struct ast_audiohook *audiohook, size_t samples, enum ast_audiohook_direction direction, struct ast_format *format)
404 {
405         return audiohook_read_frame_helper(audiohook, samples, direction, format, NULL, NULL);
406 }
407
408 /*! \brief Reads a frame in from the audiohook structure
409  * \param audiohook Audiohook structure
410  * \param samples Number of samples wanted
411  * \param direction Direction the audio frame came from
412  * \param format Format of frame remote side wants back
413  * \param read_frame frame pointer for copying read frame data
414  * \param write_frame frame pointer for copying write frame data
415  * \return Returns frame on success, NULL on failure
416  */
417 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)
418 {
419         return audiohook_read_frame_helper(audiohook, samples, AST_AUDIOHOOK_DIRECTION_BOTH, format, read_frame, write_frame);
420 }
421
422 static void audiohook_list_set_samplerate_compatibility(struct ast_audiohook_list *audiohook_list)
423 {
424         struct ast_audiohook *ah = NULL;
425         audiohook_list->native_slin_compatible = 1;
426         AST_LIST_TRAVERSE(&audiohook_list->manipulate_list, ah, list) {
427                 if (!(ah->init_flags & AST_AUDIOHOOK_MANIPULATE_ALL_RATES)) {
428                         audiohook_list->native_slin_compatible = 0;
429                         return;
430                 }
431         }
432 }
433
434 /*! \brief Attach audiohook to channel
435  * \param chan Channel
436  * \param audiohook Audiohook structure
437  * \return Returns 0 on success, -1 on failure
438  */
439 int ast_audiohook_attach(struct ast_channel *chan, struct ast_audiohook *audiohook)
440 {
441         ast_channel_lock(chan);
442
443         if (!ast_channel_audiohooks(chan)) {
444                 struct ast_audiohook_list *ahlist;
445                 /* Whoops... allocate a new structure */
446                 if (!(ahlist = ast_calloc(1, sizeof(*ahlist)))) {
447                         ast_channel_unlock(chan);
448                         return -1;
449                 }
450                 ast_channel_audiohooks_set(chan, ahlist);
451                 AST_LIST_HEAD_INIT_NOLOCK(&ast_channel_audiohooks(chan)->spy_list);
452                 AST_LIST_HEAD_INIT_NOLOCK(&ast_channel_audiohooks(chan)->whisper_list);
453                 AST_LIST_HEAD_INIT_NOLOCK(&ast_channel_audiohooks(chan)->manipulate_list);
454                 /* This sample rate will adjust as necessary when writing to the list. */
455                 ast_channel_audiohooks(chan)->list_internal_samp_rate = 8000;
456         }
457
458         /* Drop into respective list */
459         if (audiohook->type == AST_AUDIOHOOK_TYPE_SPY)
460                 AST_LIST_INSERT_TAIL(&ast_channel_audiohooks(chan)->spy_list, audiohook, list);
461         else if (audiohook->type == AST_AUDIOHOOK_TYPE_WHISPER)
462                 AST_LIST_INSERT_TAIL(&ast_channel_audiohooks(chan)->whisper_list, audiohook, list);
463         else if (audiohook->type == AST_AUDIOHOOK_TYPE_MANIPULATE)
464                 AST_LIST_INSERT_TAIL(&ast_channel_audiohooks(chan)->manipulate_list, audiohook, list);
465
466
467         audiohook_set_internal_rate(audiohook, ast_channel_audiohooks(chan)->list_internal_samp_rate, 1);
468         audiohook_list_set_samplerate_compatibility(ast_channel_audiohooks(chan));
469
470         /* Change status over to running since it is now attached */
471         ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_RUNNING);
472
473         ast_channel_unlock(chan);
474
475         return 0;
476 }
477
478 /*! \brief Update audiohook's status
479  * \param audiohook Audiohook structure
480  * \param status Audiohook status enum
481  *
482  * \note once status is updated to DONE, this function can not be used to set the
483  * status back to any other setting.  Setting DONE effectively locks the status as such.
484  */
485
486 void ast_audiohook_update_status(struct ast_audiohook *audiohook, enum ast_audiohook_status status)
487 {
488         ast_audiohook_lock(audiohook);
489         if (audiohook->status != AST_AUDIOHOOK_STATUS_DONE) {
490                 audiohook->status = status;
491                 ast_cond_signal(&audiohook->trigger);
492         }
493         ast_audiohook_unlock(audiohook);
494 }
495
496 /*! \brief Detach audiohook from channel
497  * \param audiohook Audiohook structure
498  * \return Returns 0 on success, -1 on failure
499  */
500 int ast_audiohook_detach(struct ast_audiohook *audiohook)
501 {
502         if (audiohook->status == AST_AUDIOHOOK_STATUS_NEW || audiohook->status == AST_AUDIOHOOK_STATUS_DONE)
503                 return 0;
504
505         ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_SHUTDOWN);
506
507         while (audiohook->status != AST_AUDIOHOOK_STATUS_DONE)
508                 ast_audiohook_trigger_wait(audiohook);
509
510         return 0;
511 }
512
513 /*! \brief Detach audiohooks from list and destroy said list
514  * \param audiohook_list List of audiohooks
515  * \return Returns 0 on success, -1 on failure
516  */
517 int ast_audiohook_detach_list(struct ast_audiohook_list *audiohook_list)
518 {
519         int i = 0;
520         struct ast_audiohook *audiohook = NULL;
521
522         /* Drop any spies */
523         while ((audiohook = AST_LIST_REMOVE_HEAD(&audiohook_list->spy_list, list))) {
524                 ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
525         }
526
527         /* Drop any whispering sources */
528         while ((audiohook = AST_LIST_REMOVE_HEAD(&audiohook_list->whisper_list, list))) {
529                 ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
530         }
531
532         /* Drop any manipulaters */
533         while ((audiohook = AST_LIST_REMOVE_HEAD(&audiohook_list->manipulate_list, list))) {
534                 ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
535                 audiohook->manipulate_callback(audiohook, NULL, NULL, 0);
536         }
537
538         /* Drop translation paths if present */
539         for (i = 0; i < 2; i++) {
540                 if (audiohook_list->in_translate[i].trans_pvt)
541                         ast_translator_free_path(audiohook_list->in_translate[i].trans_pvt);
542                 if (audiohook_list->out_translate[i].trans_pvt)
543                         ast_translator_free_path(audiohook_list->out_translate[i].trans_pvt);
544         }
545
546         /* Free ourselves */
547         ast_free(audiohook_list);
548
549         return 0;
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         if (AST_LIST_EMPTY(&audiohook_list->spy_list) &&
901                 AST_LIST_EMPTY(&audiohook_list->whisper_list) &&
902                 AST_LIST_EMPTY(&audiohook_list->manipulate_list)) {
903
904                 return 1;
905         }
906         return 0;
907 }
908
909 /*! \brief Pass a frame off to be handled by the audiohook core
910  * \param chan Channel that the list is coming off of
911  * \param audiohook_list List of audiohooks
912  * \param direction Direction frame is coming in from
913  * \param frame The frame itself
914  * \return Return frame on success, NULL on failure
915  */
916 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)
917 {
918         /* Pass off frame to it's respective list write function */
919         if (frame->frametype == AST_FRAME_VOICE)
920                 return audio_audiohook_write_list(chan, audiohook_list, direction, frame);
921         else if (frame->frametype == AST_FRAME_DTMF)
922                 return dtmf_audiohook_write_list(chan, audiohook_list, direction, frame);
923         else
924                 return frame;
925 }
926
927 /*! \brief Wait for audiohook trigger to be triggered
928  * \param audiohook Audiohook to wait on
929  */
930 void ast_audiohook_trigger_wait(struct ast_audiohook *audiohook)
931 {
932         struct timeval wait;
933         struct timespec ts;
934
935         wait = ast_tvadd(ast_tvnow(), ast_samp2tv(50000, 1000));
936         ts.tv_sec = wait.tv_sec;
937         ts.tv_nsec = wait.tv_usec * 1000;
938
939         ast_cond_timedwait(&audiohook->trigger, &audiohook->lock, &ts);
940
941         return;
942 }
943
944 /* Count number of channel audiohooks by type, regardless of type */
945 int ast_channel_audiohook_count_by_source(struct ast_channel *chan, const char *source, enum ast_audiohook_type type)
946 {
947         int count = 0;
948         struct ast_audiohook *ah = NULL;
949
950         if (!ast_channel_audiohooks(chan))
951                 return -1;
952
953         switch (type) {
954                 case AST_AUDIOHOOK_TYPE_SPY:
955                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->spy_list, ah, list) {
956                                 if (!strcmp(ah->source, source)) {
957                                         count++;
958                                 }
959                         }
960                         break;
961                 case AST_AUDIOHOOK_TYPE_WHISPER:
962                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->whisper_list, ah, list) {
963                                 if (!strcmp(ah->source, source)) {
964                                         count++;
965                                 }
966                         }
967                         break;
968                 case AST_AUDIOHOOK_TYPE_MANIPULATE:
969                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->manipulate_list, ah, list) {
970                                 if (!strcmp(ah->source, source)) {
971                                         count++;
972                                 }
973                         }
974                         break;
975                 default:
976                         ast_debug(1, "Invalid audiohook type supplied, (%d)\n", type);
977                         return -1;
978         }
979
980         return count;
981 }
982
983 /* Count number of channel audiohooks by type that are running */
984 int ast_channel_audiohook_count_by_source_running(struct ast_channel *chan, const char *source, enum ast_audiohook_type type)
985 {
986         int count = 0;
987         struct ast_audiohook *ah = NULL;
988         if (!ast_channel_audiohooks(chan))
989                 return -1;
990
991         switch (type) {
992                 case AST_AUDIOHOOK_TYPE_SPY:
993                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->spy_list, ah, list) {
994                                 if ((!strcmp(ah->source, source)) && (ah->status == AST_AUDIOHOOK_STATUS_RUNNING))
995                                         count++;
996                         }
997                         break;
998                 case AST_AUDIOHOOK_TYPE_WHISPER:
999                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->whisper_list, ah, list) {
1000                                 if ((!strcmp(ah->source, source)) && (ah->status == AST_AUDIOHOOK_STATUS_RUNNING))
1001                                         count++;
1002                         }
1003                         break;
1004                 case AST_AUDIOHOOK_TYPE_MANIPULATE:
1005                         AST_LIST_TRAVERSE(&ast_channel_audiohooks(chan)->manipulate_list, ah, list) {
1006                                 if ((!strcmp(ah->source, source)) && (ah->status == AST_AUDIOHOOK_STATUS_RUNNING))
1007                                         count++;
1008                         }
1009                         break;
1010                 default:
1011                         ast_debug(1, "Invalid audiohook type supplied, (%d)\n", type);
1012                         return -1;
1013         }
1014         return count;
1015 }
1016
1017 /*! \brief Audiohook volume adjustment structure */
1018 struct audiohook_volume {
1019         struct ast_audiohook audiohook; /*!< Audiohook attached to the channel */
1020         int read_adjustment;            /*!< Value to adjust frames read from the channel by */
1021         int write_adjustment;           /*!< Value to adjust frames written to the channel by */
1022 };
1023
1024 /*! \brief Callback used to destroy the audiohook volume datastore
1025  * \param data Volume information structure
1026  * \return Returns nothing
1027  */
1028 static void audiohook_volume_destroy(void *data)
1029 {
1030         struct audiohook_volume *audiohook_volume = data;
1031
1032         /* Destroy the audiohook as it is no longer in use */
1033         ast_audiohook_destroy(&audiohook_volume->audiohook);
1034
1035         /* Finally free ourselves, we are of no more use */
1036         ast_free(audiohook_volume);
1037
1038         return;
1039 }
1040
1041 /*! \brief Datastore used to store audiohook volume information */
1042 static const struct ast_datastore_info audiohook_volume_datastore = {
1043         .type = "Volume",
1044         .destroy = audiohook_volume_destroy,
1045 };
1046
1047 /*! \brief Helper function which actually gets called by audiohooks to perform the adjustment
1048  * \param audiohook Audiohook attached to the channel
1049  * \param chan Channel we are attached to
1050  * \param frame Frame of audio we want to manipulate
1051  * \param direction Direction the audio came in from
1052  * \return Returns 0 on success, -1 on failure
1053  */
1054 static int audiohook_volume_callback(struct ast_audiohook *audiohook, struct ast_channel *chan, struct ast_frame *frame, enum ast_audiohook_direction direction)
1055 {
1056         struct ast_datastore *datastore = NULL;
1057         struct audiohook_volume *audiohook_volume = NULL;
1058         int *gain = NULL;
1059
1060         /* If the audiohook is shutting down don't even bother */
1061         if (audiohook->status == AST_AUDIOHOOK_STATUS_DONE) {
1062                 return 0;
1063         }
1064
1065         /* Try to find the datastore containg adjustment information, if we can't just bail out */
1066         if (!(datastore = ast_channel_datastore_find(chan, &audiohook_volume_datastore, NULL))) {
1067                 return 0;
1068         }
1069
1070         audiohook_volume = datastore->data;
1071
1072         /* Based on direction grab the appropriate adjustment value */
1073         if (direction == AST_AUDIOHOOK_DIRECTION_READ) {
1074                 gain = &audiohook_volume->read_adjustment;
1075         } else if (direction == AST_AUDIOHOOK_DIRECTION_WRITE) {
1076                 gain = &audiohook_volume->write_adjustment;
1077         }
1078
1079         /* If an adjustment value is present modify the frame */
1080         if (gain && *gain) {
1081                 ast_frame_adjust_volume(frame, *gain);
1082         }
1083
1084         return 0;
1085 }
1086
1087 /*! \brief Helper function which finds and optionally creates an audiohook_volume_datastore datastore on a channel
1088  * \param chan Channel to look on
1089  * \param create Whether to create the datastore if not found
1090  * \return Returns audiohook_volume structure on success, NULL on failure
1091  */
1092 static struct audiohook_volume *audiohook_volume_get(struct ast_channel *chan, int create)
1093 {
1094         struct ast_datastore *datastore = NULL;
1095         struct audiohook_volume *audiohook_volume = NULL;
1096
1097         /* If we are able to find the datastore return the contents (which is actually an audiohook_volume structure) */
1098         if ((datastore = ast_channel_datastore_find(chan, &audiohook_volume_datastore, NULL))) {
1099                 return datastore->data;
1100         }
1101
1102         /* 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 */
1103         if (!create || !(datastore = ast_datastore_alloc(&audiohook_volume_datastore, NULL))) {
1104                 return NULL;
1105         }
1106
1107         /* Create a new audiohook_volume structure to contain our adjustments and audiohook */
1108         if (!(audiohook_volume = ast_calloc(1, sizeof(*audiohook_volume)))) {
1109                 ast_datastore_free(datastore);
1110                 return NULL;
1111         }
1112
1113         /* Setup our audiohook structure so we can manipulate the audio */
1114         ast_audiohook_init(&audiohook_volume->audiohook, AST_AUDIOHOOK_TYPE_MANIPULATE, "Volume", AST_AUDIOHOOK_MANIPULATE_ALL_RATES);
1115         audiohook_volume->audiohook.manipulate_callback = audiohook_volume_callback;
1116
1117         /* Attach the audiohook_volume blob to the datastore and attach to the channel */
1118         datastore->data = audiohook_volume;
1119         ast_channel_datastore_add(chan, datastore);
1120
1121         /* All is well... put the audiohook into motion */
1122         ast_audiohook_attach(chan, &audiohook_volume->audiohook);
1123
1124         return audiohook_volume;
1125 }
1126
1127 /*! \brief Adjust the volume on frames read from or written to a channel
1128  * \param chan Channel to muck with
1129  * \param direction Direction to set on
1130  * \param volume Value to adjust the volume by
1131  * \return Returns 0 on success, -1 on failure
1132  */
1133 int ast_audiohook_volume_set(struct ast_channel *chan, enum ast_audiohook_direction direction, int volume)
1134 {
1135         struct audiohook_volume *audiohook_volume = NULL;
1136
1137         /* Attempt to find the audiohook volume information, but only create it if we are not setting the adjustment value to zero */
1138         if (!(audiohook_volume = audiohook_volume_get(chan, (volume ? 1 : 0)))) {
1139                 return -1;
1140         }
1141
1142         /* Now based on the direction set the proper value */
1143         if (direction == AST_AUDIOHOOK_DIRECTION_READ || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
1144                 audiohook_volume->read_adjustment = volume;
1145         }
1146         if (direction == AST_AUDIOHOOK_DIRECTION_WRITE || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
1147                 audiohook_volume->write_adjustment = volume;
1148         }
1149
1150         return 0;
1151 }
1152
1153 /*! \brief Retrieve the volume adjustment value on frames read from or written to a channel
1154  * \param chan Channel to retrieve volume adjustment from
1155  * \param direction Direction to retrieve
1156  * \return Returns adjustment value
1157  */
1158 int ast_audiohook_volume_get(struct ast_channel *chan, enum ast_audiohook_direction direction)
1159 {
1160         struct audiohook_volume *audiohook_volume = NULL;
1161         int adjustment = 0;
1162
1163         /* Attempt to find the audiohook volume information, but do not create it as we only want to look at the values */
1164         if (!(audiohook_volume = audiohook_volume_get(chan, 0))) {
1165                 return 0;
1166         }
1167
1168         /* Grab the adjustment value based on direction given */
1169         if (direction == AST_AUDIOHOOK_DIRECTION_READ) {
1170                 adjustment = audiohook_volume->read_adjustment;
1171         } else if (direction == AST_AUDIOHOOK_DIRECTION_WRITE) {
1172                 adjustment = audiohook_volume->write_adjustment;
1173         }
1174
1175         return adjustment;
1176 }
1177
1178 /*! \brief Adjust the volume on frames read from or written to a channel
1179  * \param chan Channel to muck with
1180  * \param direction Direction to increase
1181  * \param volume Value to adjust the adjustment by
1182  * \return Returns 0 on success, -1 on failure
1183  */
1184 int ast_audiohook_volume_adjust(struct ast_channel *chan, enum ast_audiohook_direction direction, int volume)
1185 {
1186         struct audiohook_volume *audiohook_volume = NULL;
1187
1188         /* Attempt to find the audiohook volume information, and create an audiohook if none exists */
1189         if (!(audiohook_volume = audiohook_volume_get(chan, 1))) {
1190                 return -1;
1191         }
1192
1193         /* Based on the direction change the specific adjustment value */
1194         if (direction == AST_AUDIOHOOK_DIRECTION_READ || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
1195                 audiohook_volume->read_adjustment += volume;
1196         }
1197         if (direction == AST_AUDIOHOOK_DIRECTION_WRITE || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
1198                 audiohook_volume->write_adjustment += volume;
1199         }
1200
1201         return 0;
1202 }
1203
1204 /*! \brief Mute frames read from or written to a channel
1205  * \param chan Channel to muck with
1206  * \param source Type of audiohook
1207  * \param flag which flag to set / clear
1208  * \param clear set or clear
1209  * \return Returns 0 on success, -1 on failure
1210  */
1211 int ast_audiohook_set_mute(struct ast_channel *chan, const char *source, enum ast_audiohook_flags flag, int clear)
1212 {
1213         struct ast_audiohook *audiohook = NULL;
1214
1215         ast_channel_lock(chan);
1216
1217         /* Ensure the channel has audiohooks on it */
1218         if (!ast_channel_audiohooks(chan)) {
1219                 ast_channel_unlock(chan);
1220                 return -1;
1221         }
1222
1223         audiohook = find_audiohook_by_source(ast_channel_audiohooks(chan), source);
1224
1225         if (audiohook) {
1226                 if (clear) {
1227                         ast_clear_flag(audiohook, flag);
1228                 } else {
1229                         ast_set_flag(audiohook, flag);
1230                 }
1231         }
1232
1233         ast_channel_unlock(chan);
1234
1235         return (audiohook ? 0 : -1);
1236 }