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