audiohook signal trigger on every status change
[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 void ast_audiohook_update_status(struct ast_audiohook *audiohook, enum ast_audiohook_status status)
366 {
367         ast_audiohook_lock(audiohook);
368         if (audiohook->status != AST_AUDIOHOOK_STATUS_DONE) {
369                 audiohook->status = status;
370                 ast_cond_signal(&audiohook->trigger);
371         }
372         ast_audiohook_unlock(audiohook);
373 }
374
375 /*! \brief Detach audiohook from channel
376  * \param audiohook Audiohook structure
377  * \return Returns 0 on success, -1 on failure
378  */
379 int ast_audiohook_detach(struct ast_audiohook *audiohook)
380 {
381         if (audiohook->status == AST_AUDIOHOOK_STATUS_NEW || audiohook->status == AST_AUDIOHOOK_STATUS_DONE)
382                 return 0;
383
384         ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_SHUTDOWN);
385
386         while (audiohook->status != AST_AUDIOHOOK_STATUS_DONE)
387                 ast_audiohook_trigger_wait(audiohook);
388
389         return 0;
390 }
391
392 /*! \brief Detach audiohooks from list and destroy said list
393  * \param audiohook_list List of audiohooks
394  * \return Returns 0 on success, -1 on failure
395  */
396 int ast_audiohook_detach_list(struct ast_audiohook_list *audiohook_list)
397 {
398         int i = 0;
399         struct ast_audiohook *audiohook = NULL;
400
401         /* Drop any spies */
402         while ((audiohook = AST_LIST_REMOVE_HEAD(&audiohook_list->spy_list, list))) {
403                 ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
404         }
405
406         /* Drop any whispering sources */
407         while ((audiohook = AST_LIST_REMOVE_HEAD(&audiohook_list->whisper_list, list))) {
408                 ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
409         }
410
411         /* Drop any manipulaters */
412         while ((audiohook = AST_LIST_REMOVE_HEAD(&audiohook_list->manipulate_list, list))) {
413                 ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
414                 audiohook->manipulate_callback(audiohook, NULL, NULL, 0);
415         }
416
417         /* Drop translation paths if present */
418         for (i = 0; i < 2; i++) {
419                 if (audiohook_list->in_translate[i].trans_pvt)
420                         ast_translator_free_path(audiohook_list->in_translate[i].trans_pvt);
421                 if (audiohook_list->out_translate[i].trans_pvt)
422                         ast_translator_free_path(audiohook_list->out_translate[i].trans_pvt);
423         }
424         
425         /* Free ourselves */
426         ast_free(audiohook_list);
427
428         return 0;
429 }
430
431 /*! \brief find an audiohook based on its source
432  * \param audiohook_list The list of audiohooks to search in
433  * \param source The source of the audiohook we wish to find
434  * \return Return the corresponding audiohook or NULL if it cannot be found.
435  */
436 static struct ast_audiohook *find_audiohook_by_source(struct ast_audiohook_list *audiohook_list, const char *source)
437 {
438         struct ast_audiohook *audiohook = NULL;
439
440         AST_LIST_TRAVERSE(&audiohook_list->spy_list, audiohook, list) {
441                 if (!strcasecmp(audiohook->source, source))
442                         return audiohook;
443         }
444
445         AST_LIST_TRAVERSE(&audiohook_list->whisper_list, audiohook, list) {
446                 if (!strcasecmp(audiohook->source, source))
447                         return audiohook;
448         }
449
450         AST_LIST_TRAVERSE(&audiohook_list->manipulate_list, audiohook, list) {
451                 if (!strcasecmp(audiohook->source, source))
452                         return audiohook;
453         }
454
455         return NULL;
456 }
457
458 void ast_audiohook_move_by_source(struct ast_channel *old_chan, struct ast_channel *new_chan, const char *source)
459 {
460         struct ast_audiohook *audiohook;
461
462         if (!old_chan->audiohooks || !(audiohook = find_audiohook_by_source(old_chan->audiohooks, source))) {
463                 return;
464         }
465
466         /* By locking both channels and the audiohook, we can assure that
467          * another thread will not have a chance to read the audiohook's status
468          * as done, even though ast_audiohook_remove signals the trigger
469          * condition
470          */
471         ast_audiohook_lock(audiohook);
472         ast_audiohook_remove(old_chan, audiohook);
473         ast_audiohook_attach(new_chan, audiohook);
474         ast_audiohook_unlock(audiohook);
475 }
476
477 /*! \brief Detach specified source audiohook from channel
478  * \param chan Channel to detach from
479  * \param source Name of source to detach
480  * \return Returns 0 on success, -1 on failure
481  */
482 int ast_audiohook_detach_source(struct ast_channel *chan, const char *source)
483 {
484         struct ast_audiohook *audiohook = NULL;
485
486         ast_channel_lock(chan);
487
488         /* Ensure the channel has audiohooks on it */
489         if (!chan->audiohooks) {
490                 ast_channel_unlock(chan);
491                 return -1;
492         }
493
494         audiohook = find_audiohook_by_source(chan->audiohooks, source);
495
496         ast_channel_unlock(chan);
497
498         if (audiohook && audiohook->status != AST_AUDIOHOOK_STATUS_DONE)
499                 ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_SHUTDOWN);
500
501         return (audiohook ? 0 : -1);
502 }
503
504 /*!
505  * \brief Remove an audiohook from a specified channel
506  *
507  * \param chan Channel to remove from
508  * \param audiohook Audiohook to remove
509  *
510  * \return Returns 0 on success, -1 on failure
511  *
512  * \note The channel does not need to be locked before calling this function
513  */
514 int ast_audiohook_remove(struct ast_channel *chan, struct ast_audiohook *audiohook)
515 {
516         ast_channel_lock(chan);
517
518         if (!chan->audiohooks) {
519                 ast_channel_unlock(chan);
520                 return -1;
521         }
522
523         if (audiohook->type == AST_AUDIOHOOK_TYPE_SPY)
524                 AST_LIST_REMOVE(&chan->audiohooks->spy_list, audiohook, list);
525         else if (audiohook->type == AST_AUDIOHOOK_TYPE_WHISPER)
526                 AST_LIST_REMOVE(&chan->audiohooks->whisper_list, audiohook, list);
527         else if (audiohook->type == AST_AUDIOHOOK_TYPE_MANIPULATE)
528                 AST_LIST_REMOVE(&chan->audiohooks->manipulate_list, audiohook, list);
529
530         ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
531
532         ast_channel_unlock(chan);
533
534         return 0;
535 }
536
537 /*! \brief Pass a DTMF frame off to be handled by the audiohook core
538  * \param chan Channel that the list is coming off of
539  * \param audiohook_list List of audiohooks
540  * \param direction Direction frame is coming in from
541  * \param frame The frame itself
542  * \return Return frame on success, NULL on failure
543  */
544 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)
545 {
546         struct ast_audiohook *audiohook = NULL;
547
548         AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->manipulate_list, audiohook, list) {
549                 ast_audiohook_lock(audiohook);
550                 if (audiohook->status != AST_AUDIOHOOK_STATUS_RUNNING) {
551                         AST_LIST_REMOVE_CURRENT(list);
552                         ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
553                         ast_audiohook_unlock(audiohook);
554                         audiohook->manipulate_callback(audiohook, NULL, NULL, 0);
555                         continue;
556                 }
557                 if (ast_test_flag(audiohook, AST_AUDIOHOOK_WANTS_DTMF))
558                         audiohook->manipulate_callback(audiohook, chan, frame, direction);
559                 ast_audiohook_unlock(audiohook);
560         }
561         AST_LIST_TRAVERSE_SAFE_END;
562
563         return frame;
564 }
565
566 /*! \brief Pass an AUDIO frame off to be handled by the audiohook core
567  * \param chan Channel that the list is coming off of
568  * \param audiohook_list List of audiohooks
569  * \param direction Direction frame is coming in from
570  * \param frame The frame itself
571  * \return Return frame on success, NULL on failure
572  */
573 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)
574 {
575         struct ast_audiohook_translate *in_translate = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook_list->in_translate[0] : &audiohook_list->in_translate[1]);
576         struct ast_audiohook_translate *out_translate = (direction == AST_AUDIOHOOK_DIRECTION_READ ? &audiohook_list->out_translate[0] : &audiohook_list->out_translate[1]);
577         struct ast_frame *start_frame = frame, *middle_frame = frame, *end_frame = frame;
578         struct ast_audiohook *audiohook = NULL;
579         int samples = frame->samples;
580
581         /* If the frame coming in is not signed linear we have to send it through the in_translate path */
582         if (frame->subclass.codec != AST_FORMAT_SLINEAR) {
583                 if (in_translate->format != frame->subclass.codec) {
584                         if (in_translate->trans_pvt)
585                                 ast_translator_free_path(in_translate->trans_pvt);
586                         if (!(in_translate->trans_pvt = ast_translator_build_path(AST_FORMAT_SLINEAR, frame->subclass.codec)))
587                                 return frame;
588                         in_translate->format = frame->subclass.codec;
589                 }
590                 if (!(middle_frame = ast_translate(in_translate->trans_pvt, frame, 0)))
591                         return frame;
592                 samples = middle_frame->samples;
593         }
594
595         /* Queue up signed linear frame to each spy */
596         AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->spy_list, audiohook, list) {
597                 ast_audiohook_lock(audiohook);
598                 if (audiohook->status != AST_AUDIOHOOK_STATUS_RUNNING) {
599                         AST_LIST_REMOVE_CURRENT(list);
600                         ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
601                         ast_audiohook_unlock(audiohook);
602                         continue;
603                 }
604                 ast_audiohook_write_frame(audiohook, direction, middle_frame);
605                 ast_audiohook_unlock(audiohook);
606         }
607         AST_LIST_TRAVERSE_SAFE_END;
608
609         /* If this frame is being written out to the channel then we need to use whisper sources */
610         if (direction == AST_AUDIOHOOK_DIRECTION_WRITE && !AST_LIST_EMPTY(&audiohook_list->whisper_list)) {
611                 int i = 0;
612                 short read_buf[samples], combine_buf[samples], *data1 = NULL, *data2 = NULL;
613                 memset(&combine_buf, 0, sizeof(combine_buf));
614                 AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->whisper_list, audiohook, list) {
615                         ast_audiohook_lock(audiohook);
616                         if (audiohook->status != AST_AUDIOHOOK_STATUS_RUNNING) {
617                                 AST_LIST_REMOVE_CURRENT(list);
618                                 ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
619                                 ast_audiohook_unlock(audiohook);
620                                 continue;
621                         }
622                         if (ast_slinfactory_available(&audiohook->write_factory) >= samples && ast_slinfactory_read(&audiohook->write_factory, read_buf, samples)) {
623                                 /* Take audio from this whisper source and combine it into our main buffer */
624                                 for (i = 0, data1 = combine_buf, data2 = read_buf; i < samples; i++, data1++, data2++)
625                                         ast_slinear_saturated_add(data1, data2);
626                         }
627                         ast_audiohook_unlock(audiohook);
628                 }
629                 AST_LIST_TRAVERSE_SAFE_END;
630                 /* We take all of the combined whisper sources and combine them into the audio being written out */
631                 for (i = 0, data1 = middle_frame->data.ptr, data2 = combine_buf; i < samples; i++, data1++, data2++)
632                         ast_slinear_saturated_add(data1, data2);
633                 end_frame = middle_frame;
634         }
635
636         /* Pass off frame to manipulate audiohooks */
637         if (!AST_LIST_EMPTY(&audiohook_list->manipulate_list)) {
638                 AST_LIST_TRAVERSE_SAFE_BEGIN(&audiohook_list->manipulate_list, audiohook, list) {
639                         ast_audiohook_lock(audiohook);
640                         if (audiohook->status != AST_AUDIOHOOK_STATUS_RUNNING) {
641                                 AST_LIST_REMOVE_CURRENT(list);
642                                 ast_audiohook_update_status(audiohook, AST_AUDIOHOOK_STATUS_DONE);
643                                 ast_audiohook_unlock(audiohook);
644                                 /* We basically drop all of our links to the manipulate audiohook and prod it to do it's own destructive things */
645                                 audiohook->manipulate_callback(audiohook, chan, NULL, direction);
646                                 continue;
647                         }
648                         /* Feed in frame to manipulation */
649                         if (audiohook->manipulate_callback(audiohook, chan, middle_frame, direction)) {
650                                 ast_frfree(middle_frame);
651                                 middle_frame = NULL;
652                         }
653                         ast_audiohook_unlock(audiohook);
654                 }
655                 AST_LIST_TRAVERSE_SAFE_END;
656                 if (middle_frame) {
657                         end_frame = middle_frame;
658                 }
659         }
660
661         /* Now we figure out what to do with our end frame (whether to transcode or not) */
662         if (middle_frame == end_frame) {
663                 /* Middle frame was modified and became the end frame... let's see if we need to transcode */
664                 if (end_frame->subclass.codec != start_frame->subclass.codec) {
665                         if (out_translate->format != start_frame->subclass.codec) {
666                                 if (out_translate->trans_pvt)
667                                         ast_translator_free_path(out_translate->trans_pvt);
668                                 if (!(out_translate->trans_pvt = ast_translator_build_path(start_frame->subclass.codec, AST_FORMAT_SLINEAR))) {
669                                         /* We can't transcode this... drop our middle frame and return the original */
670                                         ast_frfree(middle_frame);
671                                         return start_frame;
672                                 }
673                                 out_translate->format = start_frame->subclass.codec;
674                         }
675                         /* Transcode from our middle (signed linear) frame to new format of the frame that came in */
676                         if (!(end_frame = ast_translate(out_translate->trans_pvt, middle_frame, 0))) {
677                                 /* Failed to transcode the frame... drop it and return the original */
678                                 ast_frfree(middle_frame);
679                                 return start_frame;
680                         }
681                         /* Here's the scoop... middle frame is no longer of use to us */
682                         ast_frfree(middle_frame);
683                 }
684         } else {
685                 /* No frame was modified, we can just drop our middle frame and pass the frame we got in out */
686                 if (middle_frame) {
687                         ast_frfree(middle_frame);
688                 }
689         }
690
691         return end_frame;
692 }
693
694 /*! \brief Pass a frame off to be handled by the audiohook core
695  * \param chan Channel that the list is coming off of
696  * \param audiohook_list List of audiohooks
697  * \param direction Direction frame is coming in from
698  * \param frame The frame itself
699  * \return Return frame on success, NULL on failure
700  */
701 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)
702 {
703         /* Pass off frame to it's respective list write function */
704         if (frame->frametype == AST_FRAME_VOICE)
705                 return audio_audiohook_write_list(chan, audiohook_list, direction, frame);
706         else if (frame->frametype == AST_FRAME_DTMF)
707                 return dtmf_audiohook_write_list(chan, audiohook_list, direction, frame);
708         else
709                 return frame;
710 }
711                         
712
713 /*! \brief Wait for audiohook trigger to be triggered
714  * \param audiohook Audiohook to wait on
715  */
716 void ast_audiohook_trigger_wait(struct ast_audiohook *audiohook)
717 {
718         struct timeval wait;
719         struct timespec ts;
720
721         wait = ast_tvadd(ast_tvnow(), ast_samp2tv(50000, 1000));
722         ts.tv_sec = wait.tv_sec;
723         ts.tv_nsec = wait.tv_usec * 1000;
724         
725         ast_cond_timedwait(&audiohook->trigger, &audiohook->lock, &ts);
726         
727         return;
728 }
729
730 /* Count number of channel audiohooks by type, regardless of type */
731 int ast_channel_audiohook_count_by_source(struct ast_channel *chan, const char *source, enum ast_audiohook_type type)
732 {
733         int count = 0;
734         struct ast_audiohook *ah = NULL;
735
736         if (!chan->audiohooks)
737                 return -1;
738
739         switch (type) {
740                 case AST_AUDIOHOOK_TYPE_SPY:
741                         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->audiohooks->spy_list, ah, list) {
742                                 if (!strcmp(ah->source, source)) {
743                                         count++;
744                                 }
745                         }
746                         AST_LIST_TRAVERSE_SAFE_END;
747                         break;
748                 case AST_AUDIOHOOK_TYPE_WHISPER:
749                         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->audiohooks->whisper_list, ah, list) {
750                                 if (!strcmp(ah->source, source)) {
751                                         count++;
752                                 }
753                         }
754                         AST_LIST_TRAVERSE_SAFE_END;
755                         break;
756                 case AST_AUDIOHOOK_TYPE_MANIPULATE:
757                         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->audiohooks->manipulate_list, ah, list) {
758                                 if (!strcmp(ah->source, source)) {
759                                         count++;
760                                 }
761                         }
762                         AST_LIST_TRAVERSE_SAFE_END;
763                         break;
764                 default:
765                         ast_log(LOG_DEBUG, "Invalid audiohook type supplied, (%d)\n", type);
766                         return -1;
767         }
768
769         return count;
770 }
771
772 /* Count number of channel audiohooks by type that are running */
773 int ast_channel_audiohook_count_by_source_running(struct ast_channel *chan, const char *source, enum ast_audiohook_type type)
774 {
775         int count = 0;
776         struct ast_audiohook *ah = NULL;
777         if (!chan->audiohooks)
778                 return -1;
779
780         switch (type) {
781                 case AST_AUDIOHOOK_TYPE_SPY:
782                         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->audiohooks->spy_list, ah, list) {
783                                 if ((!strcmp(ah->source, source)) && (ah->status == AST_AUDIOHOOK_STATUS_RUNNING))
784                                         count++;
785                         }
786                         AST_LIST_TRAVERSE_SAFE_END;
787                         break;
788                 case AST_AUDIOHOOK_TYPE_WHISPER:
789                         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->audiohooks->whisper_list, ah, list) {
790                                 if ((!strcmp(ah->source, source)) && (ah->status == AST_AUDIOHOOK_STATUS_RUNNING))
791                                         count++;
792                         }
793                         AST_LIST_TRAVERSE_SAFE_END;
794                         break;
795                 case AST_AUDIOHOOK_TYPE_MANIPULATE:
796                         AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->audiohooks->manipulate_list, ah, list) {
797                                 if ((!strcmp(ah->source, source)) && (ah->status == AST_AUDIOHOOK_STATUS_RUNNING))
798                                         count++;
799                         }
800                         AST_LIST_TRAVERSE_SAFE_END;
801                         break;
802                 default:
803                         ast_log(LOG_DEBUG, "Invalid audiohook type supplied, (%d)\n", type);
804                         return -1;
805         }
806         return count;
807 }
808
809 /*! \brief Audiohook volume adjustment structure */
810 struct audiohook_volume {
811         struct ast_audiohook audiohook; /*!< Audiohook attached to the channel */
812         int read_adjustment;            /*!< Value to adjust frames read from the channel by */
813         int write_adjustment;           /*!< Value to adjust frames written to the channel by */
814 };
815
816 /*! \brief Callback used to destroy the audiohook volume datastore
817  * \param data Volume information structure
818  * \return Returns nothing
819  */
820 static void audiohook_volume_destroy(void *data)
821 {
822         struct audiohook_volume *audiohook_volume = data;
823
824         /* Destroy the audiohook as it is no longer in use */
825         ast_audiohook_destroy(&audiohook_volume->audiohook);
826
827         /* Finally free ourselves, we are of no more use */
828         ast_free(audiohook_volume);
829
830         return;
831 }
832
833 /*! \brief Datastore used to store audiohook volume information */
834 static const struct ast_datastore_info audiohook_volume_datastore = {
835         .type = "Volume",
836         .destroy = audiohook_volume_destroy,
837 };
838
839 /*! \brief Helper function which actually gets called by audiohooks to perform the adjustment
840  * \param audiohook Audiohook attached to the channel
841  * \param chan Channel we are attached to
842  * \param frame Frame of audio we want to manipulate
843  * \param direction Direction the audio came in from
844  * \return Returns 0 on success, -1 on failure
845  */
846 static int audiohook_volume_callback(struct ast_audiohook *audiohook, struct ast_channel *chan, struct ast_frame *frame, enum ast_audiohook_direction direction)
847 {
848         struct ast_datastore *datastore = NULL;
849         struct audiohook_volume *audiohook_volume = NULL;
850         int *gain = NULL;
851
852         /* If the audiohook is shutting down don't even bother */
853         if (audiohook->status == AST_AUDIOHOOK_STATUS_DONE) {
854                 return 0;
855         }
856
857         /* Try to find the datastore containg adjustment information, if we can't just bail out */
858         if (!(datastore = ast_channel_datastore_find(chan, &audiohook_volume_datastore, NULL))) {
859                 return 0;
860         }
861
862         audiohook_volume = datastore->data;
863
864         /* Based on direction grab the appropriate adjustment value */
865         if (direction == AST_AUDIOHOOK_DIRECTION_READ) {
866                 gain = &audiohook_volume->read_adjustment;
867         } else if (direction == AST_AUDIOHOOK_DIRECTION_WRITE) {
868                 gain = &audiohook_volume->write_adjustment;
869         }
870
871         /* If an adjustment value is present modify the frame */
872         if (gain && *gain) {
873                 ast_frame_adjust_volume(frame, *gain);
874         }
875
876         return 0;
877 }
878
879 /*! \brief Helper function which finds and optionally creates an audiohook_volume_datastore datastore on a channel
880  * \param chan Channel to look on
881  * \param create Whether to create the datastore if not found
882  * \return Returns audiohook_volume structure on success, NULL on failure
883  */
884 static struct audiohook_volume *audiohook_volume_get(struct ast_channel *chan, int create)
885 {
886         struct ast_datastore *datastore = NULL;
887         struct audiohook_volume *audiohook_volume = NULL;
888
889         /* If we are able to find the datastore return the contents (which is actually an audiohook_volume structure) */
890         if ((datastore = ast_channel_datastore_find(chan, &audiohook_volume_datastore, NULL))) {
891                 return datastore->data;
892         }
893
894         /* 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 */
895         if (!create || !(datastore = ast_datastore_alloc(&audiohook_volume_datastore, NULL))) {
896                 return NULL;
897         }
898
899         /* Create a new audiohook_volume structure to contain our adjustments and audiohook */
900         if (!(audiohook_volume = ast_calloc(1, sizeof(*audiohook_volume)))) {
901                 ast_datastore_free(datastore);
902                 return NULL;
903         }
904
905         /* Setup our audiohook structure so we can manipulate the audio */
906         ast_audiohook_init(&audiohook_volume->audiohook, AST_AUDIOHOOK_TYPE_MANIPULATE, "Volume");
907         audiohook_volume->audiohook.manipulate_callback = audiohook_volume_callback;
908
909         /* Attach the audiohook_volume blob to the datastore and attach to the channel */
910         datastore->data = audiohook_volume;
911         ast_channel_datastore_add(chan, datastore);
912
913         /* All is well... put the audiohook into motion */
914         ast_audiohook_attach(chan, &audiohook_volume->audiohook);
915
916         return audiohook_volume;
917 }
918
919 /*! \brief Adjust the volume on frames read from or written to a channel
920  * \param chan Channel to muck with
921  * \param direction Direction to set on
922  * \param volume Value to adjust the volume by
923  * \return Returns 0 on success, -1 on failure
924  */
925 int ast_audiohook_volume_set(struct ast_channel *chan, enum ast_audiohook_direction direction, int volume)
926 {
927         struct audiohook_volume *audiohook_volume = NULL;
928
929         /* Attempt to find the audiohook volume information, but only create it if we are not setting the adjustment value to zero */
930         if (!(audiohook_volume = audiohook_volume_get(chan, (volume ? 1 : 0)))) {
931                 return -1;
932         }
933
934         /* Now based on the direction set the proper value */
935         if (direction == AST_AUDIOHOOK_DIRECTION_READ || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
936                 audiohook_volume->read_adjustment = volume;
937         }
938         if (direction == AST_AUDIOHOOK_DIRECTION_WRITE || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
939                 audiohook_volume->write_adjustment = volume;
940         }
941
942         return 0;
943 }
944
945 /*! \brief Retrieve the volume adjustment value on frames read from or written to a channel
946  * \param chan Channel to retrieve volume adjustment from
947  * \param direction Direction to retrieve
948  * \return Returns adjustment value
949  */
950 int ast_audiohook_volume_get(struct ast_channel *chan, enum ast_audiohook_direction direction)
951 {
952         struct audiohook_volume *audiohook_volume = NULL;
953         int adjustment = 0;
954
955         /* Attempt to find the audiohook volume information, but do not create it as we only want to look at the values */
956         if (!(audiohook_volume = audiohook_volume_get(chan, 0))) {
957                 return 0;
958         }
959
960         /* Grab the adjustment value based on direction given */
961         if (direction == AST_AUDIOHOOK_DIRECTION_READ) {
962                 adjustment = audiohook_volume->read_adjustment;
963         } else if (direction == AST_AUDIOHOOK_DIRECTION_WRITE) {
964                 adjustment = audiohook_volume->write_adjustment;
965         }
966
967         return adjustment;
968 }
969
970 /*! \brief Adjust the volume on frames read from or written to a channel
971  * \param chan Channel to muck with
972  * \param direction Direction to increase
973  * \param volume Value to adjust the adjustment by
974  * \return Returns 0 on success, -1 on failure
975  */
976 int ast_audiohook_volume_adjust(struct ast_channel *chan, enum ast_audiohook_direction direction, int volume)
977 {
978         struct audiohook_volume *audiohook_volume = NULL;
979
980         /* Attempt to find the audiohook volume information, and create an audiohook if none exists */
981         if (!(audiohook_volume = audiohook_volume_get(chan, 1))) {
982                 return -1;
983         }
984
985         /* Based on the direction change the specific adjustment value */
986         if (direction == AST_AUDIOHOOK_DIRECTION_READ || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
987                 audiohook_volume->read_adjustment += volume;
988         }
989         if (direction == AST_AUDIOHOOK_DIRECTION_WRITE || direction == AST_AUDIOHOOK_DIRECTION_BOTH) {
990                 audiohook_volume->write_adjustment += volume;
991         }
992
993         return 0;
994 }