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