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