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