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