e2ab2135f3eb9d600e463d4d1bd60cbc240faad2
[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 /*** MODULEINFO
31         <support_level>core</support_level>
32  ***/
33
34 #include "asterisk.h"
35
36 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
37
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <sys/time.h>
42 #include <signal.h>
43 #include <errno.h>
44 #include <unistd.h>
45
46 #include "asterisk/module.h"
47 #include "asterisk/channel.h"
48 #include "asterisk/bridge.h"
49 #include "asterisk/bridge_technology.h"
50 #include "asterisk/frame.h"
51 #include "asterisk/options.h"
52 #include "asterisk/logger.h"
53 #include "asterisk/slinfactory.h"
54 #include "asterisk/astobj2.h"
55 #include "asterisk/timing.h"
56 #include "asterisk/translate.h"
57
58 #define MAX_DATALEN 8096
59
60 /*! \brief Interval at which mixing will take place. Valid options are 10, 20, and 40. */
61 #define DEFAULT_SOFTMIX_INTERVAL 20
62
63 /*! \brief Size of the buffer used for sample manipulation */
64 #define SOFTMIX_DATALEN(rate, interval) ((rate/50) * (interval / 10))
65
66 /*! \brief Number of samples we are dealing with */
67 #define SOFTMIX_SAMPLES(rate, interval) (SOFTMIX_DATALEN(rate, interval) / 2)
68
69 /*! \brief Number of mixing iterations to perform between gathering statistics. */
70 #define SOFTMIX_STAT_INTERVAL 100
71
72 /* This is the threshold in ms at which a channel's own audio will stop getting
73  * mixed out its own write audio stream because it is not talking. */
74 #define DEFAULT_SOFTMIX_SILENCE_THRESHOLD 2500
75 #define DEFAULT_SOFTMIX_TALKING_THRESHOLD 160
76
77 #define DEFAULT_ENERGY_HISTORY_LEN 150
78
79 struct video_follow_talker_data {
80         /*! audio energy history */
81         int energy_history[DEFAULT_ENERGY_HISTORY_LEN];
82         /*! The current slot being used in the history buffer, this
83          *  increments and wraps around */
84         int energy_history_cur_slot;
85         /*! The current energy sum used for averages. */
86         int energy_accum;
87         /*! The current energy average */
88         int energy_average;
89 };
90
91 /*! \brief Structure which contains per-channel mixing information */
92 struct softmix_channel {
93         /*! Lock to protect this structure */
94         ast_mutex_t lock;
95         /*! Factory which contains audio read in from the channel */
96         struct ast_slinfactory factory;
97         /*! Frame that contains mixed audio to be written out to the channel */
98         struct ast_frame write_frame;
99         /*! Frame that contains mixed audio read from the channel */
100         struct ast_frame read_frame;
101         /*! DSP for detecting silence */
102         struct ast_dsp *dsp;
103         /*!
104          * \brief TRUE if a channel is talking.
105          *
106          * \note This affects how the channel's audio is mixed back to
107          * it.
108          */
109         unsigned int talking:1;
110         /*! TRUE if the channel provided audio for this mixing interval */
111         unsigned int have_audio:1;
112         /*! Buffer containing final mixed audio from all sources */
113         short final_buf[MAX_DATALEN];
114         /*! Buffer containing only the audio from the channel */
115         short our_buf[MAX_DATALEN];
116         /*! Data pertaining to talker mode for video conferencing */
117         struct video_follow_talker_data video_talker;
118 };
119
120 struct softmix_bridge_data {
121         struct ast_timer *timer;
122         /*!
123          * \brief Bridge pointer passed to the softmix mixing thread.
124          *
125          * \note Does not need a reference because the bridge will
126          * always exist while the mixing thread exists even if the
127          * bridge is no longer actively using the softmix technology.
128          */
129         struct ast_bridge *bridge;
130         /*! Lock for signaling the mixing thread. */
131         ast_mutex_t lock;
132         /*! Condition, used if we need to wake up the mixing thread. */
133         ast_cond_t cond;
134         /*! Thread handling the mixing */
135         pthread_t thread;
136         unsigned int internal_rate;
137         unsigned int internal_mixing_interval;
138         /*! TRUE if the mixing thread should stop */
139         unsigned int stop:1;
140 };
141
142 struct softmix_stats {
143         /*! Each index represents a sample rate used above the internal rate. */
144         unsigned int sample_rates[16];
145         /*! Each index represents the number of channels using the same index in the sample_rates array.  */
146         unsigned int num_channels[16];
147         /*! the number of channels above the internal sample rate */
148         unsigned int num_above_internal_rate;
149         /*! the number of channels at the internal sample rate */
150         unsigned int num_at_internal_rate;
151         /*! the absolute highest sample rate supported by any channel in the bridge */
152         unsigned int highest_supported_rate;
153         /*! Is the sample rate locked by the bridge, if so what is that rate.*/
154         unsigned int locked_rate;
155 };
156
157 struct softmix_mixing_array {
158         unsigned int max_num_entries;
159         unsigned int used_entries;
160         int16_t **buffers;
161 };
162
163 struct softmix_translate_helper_entry {
164         int num_times_requested; /*!< Once this entry is no longer requested, free the trans_pvt
165                                       and re-init if it was usable. */
166         struct ast_format dst_format; /*!< The destination format for this helper */
167         struct ast_trans_pvt *trans_pvt; /*!< the translator for this slot. */
168         struct ast_frame *out_frame; /*!< The output frame from the last translation */
169         AST_LIST_ENTRY(softmix_translate_helper_entry) entry;
170 };
171
172 struct softmix_translate_helper {
173         struct ast_format slin_src; /*!< the source format expected for all the translators */
174         AST_LIST_HEAD_NOLOCK(, softmix_translate_helper_entry) entries;
175 };
176
177 static struct softmix_translate_helper_entry *softmix_translate_helper_entry_alloc(struct ast_format *dst)
178 {
179         struct softmix_translate_helper_entry *entry;
180         if (!(entry = ast_calloc(1, sizeof(*entry)))) {
181                 return NULL;
182         }
183         ast_format_copy(&entry->dst_format, dst);
184         return entry;
185 }
186
187 static void *softmix_translate_helper_free_entry(struct softmix_translate_helper_entry *entry)
188 {
189         if (entry->trans_pvt) {
190                 ast_translator_free_path(entry->trans_pvt);
191         }
192         if (entry->out_frame) {
193                 ast_frfree(entry->out_frame);
194         }
195         ast_free(entry);
196         return NULL;
197 }
198
199 static void softmix_translate_helper_init(struct softmix_translate_helper *trans_helper, unsigned int sample_rate)
200 {
201         memset(trans_helper, 0, sizeof(*trans_helper));
202         ast_format_set(&trans_helper->slin_src, ast_format_slin_by_rate(sample_rate), 0);
203 }
204
205 static void softmix_translate_helper_destroy(struct softmix_translate_helper *trans_helper)
206 {
207         struct softmix_translate_helper_entry *entry;
208
209         while ((entry = AST_LIST_REMOVE_HEAD(&trans_helper->entries, entry))) {
210                 softmix_translate_helper_free_entry(entry);
211         }
212 }
213
214 static void softmix_translate_helper_change_rate(struct softmix_translate_helper *trans_helper, unsigned int sample_rate)
215 {
216         struct softmix_translate_helper_entry *entry;
217
218         ast_format_set(&trans_helper->slin_src, ast_format_slin_by_rate(sample_rate), 0);
219         AST_LIST_TRAVERSE_SAFE_BEGIN(&trans_helper->entries, entry, entry) {
220                 if (entry->trans_pvt) {
221                         ast_translator_free_path(entry->trans_pvt);
222                         if (!(entry->trans_pvt = ast_translator_build_path(&entry->dst_format, &trans_helper->slin_src))) {
223                                 AST_LIST_REMOVE_CURRENT(entry);
224                                 entry = softmix_translate_helper_free_entry(entry);
225                         }
226                 }
227         }
228         AST_LIST_TRAVERSE_SAFE_END;
229 }
230
231 /*!
232  * \internal
233  * \brief Get the next available audio on the softmix channel's read stream
234  * and determine if it should be mixed out or not on the write stream.
235  *
236  * \retval pointer to buffer containing the exact number of samples requested on success.
237  * \retval NULL if no samples are present
238  */
239 static int16_t *softmix_process_read_audio(struct softmix_channel *sc, unsigned int num_samples)
240 {
241         if ((ast_slinfactory_available(&sc->factory) >= num_samples) &&
242                 ast_slinfactory_read(&sc->factory, sc->our_buf, num_samples)) {
243                 sc->have_audio = 1;
244                 return sc->our_buf;
245         }
246         sc->have_audio = 0;
247         return NULL;
248 }
249
250 /*!
251  * \internal
252  * \brief Process a softmix channel's write audio
253  *
254  * \details This function will remove the channel's talking from its own audio if present and
255  * possibly even do the channel's write translation for it depending on how many other
256  * channels use the same write format.
257  */
258 static void softmix_process_write_audio(struct softmix_translate_helper *trans_helper,
259         struct ast_format *raw_write_fmt,
260         struct softmix_channel *sc)
261 {
262         struct softmix_translate_helper_entry *entry = NULL;
263         int i;
264
265         /* If we provided audio that was not determined to be silence,
266          * then take it out while in slinear format. */
267         if (sc->have_audio && sc->talking) {
268                 for (i = 0; i < sc->write_frame.samples; i++) {
269                         ast_slinear_saturated_subtract(&sc->final_buf[i], &sc->our_buf[i]);
270                 }
271                 /* do not do any special write translate optimization if we had to make
272                  * a special mix for them to remove their own audio. */
273                 return;
274         }
275
276         AST_LIST_TRAVERSE(&trans_helper->entries, entry, entry) {
277                 if (ast_format_cmp(&entry->dst_format, raw_write_fmt) == AST_FORMAT_CMP_EQUAL) {
278                         entry->num_times_requested++;
279                 } else {
280                         continue;
281                 }
282                 if (!entry->trans_pvt && (entry->num_times_requested > 1)) {
283                         entry->trans_pvt = ast_translator_build_path(&entry->dst_format, &trans_helper->slin_src);
284                 }
285                 if (entry->trans_pvt && !entry->out_frame) {
286                         entry->out_frame = ast_translate(entry->trans_pvt, &sc->write_frame, 0);
287                 }
288                 if (entry->out_frame && (entry->out_frame->datalen < MAX_DATALEN)) {
289                         ast_format_copy(&sc->write_frame.subclass.format, &entry->out_frame->subclass.format);
290                         memcpy(sc->final_buf, entry->out_frame->data.ptr, entry->out_frame->datalen);
291                         sc->write_frame.datalen = entry->out_frame->datalen;
292                         sc->write_frame.samples = entry->out_frame->samples;
293                 }
294                 break;
295         }
296
297         /* add new entry into list if this format destination was not matched. */
298         if (!entry && (entry = softmix_translate_helper_entry_alloc(raw_write_fmt))) {
299                 AST_LIST_INSERT_HEAD(&trans_helper->entries, entry, entry);
300         }
301 }
302
303 static void softmix_translate_helper_cleanup(struct softmix_translate_helper *trans_helper)
304 {
305         struct softmix_translate_helper_entry *entry;
306
307         AST_LIST_TRAVERSE(&trans_helper->entries, entry, entry) {
308                 if (entry->out_frame) {
309                         ast_frfree(entry->out_frame);
310                         entry->out_frame = NULL;
311                 }
312                 entry->num_times_requested = 0;
313         }
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->tech_pvt;
319         unsigned int channel_read_rate = ast_format_rate(ast_channel_rawreadformat(bridge_channel->chan));
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 /*!
359  * \internal
360  * \brief Poke the mixing thread in case it is waiting for an active channel.
361  * \since 12.0.0
362  *
363  * \param softmix_data Bridge mixing data.
364  *
365  * \return Nothing
366  */
367 static void softmix_poke_thread(struct softmix_bridge_data *softmix_data)
368 {
369         ast_mutex_lock(&softmix_data->lock);
370         ast_cond_signal(&softmix_data->cond);
371         ast_mutex_unlock(&softmix_data->lock);
372 }
373
374 /*! \brief Function called when a channel is unsuspended from the bridge */
375 static void softmix_bridge_unsuspend(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
376 {
377         if (bridge->tech_pvt) {
378                 softmix_poke_thread(bridge->tech_pvt);
379         }
380 }
381
382 /*!
383  * \internal
384  * \brief Indicate a source change to the channel.
385  * \since 12.0.0
386  *
387  * \param bridge_channel Which channel source is changing.
388  *
389  * \retval 0 on success.
390  * \retval -1 on error.
391  */
392 static int softmix_src_change(struct ast_bridge_channel *bridge_channel)
393 {
394         return ast_bridge_channel_queue_control_data(bridge_channel, AST_CONTROL_SRCCHANGE, NULL, 0);
395 }
396
397 /*! \brief Function called when a channel is joined into the bridge */
398 static int softmix_bridge_join(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
399 {
400         struct softmix_channel *sc;
401         struct softmix_bridge_data *softmix_data;
402
403         softmix_data = bridge->tech_pvt;
404         if (!softmix_data) {
405                 return -1;
406         }
407
408         /* Create a new softmix_channel structure and allocate various things on it */
409         if (!(sc = ast_calloc(1, sizeof(*sc)))) {
410                 return -1;
411         }
412
413         softmix_src_change(bridge_channel);
414
415         /* Can't forget the lock */
416         ast_mutex_init(&sc->lock);
417
418         /* Can't forget to record our pvt structure within the bridged channel structure */
419         bridge_channel->tech_pvt = sc;
420
421         set_softmix_bridge_data(softmix_data->internal_rate,
422                 softmix_data->internal_mixing_interval
423                         ? softmix_data->internal_mixing_interval
424                         : DEFAULT_SOFTMIX_INTERVAL,
425                 bridge_channel, 0);
426
427         softmix_poke_thread(softmix_data);
428         return 0;
429 }
430
431 /*! \brief Function called when a channel leaves the bridge */
432 static void softmix_bridge_leave(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
433 {
434         struct softmix_channel *sc = bridge_channel->tech_pvt;
435
436         if (!sc) {
437                 return;
438         }
439         bridge_channel->tech_pvt = NULL;
440
441         softmix_src_change(bridge_channel);
442
443         /* Drop mutex lock */
444         ast_mutex_destroy(&sc->lock);
445
446         /* Drop the factory */
447         ast_slinfactory_destroy(&sc->factory);
448
449         /* Drop the DSP */
450         ast_dsp_free(sc->dsp);
451
452         /* Eep! drop ourselves */
453         ast_free(sc);
454 }
455
456 static void softmix_pass_video_top_priority(struct ast_bridge *bridge, struct ast_frame *frame)
457 {
458         struct ast_bridge_channel *cur;
459
460         AST_LIST_TRAVERSE(&bridge->channels, cur, entry) {
461                 if (cur->suspended) {
462                         continue;
463                 }
464                 if (ast_bridge_is_video_src(bridge, cur->chan) == 1) {
465                         ast_bridge_channel_queue_frame(cur, frame);
466                         break;
467                 }
468         }
469 }
470
471 /*!
472  * \internal
473  * \brief Determine what to do with a video frame.
474  * \since 12.0.0
475  *
476  * \param bridge Which bridge is getting the frame
477  * \param bridge_channel Which channel is writing the frame.
478  * \param frame What is being written.
479  *
480  * \return Nothing
481  */
482 static void softmix_bridge_write_video(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
483 {
484         struct softmix_channel *sc;
485         int video_src_priority;
486
487         /* Determine if the video frame should be distributed or not */
488         switch (bridge->softmix.video_mode.mode) {
489         case AST_BRIDGE_VIDEO_MODE_NONE:
490                 break;
491         case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
492                 video_src_priority = ast_bridge_is_video_src(bridge, bridge_channel->chan);
493                 if (video_src_priority == 1) {
494                         /* Pass to me and everyone else. */
495                         ast_bridge_queue_everyone_else(bridge, NULL, frame);
496                 }
497                 break;
498         case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
499                 sc = bridge_channel->tech_pvt;
500                 ast_mutex_lock(&sc->lock);
501                 ast_bridge_update_talker_src_video_mode(bridge, bridge_channel->chan,
502                         sc->video_talker.energy_average,
503                         ast_format_get_video_mark(&frame->subclass.format));
504                 ast_mutex_unlock(&sc->lock);
505                 video_src_priority = ast_bridge_is_video_src(bridge, bridge_channel->chan);
506                 if (video_src_priority == 1) {
507                         int num_src = ast_bridge_number_video_src(bridge);
508                         int echo = num_src > 1 ? 0 : 1;
509
510                         ast_bridge_queue_everyone_else(bridge, echo ? NULL : bridge_channel, frame);
511                 } else if (video_src_priority == 2) {
512                         softmix_pass_video_top_priority(bridge, frame);
513                 }
514                 break;
515         }
516 }
517
518 /*!
519  * \internal
520  * \brief Determine what to do with a voice frame.
521  * \since 12.0.0
522  *
523  * \param bridge Which bridge is getting the frame
524  * \param bridge_channel Which channel is writing the frame.
525  * \param frame What is being written.
526  *
527  * \return Nothing
528  */
529 static void softmix_bridge_write_voice(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
530 {
531         struct softmix_channel *sc = bridge_channel->tech_pvt;
532         struct softmix_bridge_data *softmix_data = bridge->tech_pvt;
533         int totalsilence = 0;
534         int cur_energy = 0;
535         int silence_threshold = bridge_channel->tech_args.silence_threshold ?
536                 bridge_channel->tech_args.silence_threshold :
537                 DEFAULT_SOFTMIX_SILENCE_THRESHOLD;
538         char update_talking = -1;  /* if this is set to 0 or 1, tell the bridge that the channel has started or stopped talking. */
539
540         /* Write the frame into the conference */
541         ast_mutex_lock(&sc->lock);
542         ast_dsp_silence_with_energy(sc->dsp, frame, &totalsilence, &cur_energy);
543
544         if (bridge->softmix.video_mode.mode == AST_BRIDGE_VIDEO_MODE_TALKER_SRC) {
545                 int cur_slot = sc->video_talker.energy_history_cur_slot;
546
547                 sc->video_talker.energy_accum -= sc->video_talker.energy_history[cur_slot];
548                 sc->video_talker.energy_accum += cur_energy;
549                 sc->video_talker.energy_history[cur_slot] = cur_energy;
550                 sc->video_talker.energy_average = sc->video_talker.energy_accum / DEFAULT_ENERGY_HISTORY_LEN;
551                 sc->video_talker.energy_history_cur_slot++;
552                 if (sc->video_talker.energy_history_cur_slot == DEFAULT_ENERGY_HISTORY_LEN) {
553                         sc->video_talker.energy_history_cur_slot = 0; /* wrap around */
554                 }
555         }
556
557         if (totalsilence < silence_threshold) {
558                 if (!sc->talking) {
559                         update_talking = 1;
560                 }
561                 sc->talking = 1; /* tell the write process we have audio to be mixed out */
562         } else {
563                 if (sc->talking) {
564                         update_talking = 0;
565                 }
566                 sc->talking = 0;
567         }
568
569         /* Before adding audio in, make sure we haven't fallen behind. If audio has fallen
570          * behind 4 times the amount of samples mixed on every iteration of the mixer, Re-sync
571          * the audio by flushing the buffer before adding new audio in. */
572         if (ast_slinfactory_available(&sc->factory) > (4 * SOFTMIX_SAMPLES(softmix_data->internal_rate, softmix_data->internal_mixing_interval))) {
573                 ast_slinfactory_flush(&sc->factory);
574         }
575
576         /* If a frame was provided add it to the smoother, unless drop silence is enabled and this frame
577          * is not determined to be talking. */
578         if (!(bridge_channel->tech_args.drop_silence && !sc->talking) &&
579                 (frame->frametype == AST_FRAME_VOICE && ast_format_is_slinear(&frame->subclass.format))) {
580                 ast_slinfactory_feed(&sc->factory, frame);
581         }
582
583         /* Alllll done */
584         ast_mutex_unlock(&sc->lock);
585
586         if (update_talking != -1) {
587                 ast_bridge_channel_notify_talking(bridge_channel, update_talking);
588         }
589 }
590
591 /*!
592  * \internal
593  * \brief Determine what to do with a control frame.
594  * \since 12.0.0
595  *
596  * \param bridge Which bridge is getting the frame
597  * \param bridge_channel Which channel is writing the frame.
598  * \param frame What is being written.
599  *
600  * \retval 0 Frame accepted into the bridge.
601  * \retval -1 Frame needs to be deferred.
602  */
603 static int softmix_bridge_write_control(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
604 {
605         /*
606          * XXX Softmix needs to use channel roles to determine what to
607          * do with control frames.
608          */
609         return 0;
610 }
611
612 /*!
613  * \internal
614  * \brief Determine what to do with a frame written into the bridge.
615  * \since 12.0.0
616  *
617  * \param bridge Which bridge is getting the frame
618  * \param bridge_channel Which channel is writing the frame.
619  * \param frame What is being written.
620  *
621  * \retval 0 Frame accepted into the bridge.
622  * \retval -1 Frame needs to be deferred.
623  *
624  * \note On entry, bridge is already locked.
625  */
626 static int softmix_bridge_write(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
627 {
628         int res = 0;
629
630         if (!bridge->tech_pvt || (bridge_channel && !bridge_channel->tech_pvt)) {
631                 /* "Accept" the frame and discard it. */
632                 return 0;
633         }
634
635         /*
636          * XXX Softmix needs to use channel roles to determine who gets
637          * what frame.  Possible roles: announcer, recorder, agent,
638          * supervisor.
639          */
640         switch (frame->frametype) {
641         case AST_FRAME_NULL:
642                 /* "Accept" the frame and discard it. */
643                 break;
644         case AST_FRAME_DTMF_BEGIN:
645         case AST_FRAME_DTMF_END:
646                 res = ast_bridge_queue_everyone_else(bridge, bridge_channel, frame);
647                 break;
648         case AST_FRAME_VOICE:
649                 if (bridge_channel) {
650                         softmix_bridge_write_voice(bridge, bridge_channel, frame);
651                 }
652                 break;
653         case AST_FRAME_VIDEO:
654                 if (bridge_channel) {
655                         softmix_bridge_write_video(bridge, bridge_channel, frame);
656                 }
657                 break;
658         case AST_FRAME_CONTROL:
659                 res = softmix_bridge_write_control(bridge, bridge_channel, frame);
660                 break;
661         case AST_FRAME_BRIDGE_ACTION:
662                 res = ast_bridge_queue_everyone_else(bridge, bridge_channel, frame);
663                 break;
664         case AST_FRAME_BRIDGE_ACTION_SYNC:
665                 ast_log(LOG_ERROR, "Synchronous bridge action written to a softmix bridge.\n");
666                 ast_assert(0);
667         default:
668                 ast_debug(3, "Frame type %d unsupported\n", frame->frametype);
669                 /* "Accept" the frame and discard it. */
670                 break;
671         }
672
673         return res;
674 }
675
676 static void gather_softmix_stats(struct softmix_stats *stats,
677         const struct softmix_bridge_data *softmix_data,
678         struct ast_bridge_channel *bridge_channel)
679 {
680         int channel_native_rate;
681         int i;
682         /* Gather stats about channel sample rates. */
683         channel_native_rate = MAX(ast_format_rate(ast_channel_rawwriteformat(bridge_channel->chan)),
684                 ast_format_rate(ast_channel_rawreadformat(bridge_channel->chan)));
685
686         if (channel_native_rate > stats->highest_supported_rate) {
687                 stats->highest_supported_rate = channel_native_rate;
688         }
689         if (channel_native_rate > softmix_data->internal_rate) {
690                 for (i = 0; i < ARRAY_LEN(stats->sample_rates); i++) {
691                         if (stats->sample_rates[i] == channel_native_rate) {
692                                 stats->num_channels[i]++;
693                                 break;
694                         } else if (!stats->sample_rates[i]) {
695                                 stats->sample_rates[i] = channel_native_rate;
696                                 stats->num_channels[i]++;
697                                 break;
698                         }
699                 }
700                 stats->num_above_internal_rate++;
701         } else if (channel_native_rate == softmix_data->internal_rate) {
702                 stats->num_at_internal_rate++;
703         }
704 }
705 /*!
706  * \internal
707  * \brief Analyse mixing statistics and change bridges internal rate
708  * if necessary.
709  *
710  * \retval 0, no changes to internal rate
711  * \ratval 1, internal rate was changed, update all the channels on the next mixing iteration.
712  */
713 static unsigned int analyse_softmix_stats(struct softmix_stats *stats, struct softmix_bridge_data *softmix_data)
714 {
715         int i;
716         /* Re-adjust the internal bridge sample rate if
717          * 1. The bridge's internal sample rate is locked in at a sample
718          *    rate other than the current sample rate being used.
719          * 2. two or more channels support a higher sample rate
720          * 3. no channels support the current sample rate or a higher rate
721          */
722         if (stats->locked_rate) {
723                 /* if the rate is locked by the bridge, only update it if it differs
724                  * from the current rate we are using. */
725                 if (softmix_data->internal_rate != stats->locked_rate) {
726                         softmix_data->internal_rate = stats->locked_rate;
727                         ast_debug(1, "Bridge is locked in at sample rate %d\n",
728                                 softmix_data->internal_rate);
729                         return 1;
730                 }
731         } else if (stats->num_above_internal_rate >= 2) {
732                 /* the highest rate is just used as a starting point */
733                 unsigned int best_rate = stats->highest_supported_rate;
734                 int best_index = -1;
735
736                 for (i = 0; i < ARRAY_LEN(stats->num_channels); i++) {
737                         if (stats->num_channels[i]) {
738                                 break;
739                         }
740                         /* best_rate starts out being the first sample rate
741                          * greater than the internal sample rate that 2 or
742                          * more channels support. */
743                         if (stats->num_channels[i] >= 2 && (best_index == -1)) {
744                                 best_rate = stats->sample_rates[i];
745                                 best_index = i;
746                         /* If it has been detected that multiple rates above
747                          * the internal rate are present, compare those rates
748                          * to each other and pick the highest one two or more
749                          * channels support. */
750                         } else if (((best_index != -1) &&
751                                 (stats->num_channels[i] >= 2) &&
752                                 (stats->sample_rates[best_index] < stats->sample_rates[i]))) {
753                                 best_rate = stats->sample_rates[i];
754                                 best_index = i;
755                         /* It is possible that multiple channels exist with native sample
756                          * rates above the internal sample rate, but none of those channels
757                          * have the same rate in common.  In this case, the lowest sample
758                          * rate among those channels is picked. Over time as additional
759                          * statistic runs are made the internal sample rate number will
760                          * adjust to the most optimal sample rate, but it may take multiple
761                          * iterations. */
762                         } else if (best_index == -1) {
763                                 best_rate = MIN(best_rate, stats->sample_rates[i]);
764                         }
765                 }
766
767                 ast_debug(1, "Bridge changed from %d To %d\n",
768                         softmix_data->internal_rate, best_rate);
769                 softmix_data->internal_rate = best_rate;
770                 return 1;
771         } else if (!stats->num_at_internal_rate && !stats->num_above_internal_rate) {
772                 /* In this case, the highest supported rate is actually lower than the internal rate */
773                 softmix_data->internal_rate = stats->highest_supported_rate;
774                 ast_debug(1, "Bridge changed from %d to %d\n",
775                         softmix_data->internal_rate, stats->highest_supported_rate);
776                 return 1;
777         }
778         return 0;
779 }
780
781 static int softmix_mixing_array_init(struct softmix_mixing_array *mixing_array, unsigned int starting_num_entries)
782 {
783         memset(mixing_array, 0, sizeof(*mixing_array));
784         mixing_array->max_num_entries = starting_num_entries;
785         if (!(mixing_array->buffers = ast_calloc(mixing_array->max_num_entries, sizeof(int16_t *)))) {
786                 ast_log(LOG_NOTICE, "Failed to allocate softmix mixing structure.\n");
787                 return -1;
788         }
789         return 0;
790 }
791
792 static void softmix_mixing_array_destroy(struct softmix_mixing_array *mixing_array)
793 {
794         ast_free(mixing_array->buffers);
795 }
796
797 static int softmix_mixing_array_grow(struct softmix_mixing_array *mixing_array, unsigned int num_entries)
798 {
799         int16_t **tmp;
800         /* give it some room to grow since memory is cheap but allocations can be expensive */
801         mixing_array->max_num_entries = num_entries;
802         if (!(tmp = ast_realloc(mixing_array->buffers, (mixing_array->max_num_entries * sizeof(int16_t *))))) {
803                 ast_log(LOG_NOTICE, "Failed to re-allocate softmix mixing structure.\n");
804                 return -1;
805         }
806         mixing_array->buffers = tmp;
807         return 0;
808 }
809
810 /*!
811  * \brief Mixing loop.
812  *
813  * \retval 0 on success
814  * \retval -1 on failure
815  */
816 static int softmix_mixing_loop(struct ast_bridge *bridge)
817 {
818         struct softmix_stats stats = { { 0 }, };
819         struct softmix_mixing_array mixing_array;
820         struct softmix_bridge_data *softmix_data = bridge->tech_pvt;
821         struct ast_timer *timer;
822         struct softmix_translate_helper trans_helper;
823         int16_t buf[MAX_DATALEN];
824         unsigned int stat_iteration_counter = 0; /* counts down, gather stats at zero and reset. */
825         int timingfd;
826         int update_all_rates = 0; /* set this when the internal sample rate has changed */
827         unsigned int idx;
828         unsigned int x;
829         int res = -1;
830
831         timer = softmix_data->timer;
832         timingfd = ast_timer_fd(timer);
833         softmix_translate_helper_init(&trans_helper, softmix_data->internal_rate);
834         ast_timer_set_rate(timer, (1000 / softmix_data->internal_mixing_interval));
835
836         /* Give the mixing array room to grow, memory is cheap but allocations are expensive. */
837         if (softmix_mixing_array_init(&mixing_array, bridge->num_channels + 10)) {
838                 goto softmix_cleanup;
839         }
840
841         /*
842          * XXX Softmix needs to use channel roles to determine who gets
843          * what audio mixed.
844          */
845         while (!softmix_data->stop && bridge->num_active) {
846                 struct ast_bridge_channel *bridge_channel;
847                 int timeout = -1;
848                 enum ast_format_id cur_slin_id = ast_format_slin_by_rate(softmix_data->internal_rate);
849                 unsigned int softmix_samples = SOFTMIX_SAMPLES(softmix_data->internal_rate, softmix_data->internal_mixing_interval);
850                 unsigned int softmix_datalen = SOFTMIX_DATALEN(softmix_data->internal_rate, softmix_data->internal_mixing_interval);
851
852                 if (softmix_datalen > MAX_DATALEN) {
853                         /* This should NEVER happen, but if it does we need to know about it. Almost
854                          * all the memcpys used during this process depend on this assumption.  Rather
855                          * than checking this over and over again through out the code, this single
856                          * verification is done on each iteration. */
857                         ast_log(LOG_WARNING,
858                                 "Bridge %s: Conference mixing error, requested mixing length greater than mixing buffer.\n",
859                                 bridge->uniqueid);
860                         goto softmix_cleanup;
861                 }
862
863                 /* Grow the mixing array buffer as participants are added. */
864                 if (mixing_array.max_num_entries < bridge->num_channels
865                         && softmix_mixing_array_grow(&mixing_array, bridge->num_channels + 5)) {
866                         goto softmix_cleanup;
867                 }
868
869                 /* init the number of buffers stored in the mixing array to 0.
870                  * As buffers are added for mixing, this number is incremented. */
871                 mixing_array.used_entries = 0;
872
873                 /* These variables help determine if a rate change is required */
874                 if (!stat_iteration_counter) {
875                         memset(&stats, 0, sizeof(stats));
876                         stats.locked_rate = bridge->softmix.internal_sample_rate;
877                 }
878
879                 /* If the sample rate has changed, update the translator helper */
880                 if (update_all_rates) {
881                         softmix_translate_helper_change_rate(&trans_helper, softmix_data->internal_rate);
882                 }
883
884                 /* Go through pulling audio from each factory that has it available */
885                 AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
886                         struct softmix_channel *sc = bridge_channel->tech_pvt;
887
888                         /* Update the sample rate to match the bridge's native sample rate if necessary. */
889                         if (update_all_rates) {
890                                 set_softmix_bridge_data(softmix_data->internal_rate, softmix_data->internal_mixing_interval, bridge_channel, 1);
891                         }
892
893                         /* If stat_iteration_counter is 0, then collect statistics during this mixing interation */
894                         if (!stat_iteration_counter) {
895                                 gather_softmix_stats(&stats, softmix_data, bridge_channel);
896                         }
897
898                         /* if the channel is suspended, don't check for audio, but still gather stats */
899                         if (bridge_channel->suspended) {
900                                 continue;
901                         }
902
903                         /* Try to get audio from the factory if available */
904                         ast_mutex_lock(&sc->lock);
905                         if ((mixing_array.buffers[mixing_array.used_entries] = softmix_process_read_audio(sc, softmix_samples))) {
906                                 mixing_array.used_entries++;
907                         }
908                         ast_mutex_unlock(&sc->lock);
909                 }
910
911                 /* mix it like crazy */
912                 memset(buf, 0, softmix_datalen);
913                 for (idx = 0; idx < mixing_array.used_entries; ++idx) {
914                         for (x = 0; x < softmix_samples; ++x) {
915                                 ast_slinear_saturated_add(buf + x, mixing_array.buffers[idx] + x);
916                         }
917                 }
918
919                 /* Next step go through removing the channel's own audio and creating a good frame... */
920                 AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
921                         struct softmix_channel *sc = bridge_channel->tech_pvt;
922
923                         if (bridge_channel->suspended) {
924                                 continue;
925                         }
926
927                         ast_mutex_lock(&sc->lock);
928
929                         /* Make SLINEAR write frame from local buffer */
930                         if (sc->write_frame.subclass.format.id != cur_slin_id) {
931                                 ast_format_set(&sc->write_frame.subclass.format, cur_slin_id, 0);
932                         }
933                         sc->write_frame.datalen = softmix_datalen;
934                         sc->write_frame.samples = softmix_samples;
935                         memcpy(sc->final_buf, buf, softmix_datalen);
936
937                         /* process the softmix channel's new write audio */
938                         softmix_process_write_audio(&trans_helper, ast_channel_rawwriteformat(bridge_channel->chan), sc);
939
940                         ast_mutex_unlock(&sc->lock);
941
942                         /* A frame is now ready for the channel. */
943                         ast_bridge_channel_queue_frame(bridge_channel, &sc->write_frame);
944                 }
945
946                 update_all_rates = 0;
947                 if (!stat_iteration_counter) {
948                         update_all_rates = analyse_softmix_stats(&stats, softmix_data);
949                         stat_iteration_counter = SOFTMIX_STAT_INTERVAL;
950                 }
951                 stat_iteration_counter--;
952
953                 ast_bridge_unlock(bridge);
954                 /* cleanup any translation frame data from the previous mixing iteration. */
955                 softmix_translate_helper_cleanup(&trans_helper);
956                 /* Wait for the timing source to tell us to wake up and get things done */
957                 ast_waitfor_n_fd(&timingfd, 1, &timeout, NULL);
958                 if (ast_timer_ack(timer, 1) < 0) {
959                         ast_log(LOG_ERROR, "Bridge %s: Failed to acknowledge timer in softmix.\n",
960                                 bridge->uniqueid);
961                         ast_bridge_lock(bridge);
962                         goto softmix_cleanup;
963                 }
964                 ast_bridge_lock(bridge);
965
966                 /* make sure to detect mixing interval changes if they occur. */
967                 if (bridge->softmix.internal_mixing_interval
968                         && (bridge->softmix.internal_mixing_interval != softmix_data->internal_mixing_interval)) {
969                         softmix_data->internal_mixing_interval = bridge->softmix.internal_mixing_interval;
970                         ast_timer_set_rate(timer, (1000 / softmix_data->internal_mixing_interval));
971                         update_all_rates = 1; /* if the interval changes, the rates must be adjusted as well just to be notified new interval.*/
972                 }
973         }
974
975         res = 0;
976
977 softmix_cleanup:
978         softmix_translate_helper_destroy(&trans_helper);
979         softmix_mixing_array_destroy(&mixing_array);
980         return res;
981 }
982
983 /*!
984  * \internal
985  * \brief Mixing thread.
986  * \since 12.0.0
987  *
988  * \note The thread does not have its own reference to the
989  * bridge.  The lifetime of the thread is tied to the lifetime
990  * of the mixing technology association with the bridge.
991  */
992 static void *softmix_mixing_thread(void *data)
993 {
994         struct softmix_bridge_data *softmix_data = data;
995         struct ast_bridge *bridge = softmix_data->bridge;
996
997         ast_bridge_lock(bridge);
998         if (bridge->callid) {
999                 ast_callid_threadassoc_add(bridge->callid);
1000         }
1001
1002         ast_debug(1, "Bridge %s: starting mixing thread\n", bridge->uniqueid);
1003
1004         while (!softmix_data->stop) {
1005                 if (!bridge->num_active) {
1006                         /* Wait for something to happen to the bridge. */
1007                         ast_bridge_unlock(bridge);
1008                         ast_mutex_lock(&softmix_data->lock);
1009                         if (!softmix_data->stop) {
1010                                 ast_cond_wait(&softmix_data->cond, &softmix_data->lock);
1011                         }
1012                         ast_mutex_unlock(&softmix_data->lock);
1013                         ast_bridge_lock(bridge);
1014                         continue;
1015                 }
1016
1017                 if (softmix_mixing_loop(bridge)) {
1018                         /*
1019                          * A mixing error occurred.  Sleep and try again later so we
1020                          * won't flood the logs.
1021                          */
1022                         ast_bridge_unlock(bridge);
1023                         sleep(1);
1024                         ast_bridge_lock(bridge);
1025                 }
1026         }
1027
1028         ast_bridge_unlock(bridge);
1029
1030         ast_debug(1, "Bridge %s: stopping mixing thread\n", bridge->uniqueid);
1031
1032         return NULL;
1033 }
1034
1035 static void softmix_bridge_data_destroy(struct softmix_bridge_data *softmix_data)
1036 {
1037         if (softmix_data->timer) {
1038                 ast_timer_close(softmix_data->timer);
1039                 softmix_data->timer = NULL;
1040         }
1041         ast_mutex_destroy(&softmix_data->lock);
1042         ast_cond_destroy(&softmix_data->cond);
1043         ast_free(softmix_data);
1044 }
1045
1046 /*! \brief Function called when a bridge is created */
1047 static int softmix_bridge_create(struct ast_bridge *bridge)
1048 {
1049         struct softmix_bridge_data *softmix_data;
1050
1051         softmix_data = ast_calloc(1, sizeof(*softmix_data));
1052         if (!softmix_data) {
1053                 return -1;
1054         }
1055         softmix_data->bridge = bridge;
1056         ast_mutex_init(&softmix_data->lock);
1057         ast_cond_init(&softmix_data->cond, NULL);
1058         softmix_data->timer = ast_timer_open();
1059         if (!softmix_data->timer) {
1060                 ast_log(AST_LOG_WARNING, "Failed to open timer for softmix bridge\n");
1061                 softmix_bridge_data_destroy(softmix_data);
1062                 return -1;
1063         }
1064         /* start at 8khz, let it grow from there */
1065         softmix_data->internal_rate = 8000;
1066         softmix_data->internal_mixing_interval = DEFAULT_SOFTMIX_INTERVAL;
1067
1068         bridge->tech_pvt = softmix_data;
1069
1070         /* Start the mixing thread. */
1071         if (ast_pthread_create(&softmix_data->thread, NULL, softmix_mixing_thread,
1072                 softmix_data)) {
1073                 softmix_data->thread = AST_PTHREADT_NULL;
1074                 softmix_bridge_data_destroy(softmix_data);
1075                 bridge->tech_pvt = NULL;
1076                 return -1;
1077         }
1078
1079         return 0;
1080 }
1081
1082 /*!
1083  * \internal
1084  * \brief Request the softmix mixing thread stop.
1085  * \since 12.0.0
1086  *
1087  * \param bridge Which bridge is being stopped.
1088  *
1089  * \return Nothing
1090  */
1091 static void softmix_bridge_stop(struct ast_bridge *bridge)
1092 {
1093         struct softmix_bridge_data *softmix_data;
1094
1095         softmix_data = bridge->tech_pvt;
1096         if (!softmix_data) {
1097                 return;
1098         }
1099
1100         ast_mutex_lock(&softmix_data->lock);
1101         softmix_data->stop = 1;
1102         ast_mutex_unlock(&softmix_data->lock);
1103 }
1104
1105 /*! \brief Function called when a bridge is destroyed */
1106 static void softmix_bridge_destroy(struct ast_bridge *bridge)
1107 {
1108         struct softmix_bridge_data *softmix_data;
1109         pthread_t thread;
1110
1111         softmix_data = bridge->tech_pvt;
1112         if (!softmix_data) {
1113                 return;
1114         }
1115
1116         /* Stop the mixing thread. */
1117         ast_mutex_lock(&softmix_data->lock);
1118         softmix_data->stop = 1;
1119         ast_cond_signal(&softmix_data->cond);
1120         thread = softmix_data->thread;
1121         softmix_data->thread = AST_PTHREADT_NULL;
1122         ast_mutex_unlock(&softmix_data->lock);
1123         if (thread != AST_PTHREADT_NULL) {
1124                 ast_debug(1, "Bridge %s: Waiting for mixing thread to die.\n", bridge->uniqueid);
1125                 pthread_join(thread, NULL);
1126         }
1127
1128         softmix_bridge_data_destroy(softmix_data);
1129         bridge->tech_pvt = NULL;
1130 }
1131
1132 static struct ast_bridge_technology softmix_bridge = {
1133         .name = "softmix",
1134         .capabilities = AST_BRIDGE_CAPABILITY_MULTIMIX,
1135         .preference = AST_BRIDGE_PREFERENCE_BASE_MULTIMIX,
1136         .create = softmix_bridge_create,
1137         .stop = softmix_bridge_stop,
1138         .destroy = softmix_bridge_destroy,
1139         .join = softmix_bridge_join,
1140         .leave = softmix_bridge_leave,
1141         .unsuspend = softmix_bridge_unsuspend,
1142         .write = softmix_bridge_write,
1143 };
1144
1145 static int unload_module(void)
1146 {
1147         ast_format_cap_destroy(softmix_bridge.format_capabilities);
1148         return ast_bridge_technology_unregister(&softmix_bridge);
1149 }
1150
1151 static int load_module(void)
1152 {
1153         struct ast_format tmp;
1154         if (!(softmix_bridge.format_capabilities = ast_format_cap_alloc(0))) {
1155                 return AST_MODULE_LOAD_DECLINE;
1156         }
1157         ast_format_cap_add(softmix_bridge.format_capabilities, ast_format_set(&tmp, AST_FORMAT_SLINEAR, 0));
1158         return ast_bridge_technology_register(&softmix_bridge);
1159 }
1160
1161 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Multi-party software based channel mixing");