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