Expand codec bitfield from 32 bits to 64 bits.
[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 struct ast_audiohook_translate {
42         struct ast_trans_pvt *trans_pvt;
43         format_t format;
44 };
45
46 struct ast_audiohook_list {
47         struct ast_audiohook_translate in_translate[2];
48         struct ast_audiohook_translate out_translate[2];
49         AST_LIST_HEAD_NOLOCK(, ast_audiohook) spy_list;
50         AST_LIST_HEAD_NOLOCK(, ast_audiohook) whisper_list;
51         AST_LIST_HEAD_NOLOCK(, ast_audiohook) manipulate_list;
52 };
53
54 /*! \brief Initialize an audiohook structure
55  * \param audiohook Audiohook structure
56  * \param type
57  * \param source
58  * \return Returns 0 on success, -1 on failure
59  */
60 int ast_audiohook_init(struct ast_audiohook *audiohook, enum ast_audiohook_type type, const char *source)
61 {
62         /* Need to keep the type and source */
63         audiohook->type = type;
64         audiohook->source = source;
65
66         /* Initialize lock that protects our audiohook */
67         ast_mutex_init(&audiohook->lock);
68         ast_cond_init(&audiohook->trigger, NULL);
69
70         /* Setup the factories that are needed for this audiohook type */
71         switch (type) {
72         case AST_AUDIOHOOK_TYPE_SPY:
73                 ast_slinfactory_init(&audiohook->read_factory);
74         case AST_AUDIOHOOK_TYPE_WHISPER:
75                 ast_slinfactory_init(&audiohook->write_factory);
76                 break;
77         default:
78                 break;
79         }
80
81         /* Since we are just starting out... this audiohook is new */
82         audiohook->status = AST_AUDIOHOOK_STATUS_NEW;
83
84         return 0;
85 }
86
87 /*! \brief Destroys an audiohook structure
88  * \param audiohook Audiohook structure
89  * \return Returns 0 on success, -1 on failure
90  */
91 int ast_audiohook_destroy(struct ast_audiohook *audiohook)
92 {
93         /* Drop the factories used by this audiohook type */
94         switch (audiohook->type) {
95         case AST_AUDIOHOOK_TYPE_SPY:
96                 ast_slinfactory_destroy(&audiohook->read_factory);
97         case AST_AUDIOHOOK_TYPE_WHISPER:
98                 ast_slinfactory_destroy(&audiohook->write_factory);
99                 break;
100         default:
101                 break;
102         }
103
104         /* Destroy translation path if present */
105         if (audiohook->trans_pvt)
106                 ast_translator_free_path(audiohook->trans_pvt);
107
108         /* Lock and trigger be gone! */
109         ast_cond_destroy(&audiohook->trigger);
110         ast_mutex_destroy(&audiohook->lock);
111
112         return 0;
113 }
114
115 /*! \brief Writes a frame into the audiohook structure
116  * \param audiohook Audiohook structure
117  * \param direction Direction the audio frame came from
118  * \param frame Frame to write in
119  * \return Returns 0 on success, -1 on failure
120  */
121 int ast_audiohook_write_frame(struct ast_audiohook *audiohook, enum ast_audiohook_direction direction, struct ast_frame *frame)
122 {
123         struct ast_slinfactory *factory = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook->read_factory : &audiohook->write_factory);
124         struct ast_slinfactory *other_factory = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook->write_factory : &audiohook->read_factory);
125         struct timeval *rwtime = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook->read_time : &audiohook->write_time), previous_time = *rwtime;
126         int our_factory_samples;
127         int our_factory_ms;
128         int other_factory_samples;
129         int other_factory_ms;
130
131         /* Update last feeding time to be current */
132         *rwtime = ast_tvnow();
133
134         our_factory_samples = ast_slinfactory_available(factory);
135         our_factory_ms = ast_tvdiff_ms(*rwtime, previous_time) + (our_factory_samples / 8);
136         other_factory_samples = ast_slinfactory_available(other_factory);
137         other_factory_ms = other_factory_samples / 8;
138
139         if (ast_test_flag(audiohook, AST_AUDIOHOOK_TRIGGER_SYNC) && other_factory_samples && (our_factory_ms - other_factory_ms > AST_AUDIOHOOK_SYNC_TOLERANCE)) {
140                 if (option_debug)
141                         ast_log(LOG_DEBUG, "Flushing audiohook %p so it remains in sync\n", audiohook);
142                 ast_slinfactory_flush(factory);
143                 ast_slinfactory_flush(other_factory);
144         }
145
146         if (ast_test_flag(audiohook, AST_AUDIOHOOK_SMALL_QUEUE) && (our_factory_samples > 640 || other_factory_samples > 640)) {
147                 if (option_debug) {
148                         ast_log(LOG_DEBUG, "Audiohook %p has stale audio in its factories. Flushing them both\n", audiohook);
149                 }
150                 ast_slinfactory_flush(factory);
151                 ast_slinfactory_flush(other_factory);
152         }
153
154         /* Write frame out to respective factory */
155         ast_slinfactory_feed(factory, frame);
156
157         /* If we need to notify the respective handler of this audiohook, do so */
158         if ((ast_test_flag(audiohook, AST_AUDIOHOOK_TRIGGER_MODE) == AST_AUDIOHOOK_TRIGGER_READ) && (direction == AST_AUDIOHOOK_DIRECTION_READ)) {
159                 ast_cond_signal(&audiohook->trigger);
160         } else if ((ast_test_flag(audiohook, AST_AUDIOHOOK_TRIGGER_MODE) == AST_AUDIOHOOK_TRIGGER_WRITE) && (direction == AST_AUDIOHOOK_DIRECTION_WRITE)) {
161                 ast_cond_signal(&audiohook->trigger);
162         } else if (ast_test_flag(audiohook, AST_AUDIOHOOK_TRIGGER_SYNC)) {
163                 ast_cond_signal(&audiohook->trigger);
164         }
165
166         return 0;
167 }
168
169 static struct ast_frame *audiohook_read_frame_single(struct ast_audiohook *audiohook, size_t samples, enum ast_audiohook_direction direction)
170 {
171         struct ast_slinfactory *factory = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook->read_factory : &audiohook->write_factory);
172         int vol = (direction == AST_AUDIOHOOK_DIRECTION_READ ? audiohook->options.read_volume : audiohook->options.write_volume);
173         short buf[samples];
174         struct ast_frame frame = {
175                 .frametype = AST_FRAME_VOICE,
176                 .subclass.codec = AST_FORMAT_SLINEAR,
177                 .data.ptr = buf,
178                 .datalen = sizeof(buf),
179                 .samples = samples,
180         };
181
182         /* Ensure the factory is able to give us the samples we want */
183         if (samples > ast_slinfactory_available(factory))
184                 return NULL;
185         
186         /* Read data in from factory */
187         if (!ast_slinfactory_read(factory, buf, samples))
188                 return NULL;
189
190         /* If a volume adjustment needs to be applied apply it */
191         if (vol)
192                 ast_frame_adjust_volume(&frame, vol);
193
194         return ast_frdup(&frame);
195 }
196
197 static struct ast_frame *audiohook_read_frame_both(struct ast_audiohook *audiohook, size_t samples)
198 {
199         int i = 0, usable_read, usable_write;
200         short buf1[samples], buf2[samples], *read_buf = NULL, *write_buf = NULL, *final_buf = NULL, *data1 = NULL, *data2 = NULL;
201         struct ast_frame frame = {
202                 .frametype = AST_FRAME_VOICE,
203                 .subclass.codec = AST_FORMAT_SLINEAR,
204                 .data.ptr = NULL,
205                 .datalen = sizeof(buf1),
206                 .samples = samples,
207         };
208
209         /* Make sure both factories have the required samples */
210         usable_read = (ast_slinfactory_available(&audiohook->read_factory) >= samples ? 1 : 0);
211         usable_write = (ast_slinfactory_available(&audiohook->write_factory) >= samples ? 1 : 0);
212
213         if (!usable_read && !usable_write) {
214                 /* If both factories are unusable bail out */
215                 ast_debug(1, "Read factory %p and write factory %p both fail to provide %zd samples\n", &audiohook->read_factory, &audiohook->write_factory, samples);
216                 return NULL;
217         }
218
219         /* If we want to provide only a read factory make sure we aren't waiting for other audio */
220         if (usable_read && !usable_write && (ast_tvdiff_ms(ast_tvnow(), audiohook->write_time) < (samples/8)*2)) {
221                 ast_debug(3, "Write factory %p was pretty quick last time, waiting for them.\n", &audiohook->write_factory);
222                 return NULL;
223         }
224
225         /* If we want to provide only a write factory make sure we aren't waiting for other audio */
226         if (usable_write && !usable_read && (ast_tvdiff_ms(ast_tvnow(), audiohook->read_time) < (samples/8)*2)) {
227                 ast_debug(3, "Read factory %p was pretty quick last time, waiting for them.\n", &audiohook->read_factory);
228                 return NULL;
229         }
230
231         /* Start with the read factory... if there are enough samples, read them in */
232         if (usable_read) {
233                 if (ast_slinfactory_read(&audiohook->read_factory, buf1, samples)) {
234                         read_buf = buf1;
235                         /* Adjust read volume if need be */
236                         if (audiohook->options.read_volume) {
237                                 int count = 0;
238                                 short adjust_value = abs(audiohook->options.read_volume);
239                                 for (count = 0; count < samples; count++) {
240                                         if (audiohook->options.read_volume > 0)
241                                                 ast_slinear_saturated_multiply(&buf1[count], &adjust_value);
242                                         else if (audiohook->options.read_volume < 0)
243                                                 ast_slinear_saturated_divide(&buf1[count], &adjust_value);
244                                 }
245                         }
246                 }
247         } else if (option_debug)
248                 ast_log(LOG_DEBUG, "Failed to get %d samples from read factory %p\n", (int)samples, &audiohook->read_factory);
249
250         /* Move on to the write factory... if there are enough samples, read them in */
251         if (usable_write) {
252                 if (ast_slinfactory_read(&audiohook->write_factory, buf2, samples)) {
253                         write_buf = buf2;
254                         /* Adjust write volume if need be */
255                         if (audiohook->options.write_volume) {
256                                 int count = 0;
257                                 short adjust_value = abs(audiohook->options.write_volume);
258                                 for (count = 0; count < samples; count++) {
259                                         if (audiohook->options.write_volume > 0)
260                                                 ast_slinear_saturated_multiply(&buf2[count], &adjust_value);
261                                         else if (audiohook->options.write_volume < 0)
262                                                 ast_slinear_saturated_divide(&buf2[count], &adjust_value);
263                                 }
264                         }
265                 }
266         } else if (option_debug)
267                 ast_log(LOG_DEBUG, "Failed to get %d samples from write factory %p\n", (int)samples, &audiohook->write_factory);
268
269         /* Basically we figure out which buffer to use... and if mixing can be done here */
270         if (!read_buf && !write_buf)
271                 return NULL;
272         else if (read_buf && write_buf) {
273                 for (i = 0, data1 = read_buf, data2 = write_buf; i < samples; i++, data1++, data2++)
274                         ast_slinear_saturated_add(data1, data2);
275                 final_buf = buf1;
276         } else if (read_buf)
277                 final_buf = buf1;
278         else if (write_buf)
279                 final_buf = buf2;
280
281         /* Make the final buffer part of the frame, so it gets duplicated fine */
282         frame.data.ptr = final_buf;
283
284         /* Yahoo, a combined copy of the audio! */
285         return ast_frdup(&frame);
286 }
287
288 /*! \brief Reads a frame in from the audiohook structure
289  * \param audiohook Audiohook structure
290  * \param samples Number of samples wanted
291  * \param direction Direction the audio frame came from
292  * \param format Format of frame remote side wants back
293  * \return Returns frame on success, NULL on failure
294  */
295 struct ast_frame *ast_audiohook_read_frame(struct ast_audiohook *audiohook, size_t samples, enum ast_audiohook_direction direction, format_t format)
296 {
297         struct ast_frame *read_frame = NULL, *final_frame = NULL;
298
299         if (!(read_frame = (direction == AST_AUDIOHOOK_DIRECTION_BOTH ? audiohook_read_frame_both(audiohook, samples) : audiohook_read_frame_single(audiohook, samples, direction))))
300                 return NULL;
301
302         /* If they don't want signed linear back out, we'll have to send it through the translation path */
303         if (format != AST_FORMAT_SLINEAR) {
304                 /* Rebuild translation path if different format then previously */
305                 if (audiohook->format != format) {
306                         if (audiohook->trans_pvt) {
307                                 ast_translator_free_path(audiohook->trans_pvt);
308                                 audiohook->trans_pvt = NULL;
309                         }
310                         /* 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 */
311                         if (!(audiohook->trans_pvt = ast_translator_build_path(format, AST_FORMAT_SLINEAR))) {
312                                 ast_frfree(read_frame);
313                                 return NULL;
314                         }
315                 }
316                 /* Convert to requested format, and allow the read in frame to be freed */
317                 final_frame = ast_translate(audiohook->trans_pvt, read_frame, 1);
318         } else {
319                 final_frame = read_frame;
320         }
321
322         return final_frame;
323 }
324
325 /*! \brief Attach audiohook to channel
326  * \param chan Channel
327  * \param audiohook Audiohook structure
328  * \return Returns 0 on success, -1 on failure
329  */
330 int ast_audiohook_attach(struct ast_channel *chan, struct ast_audiohook *audiohook)
331 {
332         ast_channel_lock(chan);
333
334         if (!chan->audiohooks) {
335                 /* Whoops... allocate a new structure */
336                 if (!(chan->audiohooks = ast_calloc(1, sizeof(*chan->audiohooks)))) {
337                         ast_channel_unlock(chan);
338                         return -1;
339                 }
340                 AST_LIST_HEAD_INIT_NOLOCK(&chan->audiohooks->spy_list);
341                 AST_LIST_HEAD_INIT_NOLOCK(&chan->audiohooks->whisper_list);
342                 AST_LIST_HEAD_INIT_NOLOCK(&chan->audiohooks->manipulate_list);
343         }
344
345         /* Drop into respective list */
346         if (audiohook->type == AST_AUDIOHOOK_TYPE_SPY)
347                 AST_LIST_INSERT_TAIL(&chan->audiohooks->spy_list, audiohook, list);
348         else if (audiohook->type == AST_AUDIOHOOK_TYPE_WHISPER)
349                 AST_LIST_INSERT_TAIL(&chan->audiohooks->whisper_list, audiohook, list);
350         else if (audiohook->type == AST_AUDIOHOOK_TYPE_MANIPULATE)
351                 AST_LIST_INSERT_TAIL(&chan->audiohooks->manipulate_list, audiohook, list);
352
353         /* Change status over to running since it is now attached */
354         audiohook->status = AST_AUDIOHOOK_STATUS_RUNNING;
355
356         ast_channel_unlock(chan);
357
358         return 0;
359 }
360
361 /*! \brief Detach audiohook from channel
362  * \param audiohook Audiohook structure
363  * \return Returns 0 on success, -1 on failure
364  */
365 int ast_audiohook_detach(struct ast_audiohook *audiohook)
366 {
367         if (audiohook->status == AST_AUDIOHOOK_STATUS_NEW || audiohook->status == AST_AUDIOHOOK_STATUS_DONE)
368                 return 0;
369
370         audiohook->status = AST_AUDIOHOOK_STATUS_SHUTDOWN;
371
372         while (audiohook->status != AST_AUDIOHOOK_STATUS_DONE)
373                 ast_audiohook_trigger_wait(audiohook);
374
375         return 0;
376 }
377
378 /*! \brief Detach audiohooks from list and destroy said list
379  * \param audiohook_list List of audiohooks
380  * \return Returns 0 on success, -1 on failure
381  */
382 int ast_audiohook_detach_list(struct ast_audiohook_list *audiohook_list)
383 {
384         int i = 0;
385         struct ast_audiohook *audiohook = NULL;
386
387         /* Drop any spies */
388         while ((audiohook = AST_LIST_REMOVE_HEAD(&audiohook_list->spy_list, list))) {
389                 ast_audiohook_lock(audiohook);
390                 audiohook->status = AST_AUDIOHOOK_STATUS_DONE;
391                 ast_cond_signal(&audiohook->trigger);
392                 ast_audiohook_unlock(audiohook);
393         }
394
395         /* Drop any whispering sources */
396         while ((audiohook = AST_LIST_REMOVE_HEAD(&audiohook_list->whisper_list, list))) {
397                 ast_audiohook_lock(audiohook);
398                 audiohook->status = AST_AUDIOHOOK_STATUS_DONE;
399                 ast_cond_signal(&audiohook->trigger);
400                 ast_audiohook_unlock(audiohook);
401         }
402
403         /* Drop any manipulaters */
404         while ((audiohook = AST_LIST_REMOVE_HEAD(&audiohook_list->manipulate_list, list))) {
405                 ast_audiohook_lock(audiohook);
406                 audiohook->status = AST_AUDIOHOOK_STATUS_DONE;
407                 ast_audiohook_unlock(audiohook);
408                 audiohook->manipulate_callback(audiohook, NULL, NULL, 0);
409         }
410
411         /* Drop translation paths if present */
412         for (i = 0; i < 2; i++) {
413                 if (audiohook_list->in_translate[i].trans_pvt)
414                         ast_translator_free_path(audiohook_list->in_translate[i].trans_pvt);
415                 if (audiohook_list->out_translate[i].trans_pvt)
416                         ast_translator_free_path(audiohook_list->out_translate[i].trans_pvt);
417         }
418         
419         /* Free ourselves */
420         ast_free(audiohook_list);
421
422         return 0;
423 }
424
425 /*! \brief find an audiohook based on its source
426  * \param audiohook_list The list of audiohooks to search in
427  * \param source The source of the audiohook we wish to find
428  * \return Return the corresponding audiohook or NULL if it cannot be found.
429  */
430 static struct ast_audiohook *find_audiohook_by_source(struct ast_audiohook_list *audiohook_list, const char *source)
431 {
432         struct ast_audiohook *audiohook = NULL;
433
434         AST_LIST_TRAVERSE(&audiohook_list->spy_list, audiohook, list) {
435                 if (!strcasecmp(audiohook->source, source))
436                         return audiohook;
437         }
438
439         AST_LIST_TRAVERSE(&audiohook_list->whisper_list, audiohook, list) {
440                 if (!strcasecmp(audiohook->source, source))
441                         return audiohook;
442         }
443
444         AST_LIST_TRAVERSE(&audiohook_list->manipulate_list, audiohook, list) {
445                 if (!strcasecmp(audiohook->source, source))
446                         return audiohook;
447         }
448
449         return NULL;
450 }
451
452 void ast_audiohook_move_by_source(struct ast_channel *old_chan, struct ast_channel *new_chan, const char *source)
453 {
454         struct ast_audiohook *audiohook;
455
456         if (!old_chan->audiohooks || !(audiohook = find_audiohook_by_source(old_chan->audiohooks, source))) {
457                 return;
458         }
459
460         /* By locking both channels and the audiohook, we can assure that
461          * another thread will not have a chance to read the audiohook's status
462          * as done, even though ast_audiohook_remove signals the trigger
463          * condition
464          */
465         ast_audiohook_lock(audiohook);
466         ast_audiohook_remove(old_chan, audiohook);
467         ast_audiohook_attach(new_chan, audiohook);
468         ast_audiohook_unlock(audiohook);
469 }
470
471 /*! \brief Detach specified source audiohook from channel
472  * \param chan Channel to detach from
473  * \param source Name of source to detach
474  * \return Returns 0 on success, -1 on failure
475  */
476 int ast_audiohook_detach_source(struct ast_channel *chan, const char *source)
477 {
478         struct ast_audiohook *audiohook = NULL;
479
480         ast_channel_lock(chan);
481
482         /* Ensure the channel has audiohooks on it */
483         if (!chan->audiohooks) {
484                 ast_channel_unlock(chan);
485                 return -1;
486         }
487
488         audiohook = find_audiohook_by_source(chan->audiohooks, source);
489
490         ast_channel_unlock(chan);
491
492         if (audiohook && audiohook->status != AST_AUDIOHOOK_STATUS_DONE)
493                 audiohook->status = AST_AUDIOHOOK_STATUS_SHUTDOWN;
494
495         return (audiohook ? 0 : -1);
496 }
497
498 /*!
499  * \brief Remove an audiohook from a specified channel
500  *
501  * \param chan Channel to remove from
502  * \param audiohook Audiohook to remove
503  *
504  * \return Returns 0 on success, -1 on failure
505  *
506  * \note The channel does not need to be locked before calling this function
507  */
508 int ast_audiohook_remove(struct ast_channel *chan, struct ast_audiohook *audiohook)
509 {
510         ast_channel_lock(chan);
511
512         if (!chan->audiohooks) {
513                 ast_channel_unlock(chan);
514                 return -1;
515         }
516
517         if (audiohook->type == AST_AUDIOHOOK_TYPE_SPY)
518                 AST_LIST_REMOVE(&chan->audiohooks->spy_list, audiohook, list);
519         else if (audiohook->type == AST_AUDIOHOOK_TYPE_WHISPER)
520                 AST_LIST_REMOVE(&chan->audiohooks->whisper_list, audiohook, list);
521         else if (audiohook->type == AST_AUDIOHOOK_TYPE_MANIPULATE)
522                 AST_LIST_REMOVE(&chan->audiohooks->manipulate_list, audiohook, list);
523
524         ast_audiohook_lock(audiohook);
525         audiohook->status = AST_AUDIOHOOK_STATUS_DONE;
526         ast_cond_signal(&audiohook->trigger);
527         ast_audiohook_unlock(audiohook);
528
529         ast_channel_unlock(chan);
530
531         return 0;
532 }
533
534 /*! \brief Pass a DTMF frame off to be handled by the audiohook core
535  * \param chan Channel that the list is coming off of
536  * \param audiohook_list List of audiohooks
537  * \param direction Direction frame is coming in from
538  * \param frame The frame itself
539  * \return Return frame on success, NULL on failure
540  */
541 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)
542 {
543         struct ast_audiohook *audiohook = NULL;
544
545         AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->manipulate_list, audiohook, list) {
546                 ast_audiohook_lock(audiohook);
547                 if (audiohook->status != AST_AUDIOHOOK_STATUS_RUNNING) {
548                         AST_LIST_REMOVE_CURRENT(list);
549                         audiohook->status = AST_AUDIOHOOK_STATUS_DONE;
550                         ast_audiohook_unlock(audiohook);
551                         audiohook->manipulate_callback(audiohook, NULL, NULL, 0);
552                         continue;
553                 }
554                 if (ast_test_flag(audiohook, AST_AUDIOHOOK_WANTS_DTMF))
555                         audiohook->manipulate_callback(audiohook, chan, frame, direction);
556                 ast_audiohook_unlock(audiohook);
557         }
558         AST_LIST_TRAVERSE_SAFE_END;
559
560         return frame;
561 }
562
563 /*! \brief Pass an AUDIO frame off to be handled by the audiohook core
564  * \param chan Channel that the list is coming off of
565  * \param audiohook_list List of audiohooks
566  * \param direction Direction frame is coming in from
567  * \param frame The frame itself
568  * \return Return frame on success, NULL on failure
569  */
570 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)
571 {
572         struct ast_audiohook_translate *in_translate = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook_list->in_translate[0] : &audiohook_list->in_translate[1]);
573         struct ast_audiohook_translate *out_translate = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook_list->out_translate[0] : &audiohook_list->out_translate[1]);
574         struct ast_frame *start_frame = frame, *middle_frame = frame, *end_frame = frame;
575         struct ast_audiohook *audiohook = NULL;
576         int samples = frame->samples;
577
578         /* If the frame coming in is not signed linear we have to send it through the in_translate path */
579         if (frame->subclass.codec != AST_FORMAT_SLINEAR) {
580                 if (in_translate->format != frame->subclass.codec) {
581                         if (in_translate->trans_pvt)
582                                 ast_translator_free_path(in_translate->trans_pvt);
583                         if (!(in_translate->trans_pvt = ast_translator_build_path(AST_FORMAT_SLINEAR, frame->subclass.codec)))
584                                 return frame;
585                         in_translate->format = frame->subclass.codec;
586                 }
587                 if (!(middle_frame = ast_translate(in_translate->trans_pvt, frame, 0)))
588                         return frame;
589                 samples = middle_frame->samples;
590         }
591
592         /* Queue up signed linear frame to each spy */
593         AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->spy_list, audiohook, list) {
594                 ast_audiohook_lock(audiohook);
595                 if (audiohook->status != AST_AUDIOHOOK_STATUS_RUNNING) {
596                         AST_LIST_REMOVE_CURRENT(list);
597                         audiohook->status = AST_AUDIOHOOK_STATUS_DONE;
598                         ast_cond_signal(&audiohook->trigger);
599                         ast_audiohook_unlock(audiohook);
600                         continue;
601                 }
602                 ast_audiohook_write_frame(audiohook, direction, middle_frame);
603                 ast_audiohook_unlock(audiohook);
604         }
605         AST_LIST_TRAVERSE_SAFE_END;
606
607         /* If this frame is being written out to the channel then we need to use whisper sources */
608         if (direction == AST_AUDIOHOOK_DIRECTION_WRITE && !AST_LIST_EMPTY(&audiohook_list->whisper_list)) {
609                 int i = 0;
610                 short read_buf[samples], combine_buf[samples], *data1 = NULL, *data2 = NULL;
611                 memset(&combine_buf, 0, sizeof(combine_buf));
612                 AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->whisper_list, audiohook, list) {
613                         ast_audiohook_lock(audiohook);
614                         if (audiohook->status != AST_AUDIOHOOK_STATUS_RUNNING) {
615                                 AST_LIST_REMOVE_CURRENT(list);
616                                 audiohook->status = AST_AUDIOHOOK_STATUS_DONE;
617                                 ast_cond_signal(&audiohook->trigger);
618                                 ast_audiohook_unlock(audiohook);
619                                 continue;
620                         }
621                         if (ast_slinfactory_available(&audiohook->write_factory) >= samples && ast_slinfactory_read(&audiohook->write_factory, read_buf, samples)) {
622                                 /* Take audio from this whisper source and combine it into our main buffer */
623                                 for (i = 0, data1 = combine_buf, data2 = read_buf; i < samples; i++, data1++, data2++)
624                                         ast_slinear_saturated_add(data1, data2);
625                         }
626                         ast_audiohook_unlock(audiohook);
627                 }
628                 AST_LIST_TRAVERSE_SAFE_END;
629                 /* We take all of the combined whisper sources and combine them into the audio being written out */
630                 for (i = 0, data1 = middle_frame->data.ptr, data2 = combine_buf; i < samples; i++, data1++, data2++)
631                         ast_slinear_saturated_add(data1, data2);
632                 end_frame = middle_frame;
633         }
634
635         /* Pass off frame to manipulate audiohooks */
636         if (!AST_LIST_EMPTY(&audiohook_list->manipulate_list)) {
637                 AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->manipulate_list, audiohook, list) {
638                         ast_audiohook_lock(audiohook);
639                         if (audiohook->status != AST_AUDIOHOOK_STATUS_RUNNING) {
640                                 AST_LIST_REMOVE_CURRENT(list);
641                                 audiohook->status = AST_AUDIOHOOK_STATUS_DONE;
642                                 ast_audiohook_unlock(audiohook);
643                                 /* We basically drop all of our links to the manipulate audiohook and prod it to do it's own destructive things */
644                                 audiohook->manipulate_callback(audiohook, chan, NULL, direction);
645                                 continue;
646                         }
647                         /* Feed in frame to manipulation */
648                         if (audiohook->manipulate_callback(audiohook, chan, middle_frame, direction)) {
649                                 ast_frfree(middle_frame);
650                                 middle_frame = NULL;
651                         }
652                         ast_audiohook_unlock(audiohook);
653                 }
654                 AST_LIST_TRAVERSE_SAFE_END;
655                 if (middle_frame) {
656                         end_frame = middle_frame;
657                 }
658         }
659
660         /* Now we figure out what to do with our end frame (whether to transcode or not) */
661         if (middle_frame == end_frame) {
662                 /* Middle frame was modified and became the end frame... let's see if we need to transcode */
663                 if (end_frame->subclass.codec != start_frame->subclass.codec) {
664                         if (out_translate->format != start_frame->subclass.codec) {
665                                 if (out_translate->trans_pvt)
666                                         ast_translator_free_path(out_translate->trans_pvt);
667                                 if (!(out_translate->trans_pvt = ast_translator_build_path(start_frame->subclass.codec, AST_FORMAT_SLINEAR))) {
668                                         /* We can't transcode this... drop our middle frame and return the original */
669                                         ast_frfree(middle_frame);
670                                         return start_frame;
671                                 }
672                                 out_translate->format = start_frame->subclass.codec;
673                         }
674                         /* Transcode from our middle (signed linear) frame to new format of the frame that came in */
675                         if (!(end_frame = ast_translate(out_translate->trans_pvt, middle_frame, 0))) {
676                                 /* Failed to transcode the frame... drop it and return the original */
677                                 ast_frfree(middle_frame);
678                                 return start_frame;
679                         }
680                         /* Here's the scoop... middle frame is no longer of use to us */
681                         ast_frfree(middle_frame);
682                 }
683         } else {
684                 /* No frame was modified, we can just drop our middle frame and pass the frame we got in out */
685                 if (middle_frame) {
686                         ast_frfree(middle_frame);
687                 }
688         }
689
690         return end_frame;
691 }
692
693 /*! \brief Pass a frame off to be handled by the audiohook core
694  * \param chan Channel that the list is coming off of
695  * \param audiohook_list List of audiohooks
696  * \param direction Direction frame is coming in from
697  * \param frame The frame itself
698  * \return Return frame on success, NULL on failure
699  */
700 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)
701 {
702         /* Pass off frame to it's respective list write function */
703         if (frame->frametype == AST_FRAME_VOICE)
704                 return audio_audiohook_write_list(chan, audiohook_list, direction, frame);
705         else if (frame->frametype == AST_FRAME_DTMF)
706                 return dtmf_audiohook_write_list(chan, audiohook_list, direction, frame);
707         else
708                 return frame;
709 }
710                         
711
712 /*! \brief Wait for audiohook trigger to be triggered
713  * \param audiohook Audiohook to wait on
714  */
715 void ast_audiohook_trigger_wait(struct ast_audiohook *audiohook)
716 {
717         struct timeval wait;
718         struct timespec ts;
719
720         wait = ast_tvadd(ast_tvnow(), ast_samp2tv(50000, 1000));
721         ts.tv_sec = wait.tv_sec;
722         ts.tv_nsec = wait.tv_usec * 1000;
723         
724         ast_cond_timedwait(&audiohook->trigger, &audiohook->lock, &ts);
725         
726         return;
727 }
728
729 /* Count number of channel audiohooks by type, regardless of type */
730 int ast_channel_audiohook_count_by_source(struct ast_channel *chan, const char *source, enum ast_audiohook_type type)
731 {
732         int count = 0;
733         struct ast_audiohook *ah = NULL;
734
735         if (!chan->audiohooks)
736                 return -1;
737
738         switch (type) {
739                 case AST_AUDIOHOOK_TYPE_SPY:
740                         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->audiohooks->spy_list, ah, list) {
741                                 if (!strcmp(ah->source, source)) {
742                                         count++;
743                                 }
744                         }
745                         AST_LIST_TRAVERSE_SAFE_END;
746                         break;
747                 case AST_AUDIOHOOK_TYPE_WHISPER:
748                         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->audiohooks->whisper_list, ah, list) {
749                                 if (!strcmp(ah->source, source)) {
750                                         count++;
751                                 }
752                         }
753                         AST_LIST_TRAVERSE_SAFE_END;
754                         break;
755                 case AST_AUDIOHOOK_TYPE_MANIPULATE:
756                         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->audiohooks->manipulate_list, ah, list) {
757                                 if (!strcmp(ah->source, source)) {
758                                         count++;
759                                 }
760                         }
761                         AST_LIST_TRAVERSE_SAFE_END;
762                         break;
763                 default:
764                         ast_log(LOG_DEBUG, "Invalid audiohook type supplied, (%d)\n", type);
765                         return -1;
766         }
767
768         return count;
769 }
770
771 /* Count number of channel audiohooks by type that are running */
772 int ast_channel_audiohook_count_by_source_running(struct ast_channel *chan, const char *source, enum ast_audiohook_type type)
773 {
774         int count = 0;
775         struct ast_audiohook *ah = NULL;
776         if (!chan->audiohooks)
777                 return -1;
778
779         switch (type) {
780                 case AST_AUDIOHOOK_TYPE_SPY:
781                         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->audiohooks->spy_list, ah, list) {
782                                 if ((!strcmp(ah->source, source)) && (ah->status == AST_AUDIOHOOK_STATUS_RUNNING))
783                                         count++;
784                         }
785                         AST_LIST_TRAVERSE_SAFE_END;
786                         break;
787                 case AST_AUDIOHOOK_TYPE_WHISPER:
788                         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->audiohooks->whisper_list, ah, list) {
789                                 if ((!strcmp(ah->source, source)) && (ah->status == AST_AUDIOHOOK_STATUS_RUNNING))
790                                         count++;
791                         }
792                         AST_LIST_TRAVERSE_SAFE_END;
793                         break;
794                 case AST_AUDIOHOOK_TYPE_MANIPULATE:
795                         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->audiohooks->manipulate_list, ah, list) {
796                                 if ((!strcmp(ah->source, source)) && (ah->status == AST_AUDIOHOOK_STATUS_RUNNING))
797                                         count++;
798                         }
799                         AST_LIST_TRAVERSE_SAFE_END;
800                         break;
801                 default:
802                         ast_log(LOG_DEBUG, "Invalid audiohook type supplied, (%d)\n", type);
803                         return -1;
804         }
805         return count;
806 }
807
808 /*! \brief Audiohook volume adjustment structure */
809 struct audiohook_volume {
810         struct ast_audiohook audiohook; /*!< Audiohook attached to the channel */
811         int read_adjustment;            /*!< Value to adjust frames read from the channel by */
812         int write_adjustment;           /*!< Value to adjust frames written to the channel by */
813 };
814
815 /*! \brief Callback used to destroy the audiohook volume datastore
816  * \param data Volume information structure
817  * \return Returns nothing
818  */
819 static void audiohook_volume_destroy(void *data)
820 {
821         struct audiohook_volume *audiohook_volume = data;
822
823         /* Destroy the audiohook as it is no longer in use */
824         ast_audiohook_destroy(&audiohook_volume->audiohook);
825
826         /* Finally free ourselves, we are of no more use */
827         ast_free(audiohook_volume);
828
829         return;
830 }
831
832 /*! \brief Datastore used to store audiohook volume information */
833 static const struct ast_datastore_info audiohook_volume_datastore = {
834         .type = "Volume",
835         .destroy = audiohook_volume_destroy,
836 };
837
838 /*! \brief Helper function which actually gets called by audiohooks to perform the adjustment
839  * \param audiohook Audiohook attached to the channel
840  * \param chan Channel we are attached to
841  * \param frame Frame of audio we want to manipulate
842  * \param direction Direction the audio came in from
843  * \return Returns 0 on success, -1 on failure
844  */
845 static int audiohook_volume_callback(struct ast_audiohook *audiohook, struct ast_channel *chan, struct ast_frame *frame, enum ast_audiohook_direction direction)
846 {
847         struct ast_datastore *datastore = NULL;
848         struct audiohook_volume *audiohook_volume = NULL;
849         int *gain = NULL;
850
851         /* If the audiohook is shutting down don't even bother */
852         if (audiohook->status == AST_AUDIOHOOK_STATUS_DONE) {
853                 return 0;
854         }
855
856         /* Try to find the datastore containg adjustment information, if we can't just bail out */
857         if (!(datastore = ast_channel_datastore_find(chan, &audiohook_volume_datastore, NULL))) {
858                 return 0;
859         }
860
861         audiohook_volume = datastore->data;
862
863         /* Based on direction grab the appropriate adjustment value */
864         if (direction == AST_AUDIOHOOK_DIRECTION_READ) {
865                 gain = &audiohook_volume->read_adjustment;
866         } else if (direction == AST_AUDIOHOOK_DIRECTION_WRITE) {
867                 gain = &audiohook_volume->write_adjustment;
868         }
869
870         /* If an adjustment value is present modify the frame */
871         if (gain && *gain) {
872                 ast_frame_adjust_volume(frame, *gain);
873         }
874
875         return 0;
876 }
877
878 /*! \brief Helper function which finds and optionally creates an audiohook_volume_datastore datastore on a channel
879  * \param chan Channel to look on
880  * \param create Whether to create the datastore if not found
881  * \return Returns audiohook_volume structure on success, NULL on failure
882  */
883 static struct audiohook_volume *audiohook_volume_get(struct ast_channel *chan, int create)
884 {
885         struct ast_datastore *datastore = NULL;
886         struct audiohook_volume *audiohook_volume = NULL;
887
888         /* If we are able to find the datastore return the contents (which is actually an audiohook_volume structure) */
889         if ((datastore = ast_channel_datastore_find(chan, &audiohook_volume_datastore, NULL))) {
890                 return datastore->data;
891         }
892
893         /* 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 */
894         if (!create || !(datastore = ast_datastore_alloc(&audiohook_volume_datastore, NULL))) {
895                 return NULL;
896         }
897
898         /* Create a new audiohook_volume structure to contain our adjustments and audiohook */
899         if (!(audiohook_volume = ast_calloc(1, sizeof(*audiohook_volume)))) {
900                 ast_datastore_free(datastore);
901                 return NULL;
902         }
903
904         /* Setup our audiohook structure so we can manipulate the audio */
905         ast_audiohook_init(&audiohook_volume->audiohook, AST_AUDIOHOOK_TYPE_MANIPULATE, "Volume");
906         audiohook_volume->audiohook.manipulate_callback = audiohook_volume_callback;
907
908         /* Attach the audiohook_volume blob to the datastore and attach to the channel */
909         datastore->data = audiohook_volume;
910         ast_channel_datastore_add(chan, datastore);
911
912         /* All is well... put the audiohook into motion */
913         ast_audiohook_attach(chan, &audiohook_volume->audiohook);
914
915         return audiohook_volume;
916 }
917
918 /*! \brief Adjust the volume on frames read from or written to a channel
919  * \param chan Channel to muck with
920  * \param direction Direction to set on
921  * \param volume Value to adjust the volume by
922  * \return Returns 0 on success, -1 on failure
923  */
924 int ast_audiohook_volume_set(struct ast_channel *chan, enum ast_audiohook_direction direction, int volume)
925 {
926         struct audiohook_volume *audiohook_volume = NULL;
927
928         /* Attempt to find the audiohook volume information, but only create it if we are not setting the adjustment value to zero */
929         if (!(audiohook_volume = audiohook_volume_get(chan, (volume ? 1 : 0)))) {
930                 return -1;
931         }
932
933         /* Now based on the direction set the proper value */
934         if (direction == AST_AUDIOHOOK_DIRECTION_READ || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
935                 audiohook_volume->read_adjustment = volume;
936         }
937         if (direction == AST_AUDIOHOOK_DIRECTION_WRITE || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
938                 audiohook_volume->write_adjustment = volume;
939         }
940
941         return 0;
942 }
943
944 /*! \brief Retrieve the volume adjustment value on frames read from or written to a channel
945  * \param chan Channel to retrieve volume adjustment from
946  * \param direction Direction to retrieve
947  * \return Returns adjustment value
948  */
949 int ast_audiohook_volume_get(struct ast_channel *chan, enum ast_audiohook_direction direction)
950 {
951         struct audiohook_volume *audiohook_volume = NULL;
952         int adjustment = 0;
953
954         /* Attempt to find the audiohook volume information, but do not create it as we only want to look at the values */
955         if (!(audiohook_volume = audiohook_volume_get(chan, 0))) {
956                 return 0;
957         }
958
959         /* Grab the adjustment value based on direction given */
960         if (direction == AST_AUDIOHOOK_DIRECTION_READ) {
961                 adjustment = audiohook_volume->read_adjustment;
962         } else if (direction == AST_AUDIOHOOK_DIRECTION_WRITE) {
963                 adjustment = audiohook_volume->write_adjustment;
964         }
965
966         return adjustment;
967 }
968
969 /*! \brief Adjust the volume on frames read from or written to a channel
970  * \param chan Channel to muck with
971  * \param direction Direction to increase
972  * \param volume Value to adjust the adjustment by
973  * \return Returns 0 on success, -1 on failure
974  */
975 int ast_audiohook_volume_adjust(struct ast_channel *chan, enum ast_audiohook_direction direction, int volume)
976 {
977         struct audiohook_volume *audiohook_volume = NULL;
978
979         /* Attempt to find the audiohook volume information, and create an audiohook if none exists */
980         if (!(audiohook_volume = audiohook_volume_get(chan, 1))) {
981                 return -1;
982         }
983
984         /* Based on the direction change the specific adjustment value */
985         if (direction == AST_AUDIOHOOK_DIRECTION_READ || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
986                 audiohook_volume->read_adjustment += volume;
987         }
988         if (direction == AST_AUDIOHOOK_DIRECTION_WRITE || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
989                 audiohook_volume->write_adjustment += volume;
990         }
991
992         return 0;
993 }