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