func_jitterbuffer.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2011, Digium, Inc.
  5. *
  6. * David Vossel <dvossel@digium.com>
  7. *
  8. * See http://www.asterisk.org for more information about
  9. * the Asterisk project. Please do not directly contact
  10. * any of the maintainers of this project for assistance;
  11. * the project provides a web site, mailing lists and IRC
  12. * channels for your use.
  13. *
  14. * This program is free software, distributed under the terms of
  15. * the GNU General Public License Version 2. See the LICENSE file
  16. * at the top of the source tree.
  17. */
  18. /*! \file
  19. *
  20. * \brief Put a jitterbuffer on the read side of a channel
  21. *
  22. * \author David Vossel <dvossel@digium.com>
  23. *
  24. * \ingroup functions
  25. */
  26. #include "asterisk.h"
  27. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  28. #include "asterisk/module.h"
  29. #include "asterisk/channel.h"
  30. #include "asterisk/framehook.h"
  31. #include "asterisk/pbx.h"
  32. #include "asterisk/abstract_jb.h"
  33. #include "asterisk/timing.h"
  34. #include "asterisk/app.h"
  35. /*** DOCUMENTATION
  36. <function name="JITTERBUFFER" language="en_US">
  37. <synopsis>
  38. Add a Jitterbuffer to the Read side of the channel. This dejitters the audio stream before it reaches the Asterisk core. This is a write only function.
  39. </synopsis>
  40. <syntax>
  41. <parameter name="jitterbuffer type" required="true">
  42. <para>Jitterbuffer type can be either <literal>fixed</literal> or <literal>adaptive</literal>.</para>
  43. <para>Used as follows. </para>
  44. <para>Set(JITTERBUFFER(type)=max_size[,resync_threshold[,target_extra]])</para>
  45. <para>Set(JITTERBUFFER(type)=default) </para>
  46. </parameter>
  47. </syntax>
  48. <description>
  49. <para>max_size: Defaults to 200 ms</para>
  50. <para>Length in milliseconds of buffer.</para>
  51. <para> </para>
  52. <para>resync_threshold: Defaults to 1000ms </para>
  53. <para>The length in milliseconds over which a timestamp difference will result in resyncing the jitterbuffer. </para>
  54. <para> </para>
  55. <para>target_extra: Defaults to 40ms</para>
  56. <para>This option only affects the adaptive jitterbuffer. It represents the amount time in milliseconds by which the new jitter buffer will pad its size.</para>
  57. <para> </para>
  58. <para>Examples:</para>
  59. <para>exten => 1,1,Set(JITTERBUFFER(fixed)=default);Fixed with defaults. </para>
  60. <para>exten => 1,1,Set(JITTERBUFFER(fixed)=200);Fixed with max size 200ms, default resync threshold and target extra. </para>
  61. <para>exten => 1,1,Set(JITTERBUFFER(fixed)=200,1500);Fixed with max size 200ms resync threshold 1500. </para>
  62. <para>exten => 1,1,Set(JITTERBUFFER(adaptive)=default);Adaptive with defaults. </para>
  63. <para>exten => 1,1,Set(JITTERBUFFER(adaptive)=200,,60);Adaptive with max size 200ms, default resync threshold and 40ms target extra. </para>
  64. </description>
  65. </function>
  66. ***/
  67. #define DEFAULT_TIMER_INTERVAL 20
  68. #define DEFAULT_SIZE 200
  69. #define DEFAULT_TARGET_EXTRA 40
  70. #define DEFAULT_RESYNC 1000
  71. #define DEFAULT_TYPE AST_JB_FIXED
  72. struct jb_framedata {
  73. const struct ast_jb_impl *jb_impl;
  74. struct ast_jb_conf jb_conf;
  75. struct timeval start_tv;
  76. struct ast_format last_format;
  77. struct ast_timer *timer;
  78. int timer_interval; /* ms between deliveries */
  79. int timer_fd;
  80. int first;
  81. void *jb_obj;
  82. };
  83. static void jb_framedata_destroy(struct jb_framedata *framedata)
  84. {
  85. if (framedata->timer) {
  86. ast_timer_close(framedata->timer);
  87. framedata->timer = NULL;
  88. }
  89. if (framedata->jb_impl && framedata->jb_obj) {
  90. struct ast_frame *f;
  91. while (framedata->jb_impl->remove(framedata->jb_obj, &f) == AST_JB_IMPL_OK) {
  92. ast_frfree(f);
  93. }
  94. framedata->jb_impl->destroy(framedata->jb_obj);
  95. framedata->jb_obj = NULL;
  96. }
  97. ast_free(framedata);
  98. }
  99. static void jb_conf_default(struct ast_jb_conf *conf)
  100. {
  101. conf->max_size = DEFAULT_SIZE;
  102. conf->resync_threshold = DEFAULT_RESYNC;
  103. ast_copy_string(conf->impl, "fixed", sizeof(conf->impl));
  104. conf->target_extra = DEFAULT_TARGET_EXTRA;
  105. }
  106. /* set defaults */
  107. static int jb_framedata_init(struct jb_framedata *framedata, const char *data, const char *value)
  108. {
  109. int jb_impl_type = DEFAULT_TYPE;
  110. /* Initialize defaults */
  111. framedata->timer_fd = -1;
  112. jb_conf_default(&framedata->jb_conf);
  113. if (!(framedata->jb_impl = ast_jb_get_impl(jb_impl_type))) {
  114. return -1;
  115. }
  116. if (!(framedata->timer = ast_timer_open())) {
  117. return -1;
  118. }
  119. framedata->timer_fd = ast_timer_fd(framedata->timer);
  120. framedata->timer_interval = DEFAULT_TIMER_INTERVAL;
  121. ast_timer_set_rate(framedata->timer, 1000 / framedata->timer_interval);
  122. framedata->start_tv = ast_tvnow();
  123. /* Now check user options to see if any of the defaults need to change. */
  124. if (!ast_strlen_zero(data)) {
  125. if (!strcasecmp(data, "fixed")) {
  126. jb_impl_type = AST_JB_FIXED;
  127. } else if (!strcasecmp(data, "adaptive")) {
  128. jb_impl_type = AST_JB_ADAPTIVE;
  129. } else {
  130. ast_log(LOG_WARNING, "Unknown Jitterbuffer type %s. Failed to create jitterbuffer.\n", data);
  131. return -1;
  132. }
  133. ast_copy_string(framedata->jb_conf.impl, data, sizeof(framedata->jb_conf.impl));
  134. }
  135. if (!ast_strlen_zero(value) && strcasecmp(value, "default")) {
  136. char *parse = ast_strdupa(value);
  137. int res = 0;
  138. AST_DECLARE_APP_ARGS(args,
  139. AST_APP_ARG(max_size);
  140. AST_APP_ARG(resync_threshold);
  141. AST_APP_ARG(target_extra);
  142. );
  143. AST_STANDARD_APP_ARGS(args, parse);
  144. if (!ast_strlen_zero(args.max_size)) {
  145. res |= ast_jb_read_conf(&framedata->jb_conf,
  146. "jbmaxsize",
  147. args.max_size);
  148. }
  149. if (!ast_strlen_zero(args.resync_threshold)) {
  150. res |= ast_jb_read_conf(&framedata->jb_conf,
  151. "jbresyncthreshold",
  152. args.resync_threshold);
  153. }
  154. if (!ast_strlen_zero(args.target_extra)) {
  155. res |= ast_jb_read_conf(&framedata->jb_conf,
  156. "jbtargetextra",
  157. args.target_extra);
  158. }
  159. if (res) {
  160. ast_log(LOG_WARNING, "Invalid jitterbuffer parameters %s\n", value);
  161. }
  162. }
  163. /* now that all the user parsing is done and nothing will change, create the jb obj */
  164. framedata->jb_obj = framedata->jb_impl->create(&framedata->jb_conf, framedata->jb_conf.resync_threshold);
  165. return 0;
  166. }
  167. static void datastore_destroy_cb(void *data) {
  168. ast_free(data);
  169. ast_debug(1, "JITTERBUFFER datastore destroyed\n");
  170. }
  171. static const struct ast_datastore_info jb_datastore = {
  172. .type = "jitterbuffer",
  173. .destroy = datastore_destroy_cb
  174. };
  175. static void hook_destroy_cb(void *framedata)
  176. {
  177. ast_debug(1, "JITTERBUFFER hook destroyed\n");
  178. jb_framedata_destroy((struct jb_framedata *) framedata);
  179. }
  180. static struct ast_frame *hook_event_cb(struct ast_channel *chan, struct ast_frame *frame, enum ast_framehook_event event, void *data)
  181. {
  182. struct jb_framedata *framedata = data;
  183. struct timeval now_tv;
  184. unsigned long now;
  185. int putframe = 0; /* signifies if audio frame was placed into the buffer or not */
  186. switch (event) {
  187. case AST_FRAMEHOOK_EVENT_READ:
  188. break;
  189. case AST_FRAMEHOOK_EVENT_ATTACHED:
  190. case AST_FRAMEHOOK_EVENT_DETACHED:
  191. case AST_FRAMEHOOK_EVENT_WRITE:
  192. return frame;
  193. }
  194. if (chan->fdno == AST_JITTERBUFFER_FD && framedata->timer) {
  195. ast_timer_ack(framedata->timer, 1);
  196. }
  197. if (!frame) {
  198. return frame;
  199. }
  200. now_tv = ast_tvnow();
  201. now = ast_tvdiff_ms(now_tv, framedata->start_tv);
  202. if (frame->frametype == AST_FRAME_VOICE) {
  203. int res;
  204. struct ast_frame *jbframe;
  205. if (!ast_test_flag(frame, AST_FRFLAG_HAS_TIMING_INFO) || frame->len < 2 || frame->ts < 0) {
  206. /* only frames with timing info can enter the jitterbuffer */
  207. return frame;
  208. }
  209. jbframe = ast_frisolate(frame);
  210. ast_format_copy(&framedata->last_format, &frame->subclass.format);
  211. if (frame->len && (frame->len != framedata->timer_interval)) {
  212. framedata->timer_interval = frame->len;
  213. ast_timer_set_rate(framedata->timer, 1000 / framedata->timer_interval);
  214. }
  215. if (!framedata->first) {
  216. framedata->first = 1;
  217. res = framedata->jb_impl->put_first(framedata->jb_obj, jbframe, now);
  218. } else {
  219. res = framedata->jb_impl->put(framedata->jb_obj, jbframe, now);
  220. }
  221. if (res == AST_JB_IMPL_OK) {
  222. frame = &ast_null_frame;
  223. }
  224. putframe = 1;
  225. }
  226. if (frame->frametype == AST_FRAME_NULL) {
  227. int res;
  228. long next = framedata->jb_impl->next(framedata->jb_obj);
  229. /* If now is earlier than the next expected output frame
  230. * from the jitterbuffer we may choose to pass on retrieving
  231. * a frame during this read iteration. The only exception
  232. * to this rule is when an audio frame is placed into the buffer
  233. * and the time for the next frame to come out of the buffer is
  234. * at least within the timer_interval of the next output frame. By
  235. * doing this we are able to feed off the timing of the input frames
  236. * and only rely on our jitterbuffer timer when frames are dropped.
  237. * During testing, this hybrid form of timing gave more reliable results. */
  238. if (now < next) {
  239. long int diff = next - now;
  240. if (!putframe) {
  241. return frame;
  242. } else if (diff >= framedata->timer_interval) {
  243. return frame;
  244. }
  245. }
  246. res = framedata->jb_impl->get(framedata->jb_obj, &frame, now, framedata->timer_interval);
  247. switch (res) {
  248. case AST_JB_IMPL_OK:
  249. /* got it, and pass it through */
  250. break;
  251. case AST_JB_IMPL_DROP:
  252. ast_frfree(frame);
  253. frame = &ast_null_frame;
  254. break;
  255. case AST_JB_IMPL_INTERP:
  256. if (framedata->last_format.id) {
  257. struct ast_frame tmp = { 0, };
  258. tmp.frametype = AST_FRAME_VOICE;
  259. ast_format_copy(&tmp.subclass.format, &framedata->last_format);
  260. /* example: 8000hz / (1000 / 20ms) = 160 samples */
  261. tmp.samples = ast_format_rate(&framedata->last_format) / (1000 / framedata->timer_interval);
  262. tmp.delivery = ast_tvadd(framedata->start_tv, ast_samp2tv(next, 1000));
  263. tmp.offset = AST_FRIENDLY_OFFSET;
  264. tmp.src = "func_jitterbuffer interpolation";
  265. frame = ast_frdup(&tmp);
  266. break;
  267. }
  268. /* else fall through */
  269. case AST_JB_IMPL_NOFRAME:
  270. frame = &ast_null_frame;
  271. break;
  272. }
  273. }
  274. return frame;
  275. }
  276. static int jb_helper(struct ast_channel *chan, const char *cmd, char *data, const char *value)
  277. {
  278. struct jb_framedata *framedata;
  279. struct ast_datastore *datastore = NULL;
  280. struct ast_framehook_interface interface = {
  281. .version = AST_FRAMEHOOK_INTERFACE_VERSION,
  282. .event_cb = hook_event_cb,
  283. .destroy_cb = hook_destroy_cb,
  284. };
  285. int i = 0;
  286. if (!(framedata = ast_calloc(1, sizeof(*framedata)))) {
  287. return 0;
  288. }
  289. if (jb_framedata_init(framedata, data, value)) {
  290. jb_framedata_destroy(framedata);
  291. return 0;
  292. }
  293. interface.data = framedata;
  294. ast_channel_lock(chan);
  295. i = ast_framehook_attach(chan, &interface);
  296. if (i >= 0) {
  297. int *id;
  298. if ((datastore = ast_channel_datastore_find(chan, &jb_datastore, NULL))) {
  299. id = datastore->data;
  300. ast_framehook_detach(chan, *id);
  301. ast_channel_datastore_remove(chan, datastore);
  302. }
  303. if (!(datastore = ast_datastore_alloc(&jb_datastore, NULL))) {
  304. ast_framehook_detach(chan, i);
  305. ast_channel_unlock(chan);
  306. return 0;
  307. }
  308. if (!(id = ast_calloc(1, sizeof(int)))) {
  309. ast_datastore_free(datastore);
  310. ast_framehook_detach(chan, i);
  311. ast_channel_unlock(chan);
  312. return 0;
  313. }
  314. *id = i; /* Store off the id. The channel is still locked so it is safe to access this ptr. */
  315. datastore->data = id;
  316. ast_channel_datastore_add(chan, datastore);
  317. ast_channel_set_fd(chan, AST_JITTERBUFFER_FD, framedata->timer_fd);
  318. } else {
  319. jb_framedata_destroy(framedata);
  320. framedata = NULL;
  321. }
  322. ast_channel_unlock(chan);
  323. return 0;
  324. }
  325. static struct ast_custom_function jb_function = {
  326. .name = "JITTERBUFFER",
  327. .write = jb_helper,
  328. };
  329. static int unload_module(void)
  330. {
  331. return ast_custom_function_unregister(&jb_function);
  332. }
  333. static int load_module(void)
  334. {
  335. int res = ast_custom_function_register(&jb_function);
  336. return res ? AST_MODULE_LOAD_DECLINE : AST_MODULE_LOAD_SUCCESS;
  337. }
  338. AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Jitter buffer for read side of channel.");