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