bridge_softmix.c 32 KB

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