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