jbuf.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  1. #include "jbuf.h"
  2. #include "jerrno.h"
  3. #include <memory.h>
  4. #include <assert.h>
  5. #ifdef _WIN32
  6. #else
  7. #define max(a,b) (((a) > (b)) ? (a) : (b))
  8. #define min(a,b) (((a) < (b)) ? (a) : (b))
  9. #endif // _WIN32
  10. /* Minimal difference between JB size and 2*burst-level to perform
  11. * JB shrinking.
  12. */
  13. #define SAFE_SHRINKING_DIFF 1
  14. /* Minimal gap (in ms) between JB shrinking */
  15. #define MIN_SHRINK_GAP_MSEC 200
  16. /* Invalid sequence number, used as the initial value. */
  17. #define INVALID_OFFSET -9999
  18. /* Maximum burst length, whenever an operation is bursting longer than
  19. * this value, JB will assume that the opposite operation was idle.
  20. */
  21. #define MAX_BURST_MSEC 1000
  22. /* Number of OP switches to be performed in JB_STATUS_INITIALIZING, before
  23. * JB can switch its states to JB_STATUS_PROCESSING.
  24. */
  25. #define INIT_CYCLE 10
  26. /**
  27. * Calculate integer square root of an integer.
  28. *
  29. * @param i Integer to be calculated.
  30. *
  31. * @return Square root result.
  32. */
  33. static __inline unsigned isqrt(unsigned i)
  34. {
  35. unsigned res = 1, prev;
  36. /* Rough guess, calculate half bit of input */
  37. prev = i >> 2;
  38. while (prev) {
  39. prev >>= 2;
  40. res <<= 1;
  41. }
  42. /* Babilonian method */
  43. do {
  44. prev = res;
  45. res = (prev + i/prev) >> 1;
  46. } while ((prev+res)>>1 != res);
  47. return res;
  48. }
  49. typedef struct math_stat
  50. {
  51. int n; /* number of samples */
  52. int max; /* maximum value */
  53. int min; /* minimum value */
  54. int last; /* last value */
  55. int mean; /* mean */
  56. /* Private members */
  57. float fmean_; /* mean(floating point) */
  58. double m2_; /* variance * n */
  59. } math_stat;
  60. /**
  61. * Initialize statistics state.
  62. *
  63. * @param stat Statistic state.
  64. */
  65. static __inline void math_stat_init(math_stat *stat)
  66. {
  67. memset(stat, 0,sizeof(math_stat));
  68. }
  69. /**
  70. * Update statistics state as a new sample comes.
  71. *
  72. * @param stat Statistic state.
  73. * @param val The new sample data.
  74. */
  75. static __inline void math_stat_update(math_stat *stat, int val)
  76. {
  77. float delta;
  78. stat->last = val;
  79. if (stat->n++) {
  80. if (stat->min > val)
  81. stat->min = val;
  82. if (stat->max < val)
  83. stat->max = val;
  84. } else {
  85. stat->min = stat->max = val;
  86. }
  87. delta = val - stat->fmean_;
  88. stat->fmean_ += delta/stat->n;
  89. /* Return mean value with 'rounding' */
  90. stat->mean = (int) (stat->fmean_ + 0.5);
  91. stat->m2_ += (int)(delta * (val-stat->fmean_));
  92. }
  93. /**
  94. * Get the standard deviation of specified statistics state.
  95. *
  96. * @param stat Statistic state.
  97. *
  98. * @return The standard deviation.
  99. */
  100. static __inline unsigned math_stat_get_stddev(const math_stat *stat)
  101. {
  102. if (stat->n == 0) return 0;
  103. return (isqrt((unsigned)(stat->m2_/stat->n)));
  104. }
  105. /**
  106. * Set the standard deviation of statistics state. This is useful when
  107. * the statistic state is operated in 'read-only' mode as a storage of
  108. * statistical data.
  109. *
  110. * @param stat Statistic state.
  111. *
  112. * @param dev The standard deviation.
  113. */
  114. static __inline void math_stat_set_stddev(math_stat *stat, unsigned dev)
  115. {
  116. if (stat->n == 0)
  117. stat->n = 1;
  118. stat->m2_ = dev*dev*stat->n;
  119. }
  120. /* Struct of JB internal buffer, represented in a circular buffer containing
  121. * frame content, frame type, frame length, and frame bit info.
  122. */
  123. typedef struct jb_framelist_t
  124. {
  125. /* Settings */
  126. unsigned frame_size; /**< maximum size of frame */
  127. unsigned max_count; /**< maximum number of frames */
  128. /* Buffers */
  129. char *content; /**< frame content array */
  130. int *frame_type; /**< frame type array */
  131. size_t *content_len; /**< frame length array */
  132. unsigned *bit_info; /**< frame bit info array */
  133. /* States */
  134. unsigned head; /**< index of head, pointed frame
  135. will be returned by next GET */
  136. unsigned size; /**< current size of framelist,
  137. including discarded frames. */
  138. unsigned discarded_num; /**< current number of discarded
  139. frames. */
  140. int origin; /**< original index of flist_head */
  141. } jb_framelist_t;
  142. struct jitterbuf
  143. {
  144. /* Settings (consts) */
  145. size_t jb_frame_size; /**< frame size */
  146. unsigned jb_frame_ptime; /**< frame duration. */
  147. size_t jb_max_count; /**< capacity of jitter buffer,
  148. in frames */
  149. int jb_init_prefetch; /**< Initial prefetch */
  150. int jb_min_prefetch; /**< Minimum allowable prefetch */
  151. int jb_max_prefetch; /**< Maximum allowable prefetch */
  152. int jb_max_burst; /**< maximum possible burst, whenever
  153. burst exceeds this value, it
  154. won't be included in level
  155. calculation */
  156. int jb_min_shrink_gap; /**< How often can we shrink */
  157. /* Buffer */
  158. jb_framelist_t jb_framelist; /**< the buffer */
  159. /* States */
  160. int jb_level; /**< delay between source &
  161. destination (calculated according
  162. of the number of burst get/put
  163. operations) */
  164. int jb_max_hist_level; /**< max level during the last level
  165. calculations */
  166. int jb_stable_hist; /**< num of times the delay has been
  167. lower then the prefetch num */
  168. int jb_last_op; /**< last operation executed
  169. (put/get) */
  170. int jb_eff_level; /**< effective burst level */
  171. int jb_prefetch; /**< no. of frame to insert before
  172. removing some (at the beginning
  173. of the framelist->content
  174. operation), the value may be
  175. continuously updated based on
  176. current frame burst level. */
  177. int jb_status; /**< status is 'init' until the first
  178. 'put' operation */
  179. int jb_init_cycle_cnt; /**< status is 'init' until the first
  180. 'put' operation */
  181. int jb_last_del_seq; /**< Seq # of last frame deleted */
  182. int jb_last_discard_seq;/**< Seq # of last frame discarded */
  183. /* Statistics */
  184. math_stat jb_delay; /**< Delay statistics of jitter buffer
  185. (in ms) */
  186. math_stat jb_burst; /**< Burst statistics (in frames) */
  187. unsigned jb_lost; /**< Number of lost frames. */
  188. unsigned jb_discard; /**< Number of discarded frames. */
  189. unsigned jb_empty; /**< Number of empty/prefetching frame
  190. returned by GET. */
  191. int jb_seq;
  192. };
  193. #define JB_STATUS_INITIALIZING 0
  194. #define JB_STATUS_PROCESSING 1
  195. #define JB_STATUS_PREFETCHING 2
  196. /* Progressive discard algorithm introduced to reduce JB latency
  197. * by discarding incoming frames with adaptive aggressiveness based on
  198. * actual burst level.
  199. */
  200. #define PROGRESSIVE_DISCARD 0
  201. /* Internal JB frame flag, discarded frame will not be returned by JB to
  202. * application, it's just simply discarded.
  203. */
  204. #define JB_DISCARDED_FRAME 1024
  205. static int jb_framelist_reset(jb_framelist_t *framelist);
  206. static unsigned jb_framelist_remove_head(jb_framelist_t *framelist,
  207. unsigned count);
  208. static int jb_framelist_init(jb_framelist_t *framelist,
  209. unsigned frame_size,
  210. unsigned max_count)
  211. {
  212. memset(framelist, 0, sizeof(jb_framelist_t));
  213. framelist->frame_size = frame_size;
  214. framelist->max_count = max_count;
  215. framelist->content = (char*) malloc(framelist->frame_size*framelist->max_count);
  216. framelist->frame_type = (int*)malloc(sizeof(framelist->frame_type[0])*framelist->max_count);
  217. framelist->content_len = (size_t*)malloc(sizeof(framelist->content_len[0])*framelist->max_count);
  218. framelist->bit_info = (unsigned*)malloc(sizeof(framelist->bit_info[0])*framelist->max_count);
  219. return jb_framelist_reset(framelist);
  220. }
  221. static int jb_framelist_destroy(jb_framelist_t *framelist)
  222. {
  223. free(framelist->content);
  224. free(framelist->frame_type);
  225. free(framelist->content_len);
  226. free(framelist->bit_info);
  227. return 0;
  228. }
  229. static int jb_framelist_reset(jb_framelist_t *framelist)
  230. {
  231. framelist->head = 0;
  232. framelist->origin = INVALID_OFFSET;
  233. framelist->size = 0;
  234. framelist->discarded_num = 0;
  235. memset(framelist->frame_type,
  236. JB_MISSING_FRAME,
  237. sizeof(framelist->frame_type[0]) *
  238. framelist->max_count);
  239. memset(framelist->content_len, 0,
  240. sizeof(framelist->content_len[0]) *
  241. framelist->max_count);
  242. return 0;
  243. }
  244. static unsigned jb_framelist_size(const jb_framelist_t *framelist)
  245. {
  246. return framelist->size;
  247. }
  248. static unsigned jb_framelist_eff_size(const jb_framelist_t *framelist)
  249. {
  250. return (framelist->size - framelist->discarded_num);
  251. }
  252. static int jb_framelist_origin(const jb_framelist_t *framelist)
  253. {
  254. return framelist->origin;
  255. }
  256. static int jb_framelist_get(jb_framelist_t *framelist,
  257. void *frame, size_t *size,
  258. jb_frame_type *p_type,
  259. unsigned *bit_info)
  260. {
  261. if (framelist->size) {
  262. /* Skip discarded frames */
  263. while (framelist->frame_type[framelist->head] == JB_DISCARDED_FRAME)
  264. {
  265. jb_framelist_remove_head(framelist, 1);
  266. }
  267. /* Return the head frame if any */
  268. if (framelist->size) {
  269. memcpy(frame,
  270. framelist->content +
  271. framelist->head * framelist->frame_size,
  272. framelist->frame_size);
  273. *p_type = (jb_frame_type)
  274. framelist->frame_type[framelist->head];
  275. if (size)
  276. *size = framelist->content_len[framelist->head];
  277. if (bit_info)
  278. *bit_info = framelist->bit_info[framelist->head];
  279. framelist->frame_type[framelist->head] = JB_MISSING_FRAME;
  280. framelist->content_len[framelist->head] = 0;
  281. framelist->bit_info[framelist->head] = 0;
  282. framelist->origin++;
  283. framelist->head = (framelist->head + 1) % framelist->max_count;
  284. framelist->size--;
  285. return 1;
  286. }
  287. }
  288. /* No frame available */
  289. memset(frame, 0, framelist->frame_size);
  290. return 0;
  291. }
  292. /* Remove oldest frames as many as param 'count' */
  293. static unsigned jb_framelist_remove_head(jb_framelist_t *framelist,
  294. unsigned count)
  295. {
  296. if (count > framelist->size)
  297. count = framelist->size;
  298. if (count) {
  299. /* may be done in two steps if overlapping */
  300. unsigned step1,step2;
  301. unsigned tmp = framelist->head+count;
  302. unsigned i;
  303. if (tmp > framelist->max_count) {
  304. step1 = framelist->max_count - framelist->head;
  305. step2 = count-step1;
  306. } else {
  307. step1 = count;
  308. step2 = 0;
  309. }
  310. for (i = framelist->head; i < (framelist->head + step1); ++i) {
  311. if (framelist->frame_type[i] == JB_DISCARDED_FRAME) {
  312. assert(framelist->discarded_num > 0);
  313. framelist->discarded_num--;
  314. }
  315. }
  316. memset(framelist->frame_type+framelist->head,
  317. JB_MISSING_FRAME,
  318. step1*sizeof(framelist->frame_type[0]));
  319. memset(framelist->content_len+framelist->head,0,
  320. step1*sizeof(framelist->content_len[0]));
  321. if (step2) {
  322. for (i = 0; i < step2; ++i) {
  323. if (framelist->frame_type[i] == JB_DISCARDED_FRAME) {
  324. assert(framelist->discarded_num > 0);
  325. framelist->discarded_num--;
  326. }
  327. }
  328. memset(framelist->frame_type,JB_MISSING_FRAME,step2*sizeof(framelist->frame_type[0]));
  329. memset(framelist->content_len,0,step2*sizeof(framelist->content_len[0]));
  330. }
  331. /* update states */
  332. framelist->origin += count;
  333. framelist->head = (framelist->head + count) % framelist->max_count;
  334. framelist->size -= count;
  335. }
  336. return count;
  337. }
  338. static int jb_framelist_put_at(jb_framelist_t *framelist,
  339. int index,
  340. const void *frame,
  341. unsigned frame_size,
  342. unsigned bit_info,
  343. unsigned frame_type)
  344. {
  345. int distance;
  346. unsigned pos;
  347. enum { MAX_MISORDER = 100 };
  348. enum { MAX_DROPOUT = 3000 };
  349. assert(frame_size <= framelist->frame_size);
  350. /* too late or sequence restart */
  351. if (index < framelist->origin) {
  352. if (framelist->origin - index < MAX_MISORDER) {
  353. /* too late */
  354. return PJ_ETOOSMALL;
  355. } else {
  356. /* sequence restart */
  357. framelist->origin = index - framelist->size;
  358. }
  359. }
  360. /* if jbuf is empty, just reset the origin */
  361. if (framelist->size == 0) {
  362. assert(framelist->discarded_num == 0);
  363. framelist->origin = index;
  364. }
  365. /* get distance of this frame to the first frame in the buffer */
  366. distance = index - framelist->origin;
  367. /* far jump, the distance is greater than buffer capacity */
  368. if (distance >= (int)framelist->max_count) {
  369. if (distance > MAX_DROPOUT) {
  370. /* jump too far, reset the buffer */
  371. jb_framelist_reset(framelist);
  372. framelist->origin = index;
  373. distance = 0;
  374. } else {
  375. /* otherwise, reject the frame */
  376. return PJ_ETOOMANY;
  377. }
  378. }
  379. /* get the slot position */
  380. pos = (framelist->head + distance) % framelist->max_count;
  381. /* if the slot is occupied, it must be duplicated frame, ignore it. */
  382. if (framelist->frame_type[pos] != JB_MISSING_FRAME)
  383. return PJ_EEXISTS;
  384. /* put the frame into the slot */
  385. framelist->frame_type[pos] = frame_type;
  386. framelist->content_len[pos] = frame_size;
  387. framelist->bit_info[pos] = bit_info;
  388. /* update framelist size */
  389. if (framelist->origin + (int)framelist->size <= index)
  390. framelist->size = distance + 1;
  391. if(JB_NORMAL_FRAME == frame_type) {
  392. /* copy frame content */
  393. memcpy(framelist->content + pos * framelist->frame_size,
  394. frame, frame_size);
  395. return PJ_SUCCESS;
  396. } else {
  397. /* frame is being discarded */
  398. framelist->discarded_num++;
  399. return PJ_EIGNORED;
  400. }
  401. }
  402. enum media_jb_op
  403. {
  404. JB_OP_INIT = -1,
  405. JB_OP_PUT = 1,
  406. JB_OP_GET = 2
  407. };
  408. int jbuf_create(unsigned frame_size, unsigned ptime,unsigned max_count,jitterbuf **p_jb)
  409. {
  410. jitterbuf *jb;
  411. int status;
  412. jb = malloc(sizeof(struct jitterbuf));
  413. status = jb_framelist_init(&jb->jb_framelist, frame_size, max_count);
  414. if (status != 0)
  415. return status;
  416. jb->jb_frame_size = frame_size;
  417. jb->jb_frame_ptime = ptime;
  418. jb->jb_prefetch = min(JB_DEFAULT_INIT_DELAY,max_count*4/5);
  419. jb->jb_min_prefetch = 0;
  420. jb->jb_max_prefetch = max_count*4/5;
  421. jb->jb_max_count = max_count;
  422. jb->jb_min_shrink_gap= MIN_SHRINK_GAP_MSEC / ptime;
  423. jb->jb_max_burst = MAX_BURST_MSEC / ptime;
  424. jb->jb_last_discard_seq = 0;
  425. jb->jb_seq = 0;
  426. math_stat_init(&jb->jb_delay);
  427. math_stat_init(&jb->jb_burst);
  428. jbuf_reset(jb);
  429. *p_jb = jb;
  430. return 0;
  431. }
  432. /*
  433. * Set the jitter buffer to fixed delay mode. The default behavior
  434. * is to adapt the delay with actual packet delay.
  435. *
  436. */
  437. int jbuf_set_fixed( jitterbuf *jb, unsigned prefetch)
  438. {
  439. assert(prefetch <= jb->jb_max_count);
  440. jb->jb_min_prefetch = jb->jb_max_prefetch =
  441. jb->jb_prefetch = jb->jb_init_prefetch = prefetch;
  442. return 0;
  443. }
  444. /*
  445. * Set the jitter buffer to adaptive mode.
  446. */
  447. int jbuf_set_adaptive( jitterbuf *jb,
  448. unsigned prefetch,
  449. unsigned min_prefetch,
  450. unsigned max_prefetch)
  451. {
  452. assert(jb);
  453. assert(min_prefetch < max_prefetch && prefetch <= max_prefetch && max_prefetch <= jb->jb_max_count);
  454. jb->jb_prefetch = jb->jb_init_prefetch = prefetch;
  455. jb->jb_min_prefetch = min_prefetch;
  456. jb->jb_max_prefetch = max_prefetch;
  457. return 0;
  458. }
  459. int jbuf_reset(jitterbuf *jb)
  460. {
  461. jb->jb_level = 0;
  462. jb->jb_last_op = JB_OP_INIT;
  463. jb->jb_stable_hist = 0;
  464. jb->jb_status = JB_STATUS_INITIALIZING;
  465. jb->jb_init_cycle_cnt= 0;
  466. jb->jb_max_hist_level= 0;
  467. jb_framelist_reset(&jb->jb_framelist);
  468. return 0;
  469. }
  470. int jbuf_destroy(jitterbuf *jb)
  471. {
  472. if (!jb)
  473. return -1;
  474. jb_framelist_destroy(&jb->jb_framelist);
  475. free(jb);
  476. return 0;
  477. }
  478. static void jbuf_calculate_jitter(jitterbuf *jb)
  479. {
  480. int diff, cur_size;
  481. cur_size = jb_framelist_eff_size(&jb->jb_framelist);
  482. math_stat_update(&jb->jb_burst, jb->jb_level);
  483. jb->jb_max_hist_level = max(jb->jb_max_hist_level, jb->jb_level);
  484. /* Burst level is decreasing */
  485. if (jb->jb_level < jb->jb_eff_level) {
  486. enum { STABLE_HISTORY_LIMIT = 20 };
  487. jb->jb_stable_hist++;
  488. /* Only update the effective level (and prefetch) if 'stable'
  489. * condition is reached (not just short time impulse)
  490. */
  491. if (jb->jb_stable_hist > STABLE_HISTORY_LIMIT) {
  492. diff = (jb->jb_eff_level - jb->jb_max_hist_level) / 3;
  493. if (diff < 1)
  494. diff = 1;
  495. /* Update effective burst level */
  496. jb->jb_eff_level -= diff;
  497. /* Update prefetch based on level */
  498. if (jb->jb_init_prefetch) {
  499. jb->jb_prefetch = jb->jb_eff_level;
  500. if (jb->jb_prefetch < jb->jb_min_prefetch)
  501. jb->jb_prefetch = jb->jb_min_prefetch;
  502. }
  503. /* Reset history */
  504. jb->jb_max_hist_level = 0;
  505. jb->jb_stable_hist = 0;
  506. }
  507. }
  508. /* Burst level is increasing */
  509. else if (jb->jb_level > jb->jb_eff_level) {
  510. /* Instaneous set effective burst level to recent maximum level */
  511. jb->jb_eff_level = min(jb->jb_max_hist_level,
  512. (int)(jb->jb_max_count*4/5));
  513. /* Update prefetch based on level */
  514. if (jb->jb_init_prefetch) {
  515. jb->jb_prefetch = jb->jb_eff_level;
  516. if (jb->jb_prefetch > jb->jb_max_prefetch)
  517. jb->jb_prefetch = jb->jb_max_prefetch;
  518. }
  519. jb->jb_stable_hist = 0;
  520. /* Do not reset max_hist_level. */
  521. //jb->jb_max_hist_level = 0;
  522. }
  523. /* Level is unchanged */
  524. else {
  525. jb->jb_stable_hist = 0;
  526. }
  527. }
  528. void jbuf_update(jitterbuf *jb, int oper)
  529. {
  530. if(jb->jb_last_op != oper) {
  531. jb->jb_last_op = oper;
  532. if (jb->jb_status == JB_STATUS_INITIALIZING) {
  533. /* Switch status 'initializing' -> 'processing' after some OP
  534. * switch cycles and current OP is GET (burst level is calculated
  535. * based on PUT burst), so burst calculation is guaranted to be
  536. * performed right after the status switching.
  537. */
  538. if (++jb->jb_init_cycle_cnt >= INIT_CYCLE && oper == JB_OP_GET) {
  539. jb->jb_status = JB_STATUS_PROCESSING;
  540. } else {
  541. jb->jb_level = 0;
  542. return;
  543. }
  544. }
  545. /* Perform jitter calculation based on PUT burst-level only, since
  546. * GET burst-level may not be accurate, e.g: when VAD is active.
  547. * Note that when burst-level is too big, i.e: exceeds jb_max_burst,
  548. * the GET op may be idle, in this case, we better skip the jitter
  549. * calculation.
  550. */
  551. if (oper == JB_OP_GET && jb->jb_level < jb->jb_max_burst)
  552. jbuf_calculate_jitter(jb);
  553. jb->jb_level = 0;
  554. }
  555. /* These code is used for shortening the delay in the jitter buffer.
  556. * It needs shrink only when there is possibility of drift. Drift
  557. * detection is performed by inspecting the jitter buffer size, if
  558. * its size is twice of current burst level, there can be drift.
  559. *
  560. * Moreover, normally drift level is quite low, so JB shouldn't need
  561. * to shrink aggresively, it will shrink maximum one frame per
  562. * MIN_SHRINK_GAP_MSEC ms. Theoritically, JB may handle drift level
  563. * as much as = FRAME_PTIME/MIN_SHRINK_GAP_MSEC * 100%
  564. *
  565. * Whenever there is drift, where PUT > GET, this method will keep
  566. * the latency (JB size) as much as twice of burst level.
  567. */
  568. /* Shrinking due of drift will be implicitly done by progressive discard,
  569. * so just disable it when progressive discard is active.
  570. */
  571. #if !PROGRESSIVE_DISCARD
  572. if (jb->jb_status != JB_STATUS_PROCESSING)
  573. return;
  574. {
  575. int diff, burst_level;
  576. burst_level = max(jb->jb_eff_level, jb->jb_level);
  577. diff = jb_framelist_eff_size(&jb->jb_framelist) - burst_level*2;
  578. if (diff >= SAFE_SHRINKING_DIFF) {
  579. int seq_origin;
  580. /* Check and adjust jb_last_del_seq, in case there was
  581. * seq restart
  582. */
  583. seq_origin = jb_framelist_origin(&jb->jb_framelist);
  584. if (seq_origin < jb->jb_last_del_seq)
  585. jb->jb_last_del_seq = seq_origin;
  586. if (seq_origin - jb->jb_last_del_seq >= jb->jb_min_shrink_gap)
  587. {
  588. /* Shrink slowly, one frame per cycle */
  589. diff = 1;
  590. /* Drop frame(s)! */
  591. diff = jb_framelist_remove_head(&jb->jb_framelist, diff);
  592. jb->jb_last_del_seq = jb_framelist_origin(&jb->jb_framelist);
  593. jb->jb_discard += diff;
  594. }
  595. }
  596. }
  597. #endif /* !PROGRESSIVE_DISCARD */
  598. }
  599. void jbuf_put_frame( jitterbuf *jb, const void *frame, size_t frame_size)
  600. {
  601. int frame_seq = jb->jb_seq ++;
  602. jbuf_put_frame2(jb, frame, frame_size, 0, frame_seq, NULL);
  603. }
  604. void jbuf_put_frame2(jitterbuf *jb,
  605. const void *frame,
  606. size_t frame_size,
  607. unsigned bit_info,
  608. int frame_seq,
  609. int *discarded)
  610. {
  611. size_t min_frame_size;
  612. int new_size, cur_size, frame_type = JB_NORMAL_FRAME;
  613. int status;
  614. cur_size = jb_framelist_eff_size(&jb->jb_framelist);
  615. #if PROGRESSIVE_DISCARD
  616. {
  617. unsigned interval, seq_delta;
  618. unsigned burst_level, burst_factor;
  619. /* Calculating discard interval (aggressiveness) based on
  620. * (current size / burst level).
  621. */
  622. if (jb->jb_status == JB_STATUS_PROCESSING) {
  623. burst_level = max(jb->jb_eff_level, jb->jb_level);
  624. burst_factor = cur_size / burst_level;
  625. /* Tolerate small spikes */
  626. if ((burst_level <= 5) && (burst_factor < 3))
  627. burst_factor = 0;
  628. } else {
  629. burst_factor = 0;
  630. }
  631. switch (burst_factor) {
  632. case 0:
  633. interval = 0;
  634. break;
  635. case 1:
  636. interval = 7;
  637. break;
  638. case 2:
  639. interval = 5;
  640. break;
  641. default:
  642. interval = 4;
  643. break;
  644. }
  645. /* Do the math now to see if we should discard this packet.
  646. * Calculate the distance from the last sequence
  647. * discarded. If negative, then this is an out of
  648. * order frame so just proceed with discard. Else
  649. * see if the delta is at least the intervals worth away
  650. * from the last frame discarded.
  651. */
  652. seq_delta = (unsigned short)(frame_seq - jb->jb_last_discard_seq);
  653. if ((0 != interval) && (seq_delta >= interval)) {
  654. frame_type = JB_DISCARDED_FRAME;
  655. jb->jb_last_discard_seq = frame_seq;
  656. }
  657. }
  658. #endif /* PROGRESSIVE_DISCARD */
  659. /* Attempt to store the frame */
  660. min_frame_size = min(frame_size, jb->jb_frame_size);
  661. status = jb_framelist_put_at(&jb->jb_framelist, frame_seq, frame,
  662. min_frame_size, bit_info, frame_type);
  663. /* Jitter buffer is full, remove some older frames */
  664. while (status == PJ_ETOOMANY) {
  665. int distance;
  666. unsigned removed;
  667. /* When progressive discard activated, just remove as few as possible
  668. * just to make this frame in.
  669. */
  670. #if PROGRESSIVE_DISCARD
  671. /* The cases of seq-jump, out-of-order, and seq restart should have
  672. * been handled/normalized by previous call of jb_framelist_put_at().
  673. * So we're confident about 'distance' value here.
  674. */
  675. distance = (frame_seq - jb_framelist_origin(&jb->jb_framelist)) -
  676. jb->jb_max_count + 1;
  677. assert(distance > 0);
  678. #else
  679. distance = max(jb->jb_max_count/4, 1);
  680. #endif
  681. removed = jb_framelist_remove_head(&jb->jb_framelist, distance);
  682. status = jb_framelist_put_at(&jb->jb_framelist, frame_seq, frame,
  683. min_frame_size, bit_info, frame_type);
  684. jb->jb_discard += removed;
  685. }
  686. /* Get new JB size after PUT */
  687. new_size = jb_framelist_eff_size(&jb->jb_framelist);
  688. /* Return the flag if this frame is discarded */
  689. if (discarded)
  690. *discarded = (status != PJ_SUCCESS);
  691. if (status == PJ_SUCCESS) {
  692. if (jb->jb_status == JB_STATUS_PREFETCHING) {
  693. if (new_size >= jb->jb_prefetch)
  694. jb->jb_status = JB_STATUS_PROCESSING;
  695. }
  696. jb->jb_level += (new_size > cur_size ? new_size-cur_size : 1);
  697. jbuf_update(jb, JB_OP_PUT);
  698. } else
  699. jb->jb_discard++;
  700. }
  701. /*
  702. * Get frame from jitter buffer.
  703. */
  704. void jbuf_get_frame( jitterbuf *jb, void *frame, char *p_frame_type)
  705. {
  706. jbuf_get_frame2(jb, frame, NULL, p_frame_type, NULL);
  707. }
  708. /*
  709. * Get frame from jitter buffer.
  710. */
  711. void jbuf_get_frame2(jitterbuf *jb,
  712. void *frame,
  713. size_t *size,
  714. char *p_frame_type,
  715. unsigned *bit_info)
  716. {
  717. if (jb->jb_status == JB_STATUS_PREFETCHING) {
  718. /* Can't return frame because jitter buffer is filling up
  719. * minimum prefetch.
  720. */
  721. *p_frame_type = JB_ZERO_PREFETCH_FRAME;
  722. if (size)
  723. *size = 0;
  724. jb->jb_empty++;
  725. } else {
  726. jb_frame_type ftype = JB_NORMAL_FRAME;
  727. int res;
  728. /* Try to retrieve a frame from frame list */
  729. res = jb_framelist_get(&jb->jb_framelist, frame, size, &ftype,
  730. bit_info);
  731. if (res) {
  732. /* We've successfully retrieved a frame from the frame list, but
  733. * the frame could be a blank frame!
  734. */
  735. if (ftype == JB_NORMAL_FRAME) {
  736. *p_frame_type = JB_NORMAL_FRAME;
  737. } else {
  738. *p_frame_type = JB_MISSING_FRAME;
  739. jb->jb_lost++;
  740. }
  741. /* Store delay history at the first GET */
  742. if (jb->jb_last_op == JB_OP_PUT) {
  743. unsigned cur_size;
  744. /* We've just retrieved one frame, so add one to cur_size */
  745. cur_size = jb_framelist_eff_size(&jb->jb_framelist) + 1;
  746. math_stat_update(&jb->jb_delay,
  747. cur_size*jb->jb_frame_ptime);
  748. }
  749. } else {
  750. /* Jitter buffer is empty */
  751. if (jb->jb_prefetch)
  752. jb->jb_status = JB_STATUS_PREFETCHING;
  753. *p_frame_type = JB_ZERO_EMPTY_FRAME;
  754. if (size)
  755. *size = 0;
  756. jb->jb_empty++;
  757. }
  758. }
  759. jb->jb_level++;
  760. jbuf_update(jb, JB_OP_GET);
  761. }
  762. int jbuf_get_state(const jitterbuf *jb, jb_state *state )
  763. {
  764. assert(jb && state);
  765. state->frame_size = jb->jb_frame_size;
  766. state->min_prefetch = jb->jb_min_prefetch;
  767. state->max_prefetch = jb->jb_max_prefetch;
  768. state->burst = jb->jb_eff_level;
  769. state->prefetch = jb->jb_prefetch;
  770. state->size = jb_framelist_eff_size(&jb->jb_framelist);
  771. state->avg_delay = jb->jb_delay.mean;
  772. state->min_delay = jb->jb_delay.min;
  773. state->max_delay = jb->jb_delay.max;
  774. state->dev_delay = math_stat_get_stddev(&jb->jb_delay);
  775. state->avg_burst = jb->jb_burst.mean;
  776. state->empty = jb->jb_empty;
  777. state->discard = jb->jb_discard;
  778. state->lost = jb->jb_lost;
  779. return 0;
  780. }