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