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