New HD ConfBridge conferencing application.
[asterisk/asterisk.git] / bridges / bridge_softmix.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2011, Digium, Inc.
5  *
6  * Joshua Colp <jcolp@digium.com>
7  * David Vossel <dvossel@digium.com>
8  *
9  * See http://www.asterisk.org for more information about
10  * the Asterisk project. Please do not directly contact
11  * any of the maintainers of this project for assistance;
12  * the project provides a web site, mailing lists and IRC
13  * channels for your use.
14  *
15  * This program is free software, distributed under the terms of
16  * the GNU General Public License Version 2. See the LICENSE file
17  * at the top of the source tree.
18  */
19
20 /*! \file
21  *
22  * \brief Multi-party software based channel mixing
23  *
24  * \author Joshua Colp <jcolp@digium.com>
25  * \author David Vossel <dvossel@digium.com>
26  *
27  * \ingroup bridges
28  */
29
30 #include "asterisk.h"
31
32 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
33
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <sys/time.h>
38 #include <signal.h>
39 #include <errno.h>
40 #include <unistd.h>
41
42 #include "asterisk/module.h"
43 #include "asterisk/channel.h"
44 #include "asterisk/bridging.h"
45 #include "asterisk/bridging_technology.h"
46 #include "asterisk/frame.h"
47 #include "asterisk/options.h"
48 #include "asterisk/logger.h"
49 #include "asterisk/slinfactory.h"
50 #include "asterisk/astobj2.h"
51 #include "asterisk/timing.h"
52 #include "asterisk/translate.h"
53
54 #define MAX_DATALEN 8096
55
56 /*! \brief Interval at which mixing will take place. Valid options are 10, 20, and 40. */
57 #define DEFAULT_SOFTMIX_INTERVAL 20
58
59 /*! \brief Size of the buffer used for sample manipulation */
60 #define SOFTMIX_DATALEN(rate, interval) ((rate/50) * (interval / 10))
61
62 /*! \brief Number of samples we are dealing with */
63 #define SOFTMIX_SAMPLES(rate, interval) (SOFTMIX_DATALEN(rate, interval) / 2)
64
65 /*! \brief Number of mixing iterations to perform between gathering statistics. */
66 #define SOFTMIX_STAT_INTERVAL 100
67
68 /* This is the threshold in ms at which a channel's own audio will stop getting
69  * mixed out its own write audio stream because it is not talking. */
70 #define DEFAULT_SOFTMIX_SILENCE_THRESHOLD 2500
71 #define DEFAULT_SOFTMIX_TALKING_THRESHOLD 160
72
73 /*! \brief Structure which contains per-channel mixing information */
74 struct softmix_channel {
75         /*! Lock to protect this structure */
76         ast_mutex_t lock;
77         /*! Factory which contains audio read in from the channel */
78         struct ast_slinfactory factory;
79         /*! Frame that contains mixed audio to be written out to the channel */
80         struct ast_frame write_frame;
81         /*! Frame that contains mixed audio read from the channel */
82         struct ast_frame read_frame;
83         /*! DSP for detecting silence */
84         struct ast_dsp *dsp;
85         /*! Bit used to indicate if a channel is talking or not. This affects how
86          * the channel's audio is mixed back to it. */
87         int talking:1;
88         /*! Bit used to indicate that the channel provided audio for this mixing interval */
89         int have_audio:1;
90         /*! Bit used to indicate that a frame is available to be written out to the channel */
91         int have_frame:1;
92         /*! Buffer containing final mixed audio from all sources */
93         short final_buf[MAX_DATALEN];
94         /*! Buffer containing only the audio from the channel */
95         short our_buf[MAX_DATALEN];
96 };
97
98 struct softmix_bridge_data {
99         struct ast_timer *timer;
100         unsigned int internal_rate;
101         unsigned int internal_mixing_interval;
102 };
103
104 struct softmix_stats {
105                 /*! Each index represents a sample rate used above the internal rate. */
106                 unsigned int sample_rates[16];
107                 /*! Each index represents the number of channels using the same index in the sample_rates array.  */
108                 unsigned int num_channels[16];
109                 /*! the number of channels above the internal sample rate */
110                 unsigned int num_above_internal_rate;
111                 /*! the number of channels at the internal sample rate */
112                 unsigned int num_at_internal_rate;
113                 /*! the absolute highest sample rate supported by any channel in the bridge */
114                 unsigned int highest_supported_rate;
115                 /*! Is the sample rate locked by the bridge, if so what is that rate.*/
116                 unsigned int locked_rate;
117 };
118
119 struct softmix_mixing_array {
120         int max_num_entries;
121         int used_entries;
122         int16_t **buffers;
123 };
124
125 struct softmix_translate_helper_entry {
126         int num_times_requested; /*!< Once this entry is no longer requested, free the trans_pvt
127                                       and re-init if it was usable. */
128         struct ast_format dst_format; /*!< The destination format for this helper */
129         struct ast_trans_pvt *trans_pvt; /*!< the translator for this slot. */
130         struct ast_frame *out_frame; /*!< The output frame from the last translation */
131         AST_LIST_ENTRY(softmix_translate_helper_entry) entry;
132 };
133
134 struct softmix_translate_helper {
135         struct ast_format slin_src; /*!< the source format expected for all the translators */
136         AST_LIST_HEAD_NOLOCK(, softmix_translate_helper_entry) entries;
137 };
138
139 static struct softmix_translate_helper_entry *softmix_translate_helper_entry_alloc(struct ast_format *dst)
140 {
141         struct softmix_translate_helper_entry *entry;
142         if (!(entry = ast_calloc(1, sizeof(*entry)))) {
143                 return NULL;
144         }
145         ast_format_copy(&entry->dst_format, dst);
146         return entry;
147 }
148
149 static void *softmix_translate_helper_free_entry(struct softmix_translate_helper_entry *entry)
150 {
151         if (entry->trans_pvt) {
152                 ast_translator_free_path(entry->trans_pvt);
153         }
154         if (entry->out_frame) {
155                 ast_frfree(entry->out_frame);
156         }
157         ast_free(entry);
158         return NULL;
159 }
160
161 static void softmix_translate_helper_init(struct softmix_translate_helper *trans_helper, unsigned int sample_rate)
162 {
163         memset(trans_helper, 0, sizeof(*trans_helper));
164         ast_format_set(&trans_helper->slin_src, ast_format_slin_by_rate(sample_rate), 0);
165 }
166
167 static void softmix_translate_helper_destroy(struct softmix_translate_helper *trans_helper)
168 {
169         struct softmix_translate_helper_entry *entry;
170
171         while ((entry = AST_LIST_REMOVE_HEAD(&trans_helper->entries, entry))) {
172                 softmix_translate_helper_free_entry(entry);
173         }
174 }
175
176 static void softmix_translate_helper_change_rate(struct softmix_translate_helper *trans_helper, unsigned int sample_rate)
177 {
178         struct softmix_translate_helper_entry *entry;
179
180         ast_format_set(&trans_helper->slin_src, ast_format_slin_by_rate(sample_rate), 0);
181         AST_LIST_TRAVERSE_SAFE_BEGIN(&trans_helper->entries, entry, entry) {
182                 if (entry->trans_pvt) {
183                         ast_translator_free_path(entry->trans_pvt);
184                         if (!(entry->trans_pvt = ast_translator_build_path(&entry->dst_format, &trans_helper->slin_src))) {
185                                 AST_LIST_REMOVE_CURRENT(entry);
186                                 entry = softmix_translate_helper_free_entry(entry);
187                         }
188                 }
189         }
190         AST_LIST_TRAVERSE_SAFE_END;
191 }
192
193 /*!
194  * \internal
195  * \brief Get the next available audio on the softmix channel's read stream
196  * and determine if it should be mixed out or not on the write stream. 
197  *
198  * \retval pointer to buffer containing the exact number of samples requested on success.
199  * \retval NULL if no samples are present
200  */
201 static int16_t *softmix_process_read_audio(struct softmix_channel *sc, unsigned int num_samples)
202 {
203         if ((ast_slinfactory_available(&sc->factory) >= num_samples) &&
204                 ast_slinfactory_read(&sc->factory, sc->our_buf, num_samples)) {
205                 sc->have_audio = 1;
206                 return sc->our_buf;
207         }
208         sc->have_audio = 0;
209         return NULL;
210 }
211
212 /*!
213  * \internal
214  * \brief Process a softmix channel's write audio
215  *
216  * \details This function will remove the channel's talking from its own audio if present and
217  * possibly even do the channel's write translation for it depending on how many other
218  * channels use the same write format.
219  */
220 static void softmix_process_write_audio(struct softmix_translate_helper *trans_helper,
221         struct ast_format *raw_write_fmt,
222         struct softmix_channel *sc)
223 {
224         struct softmix_translate_helper_entry *entry = NULL;
225         int i;
226
227         /* If we provided audio that was not determined to be silence,
228          * then take it out while in slinear format. */
229         if (sc->have_audio && sc->talking) {
230                 for (i = 0; i < sc->write_frame.samples; i++) {
231                         ast_slinear_saturated_subtract(&sc->final_buf[i], &sc->our_buf[i]);
232                 }
233                 /* do not do any special write translate optimization if we had to make
234                  * a special mix for them to remove their own audio. */
235                 return;
236         }
237
238         AST_LIST_TRAVERSE(&trans_helper->entries, entry, entry) {
239                 if (ast_format_cmp(&entry->dst_format, raw_write_fmt) == AST_FORMAT_CMP_EQUAL) {
240                         entry->num_times_requested++;
241                 } else {
242                         continue;
243                 }
244                 if (!entry->trans_pvt && (entry->num_times_requested > 1)) {
245                         entry->trans_pvt = ast_translator_build_path(&entry->dst_format, &trans_helper->slin_src);
246                 }
247                 if (entry->trans_pvt && !entry->out_frame) {
248                         entry->out_frame = ast_translate(entry->trans_pvt, &sc->write_frame, 0);
249                 }
250                 if (entry->out_frame && (entry->out_frame->datalen < MAX_DATALEN)) {
251                         ast_format_copy(&sc->write_frame.subclass.format, &entry->out_frame->subclass.format);
252                         memcpy(sc->final_buf, entry->out_frame->data.ptr, entry->out_frame->datalen);
253                         sc->write_frame.datalen = entry->out_frame->datalen;
254                         sc->write_frame.samples = entry->out_frame->samples;
255                 }
256                 break;
257         }
258
259         /* add new entry into list if this format destination was not matched. */
260         if (!entry && (entry = softmix_translate_helper_entry_alloc(raw_write_fmt))) {
261                 AST_LIST_INSERT_HEAD(&trans_helper->entries, entry, entry);
262         }
263 }
264
265 static void softmix_translate_helper_cleanup(struct softmix_translate_helper *trans_helper)
266 {
267         struct softmix_translate_helper_entry *entry = NULL;
268         AST_LIST_TRAVERSE(&trans_helper->entries, entry, entry) {
269                 if (entry->out_frame) {
270                         ast_frfree(entry->out_frame);
271                         entry->out_frame = NULL;
272                 }
273                 entry->num_times_requested = 0;
274         }
275 }
276
277 static void softmix_bridge_data_destroy(void *obj)
278 {
279         struct softmix_bridge_data *softmix_data = obj;
280         ast_timer_close(softmix_data->timer);
281 }
282
283 /*! \brief Function called when a bridge is created */
284 static int softmix_bridge_create(struct ast_bridge *bridge)
285 {
286         struct softmix_bridge_data *softmix_data;
287
288         if (!(softmix_data = ao2_alloc(sizeof(*softmix_data), softmix_bridge_data_destroy))) {
289                 return -1;
290         }
291         if (!(softmix_data->timer = ast_timer_open())) {
292                 ao2_ref(softmix_data, -1);
293                 return -1;
294         }
295
296         /* start at 8khz, let it grow from there */
297         softmix_data->internal_rate = 8000;
298         softmix_data->internal_mixing_interval = DEFAULT_SOFTMIX_INTERVAL;
299
300         bridge->bridge_pvt = softmix_data;
301         return 0;
302 }
303
304 /*! \brief Function called when a bridge is destroyed */
305 static int softmix_bridge_destroy(struct ast_bridge *bridge)
306 {
307         struct softmix_bridge_data *softmix_data = bridge->bridge_pvt;
308         if (!bridge->bridge_pvt) {
309                 return -1;
310         }
311         ao2_ref(softmix_data, -1);
312         bridge->bridge_pvt = NULL;
313         return 0;
314 }
315
316 static void set_softmix_bridge_data(int rate, int interval, struct ast_bridge_channel *bridge_channel, int reset)
317 {
318         struct softmix_channel *sc = bridge_channel->bridge_pvt;
319         unsigned int channel_read_rate = ast_format_rate(&bridge_channel->chan->rawreadformat);
320
321         ast_mutex_lock(&sc->lock);
322         if (reset) {
323                 ast_slinfactory_destroy(&sc->factory);
324                 ast_dsp_free(sc->dsp);
325         }
326         /* Setup read/write frame parameters */
327         sc->write_frame.frametype = AST_FRAME_VOICE;
328         ast_format_set(&sc->write_frame.subclass.format, ast_format_slin_by_rate(rate), 0);
329         sc->write_frame.data.ptr = sc->final_buf;
330         sc->write_frame.datalen = SOFTMIX_DATALEN(rate, interval);
331         sc->write_frame.samples = SOFTMIX_SAMPLES(rate, interval);
332
333         sc->read_frame.frametype = AST_FRAME_VOICE;
334         ast_format_set(&sc->read_frame.subclass.format, ast_format_slin_by_rate(channel_read_rate), 0);
335         sc->read_frame.data.ptr = sc->our_buf;
336         sc->read_frame.datalen = SOFTMIX_DATALEN(channel_read_rate, interval);
337         sc->read_frame.samples = SOFTMIX_SAMPLES(channel_read_rate, interval);
338
339         /* Setup smoother */
340         ast_slinfactory_init_with_format(&sc->factory, &sc->write_frame.subclass.format);
341
342         /* set new read and write formats on channel. */
343         ast_set_read_format(bridge_channel->chan, &sc->read_frame.subclass.format);
344         ast_set_write_format(bridge_channel->chan, &sc->write_frame.subclass.format);
345
346         /* set up new DSP.  This is on the read side only right before the read frame enters the smoother.  */
347         sc->dsp = ast_dsp_new_with_rate(channel_read_rate);
348         /* we want to aggressively detect silence to avoid feedback */
349         if (bridge_channel->tech_args.talking_threshold) {
350                 ast_dsp_set_threshold(sc->dsp, bridge_channel->tech_args.talking_threshold);
351         } else {
352                 ast_dsp_set_threshold(sc->dsp, DEFAULT_SOFTMIX_TALKING_THRESHOLD);
353         }
354
355         ast_mutex_unlock(&sc->lock);
356 }
357
358 /*! \brief Function called when a channel is joined into the bridge */
359 static int softmix_bridge_join(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
360 {
361         struct softmix_channel *sc = NULL;
362         struct softmix_bridge_data *softmix_data = bridge->bridge_pvt;
363
364         /* Create a new softmix_channel structure and allocate various things on it */
365         if (!(sc = ast_calloc(1, sizeof(*sc)))) {
366                 return -1;
367         }
368
369         /* Can't forget the lock */
370         ast_mutex_init(&sc->lock);
371
372         /* Can't forget to record our pvt structure within the bridged channel structure */
373         bridge_channel->bridge_pvt = sc;
374
375         set_softmix_bridge_data(softmix_data->internal_rate,
376                 softmix_data->internal_mixing_interval ? softmix_data->internal_mixing_interval : DEFAULT_SOFTMIX_INTERVAL,
377                 bridge_channel, 0);
378
379         return 0;
380 }
381
382 /*! \brief Function called when a channel leaves the bridge */
383 static int softmix_bridge_leave(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
384 {
385         struct softmix_channel *sc = bridge_channel->bridge_pvt;
386
387         if (!(bridge_channel->bridge_pvt)) {
388                 return 0;
389         }
390         bridge_channel->bridge_pvt = NULL;
391
392         /* Drop mutex lock */
393         ast_mutex_destroy(&sc->lock);
394
395         /* Drop the factory */
396         ast_slinfactory_destroy(&sc->factory);
397
398         /* Drop the DSP */
399         ast_dsp_free(sc->dsp);
400
401         /* Eep! drop ourselves */
402         ast_free(sc);
403
404         return 0;
405 }
406
407 /*!
408  * \internal
409  * \brief If the bridging core passes DTMF to us, then they want it to be distributed out to all memebers. Do that here.
410  */
411 static void softmix_pass_dtmf(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
412 {
413         struct ast_bridge_channel *tmp;
414         AST_LIST_TRAVERSE(&bridge->channels, tmp, entry) {
415                 if (tmp == bridge_channel) {
416                         continue;
417                 }
418                 ast_write(tmp->chan, frame);
419         }
420 }
421
422 /*! \brief Function called when a channel writes a frame into the bridge */
423 static enum ast_bridge_write_result softmix_bridge_write(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
424 {
425         struct softmix_channel *sc = bridge_channel->bridge_pvt;
426         struct softmix_bridge_data *softmix_data = bridge->bridge_pvt;
427         int totalsilence = 0;
428         int silence_threshold = bridge_channel->tech_args.silence_threshold ?
429                 bridge_channel->tech_args.silence_threshold :
430                 DEFAULT_SOFTMIX_SILENCE_THRESHOLD;
431         char update_talking = -1;  /* if this is set to 0 or 1, tell the bridge that the channel has started or stopped talking. */
432
433         /* Only accept audio frames, all others are unsupported */
434         if (frame->frametype == AST_FRAME_DTMF_END || frame->frametype == AST_FRAME_DTMF_BEGIN) {
435                 softmix_pass_dtmf(bridge, bridge_channel, frame);
436                 return AST_BRIDGE_WRITE_SUCCESS;
437         } else if (frame->frametype != AST_FRAME_VOICE) {
438                 return AST_BRIDGE_WRITE_UNSUPPORTED;
439         }
440
441         ast_mutex_lock(&sc->lock);
442
443         ast_dsp_silence(sc->dsp, frame, &totalsilence);
444         if (totalsilence < silence_threshold) {
445                 if (!sc->talking) {
446                         update_talking = 1;
447                 }
448                 sc->talking = 1; /* tell the write process we have audio to be mixed out */
449         } else {
450                 if (sc->talking) {
451                         update_talking = 0;
452                 }
453                 sc->talking = 0;
454         }
455
456         /* Before adding audio in, make sure we haven't fallen behind. If audio has fallen
457          * behind 4 times the amount of samples mixed on every iteration of the mixer, Re-sync
458          * the audio by flushing the buffer before adding new audio in. */
459         if (ast_slinfactory_available(&sc->factory) > (4 * SOFTMIX_SAMPLES(softmix_data->internal_rate, softmix_data->internal_mixing_interval))) {
460                 ast_slinfactory_flush(&sc->factory);
461         }
462
463         /* If a frame was provided add it to the smoother, unless drop silence is enabled and this frame
464          * is not determined to be talking. */
465         if (!(bridge_channel->tech_args.drop_silence && !sc->talking) &&
466                 (frame->frametype == AST_FRAME_VOICE && ast_format_is_slinear(&frame->subclass.format))) {
467                 ast_slinfactory_feed(&sc->factory, frame);
468         }
469
470         /* If a frame is ready to be written out, do so */
471         if (sc->have_frame) {
472                 ast_write(bridge_channel->chan, &sc->write_frame);
473                 sc->have_frame = 0;
474         }
475
476         /* Alllll done */
477         ast_mutex_unlock(&sc->lock);
478
479         if (update_talking != -1) {
480                 ast_bridge_notify_talking(bridge, bridge_channel, update_talking);
481         }
482
483         return AST_BRIDGE_WRITE_SUCCESS;
484 }
485
486 /*! \brief Function called when the channel's thread is poked */
487 static int softmix_bridge_poke(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
488 {
489         struct softmix_channel *sc = bridge_channel->bridge_pvt;
490
491         ast_mutex_lock(&sc->lock);
492
493         if (sc->have_frame) {
494                 ast_write(bridge_channel->chan, &sc->write_frame);
495                 sc->have_frame = 0;
496         }
497
498         ast_mutex_unlock(&sc->lock);
499
500         return 0;
501 }
502
503 static void gather_softmix_stats(struct softmix_stats *stats,
504         const struct softmix_bridge_data *softmix_data,
505         struct ast_bridge_channel *bridge_channel)
506 {
507         int channel_native_rate;
508         int i;
509         /* Gather stats about channel sample rates. */
510         channel_native_rate = MAX(ast_format_rate(&bridge_channel->chan->rawwriteformat),
511                 ast_format_rate(&bridge_channel->chan->rawreadformat));
512
513         if (channel_native_rate > stats->highest_supported_rate) {
514                 stats->highest_supported_rate = channel_native_rate;
515         }
516         if (channel_native_rate > softmix_data->internal_rate) {
517                 for (i = 0; i < ARRAY_LEN(stats->sample_rates); i++) {
518                         if (stats->sample_rates[i] == channel_native_rate) {
519                                 stats->num_channels[i]++;
520                                 break;
521                         } else if (!stats->sample_rates[i]) {
522                                 stats->sample_rates[i] = channel_native_rate;
523                                 stats->num_channels[i]++;
524                                 break;
525                         }
526                 }
527                 stats->num_above_internal_rate++;
528         } else if (channel_native_rate == softmix_data->internal_rate) {
529                 stats->num_at_internal_rate++;
530         }
531 }
532 /*!
533  * \internal
534  * \brief Analyse mixing statistics and change bridges internal rate
535  * if necessary.
536  *
537  * \retval 0, no changes to internal rate 
538  * \ratval 1, internal rate was changed, update all the channels on the next mixing iteration.
539  */
540 static unsigned int analyse_softmix_stats(struct softmix_stats *stats, struct softmix_bridge_data *softmix_data)
541 {
542         int i;
543         /* Re-adjust the internal bridge sample rate if
544          * 1. The bridge's internal sample rate is locked in at a sample
545          *    rate other than the current sample rate being used.
546          * 2. two or more channels support a higher sample rate
547          * 3. no channels support the current sample rate or a higher rate
548          */
549         if (stats->locked_rate) {
550                 /* if the rate is locked by the bridge, only update it if it differs
551                  * from the current rate we are using. */
552                 if (softmix_data->internal_rate != stats->locked_rate) {
553                         softmix_data->internal_rate = stats->locked_rate;
554                         ast_debug(1, " Bridge is locked in at sample rate %d\n", softmix_data->internal_rate);
555                         return 1;
556                 }
557         } else if (stats->num_above_internal_rate >= 2) {
558                 /* the highest rate is just used as a starting point */
559                 unsigned int best_rate = stats->highest_supported_rate;
560                 int best_index = -1;
561
562                 for (i = 0; i < ARRAY_LEN(stats->num_channels); i++) {
563                         if (stats->num_channels[i]) {
564                                 break;
565                         }
566                         /* best_rate starts out being the first sample rate
567                          * greater than the internal sample rate that 2 or
568                          * more channels support. */
569                         if (stats->num_channels[i] >= 2 && (best_index == -1)) {
570                                 best_rate = stats->sample_rates[i];
571                                 best_index = i;
572                         /* If it has been detected that multiple rates above
573                          * the internal rate are present, compare those rates
574                          * to each other and pick the highest one two or more
575                          * channels support. */
576                         } else if (((best_index != -1) &&
577                                 (stats->num_channels[i] >= 2) &&
578                                 (stats->sample_rates[best_index] < stats->sample_rates[i]))) {
579                                 best_rate = stats->sample_rates[i];
580                                 best_index = i;
581                         /* It is possible that multiple channels exist with native sample
582                          * rates above the internal sample rate, but none of those channels
583                          * have the same rate in common.  In this case, the lowest sample
584                          * rate among those channels is picked. Over time as additional
585                          * statistic runs are made the internal sample rate number will
586                          * adjust to the most optimal sample rate, but it may take multiple
587                          * iterations. */
588                         } else if (best_index == -1) {
589                                 best_rate = MIN(best_rate, stats->sample_rates[i]);
590                         }
591                 }
592
593                 ast_debug(1, " Bridge changed from %d To %d\n", softmix_data->internal_rate, best_rate);
594                 softmix_data->internal_rate = best_rate;
595                 return 1;
596         } else if (!stats->num_at_internal_rate && !stats->num_above_internal_rate) {
597                 /* In this case, the highest supported rate is actually lower than the internal rate */
598                 softmix_data->internal_rate = stats->highest_supported_rate;
599                 ast_debug(1, " Bridge changed from %d to %d\n", softmix_data->internal_rate, stats->highest_supported_rate);
600                 return 1;
601         }
602         return 0;
603 }
604
605 static int softmix_mixing_array_init(struct softmix_mixing_array *mixing_array, unsigned int starting_num_entries)
606 {
607         memset(mixing_array, 0, sizeof(*mixing_array));
608         mixing_array->max_num_entries = starting_num_entries;
609         if (!(mixing_array->buffers = ast_calloc(mixing_array->max_num_entries, sizeof(int16_t *)))) {
610                 ast_log(LOG_NOTICE, "Failed to allocate softmix mixing structure. \n");
611                 return -1;
612         }
613         return 0;
614 }
615
616 static void softmix_mixing_array_destroy(struct softmix_mixing_array *mixing_array)
617 {
618         ast_free(mixing_array->buffers);
619 }
620
621 static int softmix_mixing_array_grow(struct softmix_mixing_array *mixing_array, unsigned int num_entries)
622 {
623         int16_t **tmp;
624         /* give it some room to grow since memory is cheap but allocations can be expensive */
625         mixing_array->max_num_entries = num_entries;
626         if (!(tmp = ast_realloc(mixing_array->buffers, (mixing_array->max_num_entries * sizeof(int16_t *))))) {
627                 ast_log(LOG_NOTICE, "Failed to re-allocate softmix mixing structure. \n");
628                 return -1;
629         }
630         mixing_array->buffers = tmp;
631         return 0;
632 }
633
634 /*! \brief Function which acts as the mixing thread */
635 static int softmix_bridge_thread(struct ast_bridge *bridge)
636 {
637         struct softmix_stats stats = { { 0 }, };
638         struct softmix_mixing_array mixing_array;
639         struct softmix_bridge_data *softmix_data = bridge->bridge_pvt;
640         struct ast_timer *timer;
641         struct softmix_translate_helper trans_helper;
642         int16_t buf[MAX_DATALEN] = { 0, };
643         unsigned int stat_iteration_counter = 0; /* counts down, gather stats at zero and reset. */
644         int timingfd;
645         int update_all_rates = 0; /* set this when the internal sample rate has changed */
646         int i, x;
647         int res = -1;
648
649         if (!(softmix_data = bridge->bridge_pvt)) {
650                 goto softmix_cleanup;
651         }
652
653         ao2_ref(softmix_data, 1);
654         timer = softmix_data->timer;
655         timingfd = ast_timer_fd(timer);
656         softmix_translate_helper_init(&trans_helper, softmix_data->internal_rate);
657         ast_timer_set_rate(timer, (1000 / softmix_data->internal_mixing_interval));
658
659         /* Give the mixing array room to grow, memory is cheap but allocations are expensive. */
660         if (softmix_mixing_array_init(&mixing_array, bridge->num + 10)) {
661                 ast_log(LOG_NOTICE, "Failed to allocate softmix mixing structure. \n");
662                 goto softmix_cleanup;
663         }
664
665         while (!bridge->stop && !bridge->refresh && bridge->array_num) {
666                 struct ast_bridge_channel *bridge_channel = NULL;
667                 int timeout = -1;
668                 enum ast_format_id cur_slin_id = ast_format_slin_by_rate(softmix_data->internal_rate);
669                 unsigned int softmix_samples = SOFTMIX_SAMPLES(softmix_data->internal_rate, softmix_data->internal_mixing_interval);
670                 unsigned int softmix_datalen = SOFTMIX_DATALEN(softmix_data->internal_rate, softmix_data->internal_mixing_interval);
671
672                 if (softmix_datalen > MAX_DATALEN) {
673                         /* This should NEVER happen, but if it does we need to know about it. Almost
674                          * all the memcpys used during this process depend on this assumption.  Rather
675                          * than checking this over and over again through out the code, this single
676                          * verification is done on each iteration. */
677                         ast_log(LOG_WARNING, "Conference mixing error, requested mixing length greater than mixing buffer.\n");
678                         goto softmix_cleanup;
679                 }
680
681                 /* Grow the mixing array buffer as participants are added. */
682                 if (mixing_array.max_num_entries < bridge->num && softmix_mixing_array_grow(&mixing_array, bridge->num + 5)) {
683                         goto softmix_cleanup;
684                 }
685
686                 /* init the number of buffers stored in the mixing array to 0.
687                  * As buffers are added for mixing, this number is incremented. */
688                 mixing_array.used_entries = 0;
689
690                 /* These variables help determine if a rate change is required */
691                 if (!stat_iteration_counter) {
692                         memset(&stats, 0, sizeof(stats));
693                         stats.locked_rate = bridge->internal_sample_rate;
694                 }
695
696                 /* If the sample rate has changed, update the translator helper */
697                 if (update_all_rates) {
698                         softmix_translate_helper_change_rate(&trans_helper, softmix_data->internal_rate);
699                 }
700
701                 /* Go through pulling audio from each factory that has it available */
702                 AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
703                         struct softmix_channel *sc = bridge_channel->bridge_pvt;
704
705                         /* Update the sample rate to match the bridge's native sample rate if necessary. */
706                         if (update_all_rates) {
707                                 set_softmix_bridge_data(softmix_data->internal_rate, softmix_data->internal_mixing_interval, bridge_channel, 1);
708                         }
709
710                         /* If stat_iteration_counter is 0, then collect statistics during this mixing interation */
711                         if (!stat_iteration_counter) {
712                                 gather_softmix_stats(&stats, softmix_data, bridge_channel);
713                         }
714
715                         /* if the channel is suspended, don't check for audio, but still gather stats */
716                         if (bridge_channel->suspended) {
717                                 continue;
718                         }
719
720                         /* Try to get audio from the factory if available */
721                         ast_mutex_lock(&sc->lock);
722                         if ((mixing_array.buffers[mixing_array.used_entries] = softmix_process_read_audio(sc, softmix_samples))) {
723                                 mixing_array.used_entries++;
724                         }
725                         ast_mutex_unlock(&sc->lock);
726                 }
727
728                 /* mix it like crazy */
729                 memset(buf, 0, softmix_datalen);
730                 for (i = 0; i < mixing_array.used_entries; i++) {
731                         for (x = 0; x < softmix_samples; x++) {
732                                 ast_slinear_saturated_add(buf + x, mixing_array.buffers[i] + x);
733                         }
734                 }
735
736                 /* Next step go through removing the channel's own audio and creating a good frame... */
737                 AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
738                         struct softmix_channel *sc = bridge_channel->bridge_pvt;
739
740                         if (bridge_channel->suspended) {
741                                 continue;
742                         }
743
744                         ast_mutex_lock(&sc->lock);
745
746                         /* Make SLINEAR write frame from local buffer */
747                         if (sc->write_frame.subclass.format.id != cur_slin_id) {
748                                 ast_format_set(&sc->write_frame.subclass.format, cur_slin_id, 0);
749                         }
750                         sc->write_frame.datalen = softmix_datalen;
751                         sc->write_frame.samples = softmix_samples;
752                         memcpy(sc->final_buf, buf, softmix_datalen);
753
754                         /* process the softmix channel's new write audio */
755                         softmix_process_write_audio(&trans_helper, &bridge_channel->chan->rawwriteformat, sc);
756
757                         /* The frame is now ready for use... */
758                         sc->have_frame = 1;
759
760                         ast_mutex_unlock(&sc->lock);
761
762                         /* Poke bridged channel thread just in case */
763                         pthread_kill(bridge_channel->thread, SIGURG);
764                 }
765
766                 update_all_rates = 0;
767                 if (!stat_iteration_counter) {
768                         update_all_rates = analyse_softmix_stats(&stats, softmix_data);
769                         stat_iteration_counter = SOFTMIX_STAT_INTERVAL;
770                 }
771                 stat_iteration_counter--;
772
773                 ao2_unlock(bridge);
774                 /* cleanup any translation frame data from the previous mixing iteration. */
775                 softmix_translate_helper_cleanup(&trans_helper);
776                 /* Wait for the timing source to tell us to wake up and get things done */
777                 ast_waitfor_n_fd(&timingfd, 1, &timeout, NULL);
778                 ast_timer_ack(timer, 1);
779                 ao2_lock(bridge);
780
781                 /* make sure to detect mixing interval changes if they occur. */
782                 if (bridge->internal_mixing_interval && (bridge->internal_mixing_interval != softmix_data->internal_mixing_interval)) {
783                         softmix_data->internal_mixing_interval = bridge->internal_mixing_interval;
784                         ast_timer_set_rate(timer, (1000 / softmix_data->internal_mixing_interval));
785                         update_all_rates = 1; /* if the interval changes, the rates must be adjusted as well just to be notified new interval.*/
786                 }
787         }
788
789         res = 0;
790
791 softmix_cleanup:
792         softmix_translate_helper_destroy(&trans_helper);
793         softmix_mixing_array_destroy(&mixing_array);
794         if (softmix_data) {
795                 ao2_ref(softmix_data, -1);
796         }
797         return res;
798 }
799
800 static struct ast_bridge_technology softmix_bridge = {
801         .name = "softmix",
802         .capabilities = AST_BRIDGE_CAPABILITY_MULTIMIX | AST_BRIDGE_CAPABILITY_THREAD | AST_BRIDGE_CAPABILITY_MULTITHREADED | AST_BRIDGE_CAPABILITY_OPTIMIZE,
803         .preference = AST_BRIDGE_PREFERENCE_LOW,
804         .create = softmix_bridge_create,
805         .destroy = softmix_bridge_destroy,
806         .join = softmix_bridge_join,
807         .leave = softmix_bridge_leave,
808         .write = softmix_bridge_write,
809         .thread = softmix_bridge_thread,
810         .poke = softmix_bridge_poke,
811 };
812
813 static int unload_module(void)
814 {
815         ast_format_cap_destroy(softmix_bridge.format_capabilities);
816         return ast_bridge_technology_unregister(&softmix_bridge);
817 }
818
819 static int load_module(void)
820 {
821         struct ast_format tmp;
822         if (!(softmix_bridge.format_capabilities = ast_format_cap_alloc())) {
823                 return AST_MODULE_LOAD_DECLINE;
824         }
825         ast_format_cap_add(softmix_bridge.format_capabilities, ast_format_set(&tmp, AST_FORMAT_SLINEAR, 0));
826         return ast_bridge_technology_register(&softmix_bridge);
827 }
828
829 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Multi-party software based channel mixing");