sync_queue.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  1. /*
  2. * This file is part of FFmpeg.
  3. *
  4. * FFmpeg is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * FFmpeg is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with FFmpeg; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #include <stdint.h>
  19. #include <string.h>
  20. #include "libavutil/avassert.h"
  21. #include "libavutil/channel_layout.h"
  22. #include "libavutil/cpu.h"
  23. #include "libavutil/error.h"
  24. #include "libavutil/fifo.h"
  25. #include "libavutil/mathematics.h"
  26. #include "libavutil/mem.h"
  27. #include "libavutil/samplefmt.h"
  28. #include "libavutil/timestamp.h"
  29. #include "objpool.h"
  30. #include "sync_queue.h"
  31. /*
  32. * How this works:
  33. * --------------
  34. * time: 0 1 2 3 4 5 6 7 8 9 10 11 12 13
  35. * -------------------------------------------------------------------
  36. * | | | | | | | | | | | | | |
  37. * | ┌───┐┌────────┐┌───┐┌─────────────┐
  38. * stream 0| │d=1││ d=2 ││d=1││ d=3 │
  39. * | └───┘└────────┘└───┘└─────────────┘
  40. * ┌───┐ ┌───────────────────────┐
  41. * stream 1│d=1│ │ d=5 │
  42. * └───┘ └───────────────────────┘
  43. * | ┌───┐┌───┐┌───┐┌───┐
  44. * stream 2| │d=1││d=1││d=1││d=1│ <- stream 2 is the head stream of the queue
  45. * | └───┘└───┘└───┘└───┘
  46. * ^ ^
  47. * [stream 2 tail] [stream 2 head]
  48. *
  49. * We have N streams (N=3 in the diagram), each stream is a FIFO. The *tail* of
  50. * each FIFO is the frame with smallest end time, the *head* is the frame with
  51. * the largest end time. Frames submitted to the queue with sq_send() are placed
  52. * after the head, frames returned to the caller with sq_receive() are taken
  53. * from the tail.
  54. *
  55. * The head stream of the whole queue (SyncQueue.head_stream) is the limiting
  56. * stream with the *smallest* head timestamp, i.e. the stream whose source lags
  57. * furthest behind all other streams. It determines which frames can be output
  58. * from the queue.
  59. *
  60. * In the diagram, the head stream is 2, because it head time is t=5, while
  61. * streams 0 and 1 end at t=8 and t=9 respectively. All frames that _end_ at
  62. * or before t=5 can be output, i.e. the first 3 frames from stream 0, first
  63. * frame from stream 1, and all 4 frames from stream 2.
  64. */
  65. typedef struct SyncQueueStream {
  66. AVFifo *fifo;
  67. AVRational tb;
  68. /* number of audio samples in fifo */
  69. uint64_t samples_queued;
  70. /* stream head: largest timestamp seen */
  71. int64_t head_ts;
  72. int limiting;
  73. /* no more frames will be sent for this stream */
  74. int finished;
  75. uint64_t frames_sent;
  76. uint64_t samples_sent;
  77. uint64_t frames_max;
  78. int frame_samples;
  79. } SyncQueueStream;
  80. struct SyncQueue {
  81. enum SyncQueueType type;
  82. void *logctx;
  83. /* no more frames will be sent for any stream */
  84. int finished;
  85. /* sync head: the stream with the _smallest_ head timestamp
  86. * this stream determines which frames can be output */
  87. int head_stream;
  88. /* the finished stream with the smallest finish timestamp or -1 */
  89. int head_finished_stream;
  90. // maximum buffering duration in microseconds
  91. int64_t buf_size_us;
  92. SyncQueueStream *streams;
  93. unsigned int nb_streams;
  94. // pool of preallocated frames to avoid constant allocations
  95. ObjPool *pool;
  96. int have_limiting;
  97. uintptr_t align_mask;
  98. };
  99. static void frame_move(const SyncQueue *sq, SyncQueueFrame dst,
  100. SyncQueueFrame src)
  101. {
  102. if (sq->type == SYNC_QUEUE_PACKETS)
  103. av_packet_move_ref(dst.p, src.p);
  104. else
  105. av_frame_move_ref(dst.f, src.f);
  106. }
  107. /**
  108. * Compute the end timestamp of a frame. If nb_samples is provided, consider
  109. * the frame to have this number of audio samples, otherwise use frame duration.
  110. */
  111. static int64_t frame_end(const SyncQueue *sq, SyncQueueFrame frame, int nb_samples)
  112. {
  113. if (nb_samples) {
  114. int64_t d = av_rescale_q(nb_samples, (AVRational){ 1, frame.f->sample_rate},
  115. frame.f->time_base);
  116. return frame.f->pts + d;
  117. }
  118. return (sq->type == SYNC_QUEUE_PACKETS) ?
  119. frame.p->pts + frame.p->duration :
  120. frame.f->pts + frame.f->duration;
  121. }
  122. static int frame_samples(const SyncQueue *sq, SyncQueueFrame frame)
  123. {
  124. return (sq->type == SYNC_QUEUE_PACKETS) ? 0 : frame.f->nb_samples;
  125. }
  126. static int frame_null(const SyncQueue *sq, SyncQueueFrame frame)
  127. {
  128. return (sq->type == SYNC_QUEUE_PACKETS) ? (frame.p == NULL) : (frame.f == NULL);
  129. }
  130. static void tb_update(const SyncQueue *sq, SyncQueueStream *st,
  131. const SyncQueueFrame frame)
  132. {
  133. AVRational tb = (sq->type == SYNC_QUEUE_PACKETS) ?
  134. frame.p->time_base : frame.f->time_base;
  135. av_assert0(tb.num > 0 && tb.den > 0);
  136. if (tb.num == st->tb.num && tb.den == st->tb.den)
  137. return;
  138. // timebase should not change after the first frame
  139. av_assert0(!av_fifo_can_read(st->fifo));
  140. if (st->head_ts != AV_NOPTS_VALUE)
  141. st->head_ts = av_rescale_q(st->head_ts, st->tb, tb);
  142. st->tb = tb;
  143. }
  144. static void finish_stream(SyncQueue *sq, unsigned int stream_idx)
  145. {
  146. SyncQueueStream *st = &sq->streams[stream_idx];
  147. if (!st->finished)
  148. av_log(sq->logctx, AV_LOG_DEBUG,
  149. "sq: finish %u; head ts %s\n", stream_idx,
  150. av_ts2timestr(st->head_ts, &st->tb));
  151. st->finished = 1;
  152. if (st->limiting && st->head_ts != AV_NOPTS_VALUE) {
  153. /* check if this stream is the new finished head */
  154. if (sq->head_finished_stream < 0 ||
  155. av_compare_ts(st->head_ts, st->tb,
  156. sq->streams[sq->head_finished_stream].head_ts,
  157. sq->streams[sq->head_finished_stream].tb) < 0) {
  158. sq->head_finished_stream = stream_idx;
  159. }
  160. /* mark as finished all streams that should no longer receive new frames,
  161. * due to them being ahead of some finished stream */
  162. st = &sq->streams[sq->head_finished_stream];
  163. for (unsigned int i = 0; i < sq->nb_streams; i++) {
  164. SyncQueueStream *st1 = &sq->streams[i];
  165. if (st != st1 && st1->head_ts != AV_NOPTS_VALUE &&
  166. av_compare_ts(st->head_ts, st->tb, st1->head_ts, st1->tb) <= 0) {
  167. if (!st1->finished)
  168. av_log(sq->logctx, AV_LOG_DEBUG,
  169. "sq: finish secondary %u; head ts %s\n", i,
  170. av_ts2timestr(st1->head_ts, &st1->tb));
  171. st1->finished = 1;
  172. }
  173. }
  174. }
  175. /* mark the whole queue as finished if all streams are finished */
  176. for (unsigned int i = 0; i < sq->nb_streams; i++) {
  177. if (!sq->streams[i].finished)
  178. return;
  179. }
  180. sq->finished = 1;
  181. av_log(sq->logctx, AV_LOG_DEBUG, "sq: finish queue\n");
  182. }
  183. static void queue_head_update(SyncQueue *sq)
  184. {
  185. av_assert0(sq->have_limiting);
  186. if (sq->head_stream < 0) {
  187. unsigned first_limiting = UINT_MAX;
  188. /* wait for one timestamp in each stream before determining
  189. * the queue head */
  190. for (unsigned int i = 0; i < sq->nb_streams; i++) {
  191. SyncQueueStream *st = &sq->streams[i];
  192. if (!st->limiting)
  193. continue;
  194. if (st->head_ts == AV_NOPTS_VALUE)
  195. return;
  196. if (first_limiting == UINT_MAX)
  197. first_limiting = i;
  198. }
  199. // placeholder value, correct one will be found below
  200. av_assert0(first_limiting < UINT_MAX);
  201. sq->head_stream = first_limiting;
  202. }
  203. for (unsigned int i = 0; i < sq->nb_streams; i++) {
  204. SyncQueueStream *st_head = &sq->streams[sq->head_stream];
  205. SyncQueueStream *st_other = &sq->streams[i];
  206. if (st_other->limiting && st_other->head_ts != AV_NOPTS_VALUE &&
  207. av_compare_ts(st_other->head_ts, st_other->tb,
  208. st_head->head_ts, st_head->tb) < 0)
  209. sq->head_stream = i;
  210. }
  211. }
  212. /* update this stream's head timestamp */
  213. static void stream_update_ts(SyncQueue *sq, unsigned int stream_idx, int64_t ts)
  214. {
  215. SyncQueueStream *st = &sq->streams[stream_idx];
  216. if (ts == AV_NOPTS_VALUE ||
  217. (st->head_ts != AV_NOPTS_VALUE && st->head_ts >= ts))
  218. return;
  219. st->head_ts = ts;
  220. /* if this stream is now ahead of some finished stream, then
  221. * this stream is also finished */
  222. if (sq->head_finished_stream >= 0 &&
  223. av_compare_ts(sq->streams[sq->head_finished_stream].head_ts,
  224. sq->streams[sq->head_finished_stream].tb,
  225. ts, st->tb) <= 0)
  226. finish_stream(sq, stream_idx);
  227. /* update the overall head timestamp if it could have changed */
  228. if (st->limiting &&
  229. (sq->head_stream < 0 || sq->head_stream == stream_idx))
  230. queue_head_update(sq);
  231. }
  232. /* If the queue for the given stream (or all streams when stream_idx=-1)
  233. * is overflowing, trigger a fake heartbeat on lagging streams.
  234. *
  235. * @return 1 if heartbeat triggered, 0 otherwise
  236. */
  237. static int overflow_heartbeat(SyncQueue *sq, int stream_idx)
  238. {
  239. SyncQueueStream *st;
  240. SyncQueueFrame frame;
  241. int64_t tail_ts = AV_NOPTS_VALUE;
  242. /* if no stream specified, pick the one that is most ahead */
  243. if (stream_idx < 0) {
  244. int64_t ts = AV_NOPTS_VALUE;
  245. for (int i = 0; i < sq->nb_streams; i++) {
  246. st = &sq->streams[i];
  247. if (st->head_ts != AV_NOPTS_VALUE &&
  248. (ts == AV_NOPTS_VALUE ||
  249. av_compare_ts(ts, sq->streams[stream_idx].tb,
  250. st->head_ts, st->tb) < 0)) {
  251. ts = st->head_ts;
  252. stream_idx = i;
  253. }
  254. }
  255. /* no stream has a timestamp yet -> nothing to do */
  256. if (stream_idx < 0)
  257. return 0;
  258. }
  259. st = &sq->streams[stream_idx];
  260. /* get the chosen stream's tail timestamp */
  261. for (size_t i = 0; tail_ts == AV_NOPTS_VALUE &&
  262. av_fifo_peek(st->fifo, &frame, 1, i) >= 0; i++)
  263. tail_ts = frame_end(sq, frame, 0);
  264. /* overflow triggers when the tail is over specified duration behind the head */
  265. if (tail_ts == AV_NOPTS_VALUE || tail_ts >= st->head_ts ||
  266. av_rescale_q(st->head_ts - tail_ts, st->tb, AV_TIME_BASE_Q) < sq->buf_size_us)
  267. return 0;
  268. /* signal a fake timestamp for all streams that prevent tail_ts from being output */
  269. tail_ts++;
  270. for (unsigned int i = 0; i < sq->nb_streams; i++) {
  271. const SyncQueueStream *st1 = &sq->streams[i];
  272. int64_t ts;
  273. if (st == st1 || st1->finished ||
  274. (st1->head_ts != AV_NOPTS_VALUE &&
  275. av_compare_ts(tail_ts, st->tb, st1->head_ts, st1->tb) <= 0))
  276. continue;
  277. ts = av_rescale_q(tail_ts, st->tb, st1->tb);
  278. if (st1->head_ts != AV_NOPTS_VALUE)
  279. ts = FFMAX(st1->head_ts + 1, ts);
  280. av_log(sq->logctx, AV_LOG_DEBUG, "sq: %u overflow heardbeat %s -> %s\n",
  281. i, av_ts2timestr(st1->head_ts, &st1->tb), av_ts2timestr(ts, &st1->tb));
  282. stream_update_ts(sq, i, ts);
  283. }
  284. return 1;
  285. }
  286. int sq_send(SyncQueue *sq, unsigned int stream_idx, SyncQueueFrame frame)
  287. {
  288. SyncQueueStream *st;
  289. SyncQueueFrame dst;
  290. int64_t ts;
  291. int ret, nb_samples;
  292. av_assert0(stream_idx < sq->nb_streams);
  293. st = &sq->streams[stream_idx];
  294. if (frame_null(sq, frame)) {
  295. av_log(sq->logctx, AV_LOG_DEBUG, "sq: %u EOF\n", stream_idx);
  296. finish_stream(sq, stream_idx);
  297. return 0;
  298. }
  299. if (st->finished)
  300. return AVERROR_EOF;
  301. tb_update(sq, st, frame);
  302. ret = objpool_get(sq->pool, (void**)&dst);
  303. if (ret < 0)
  304. return ret;
  305. frame_move(sq, dst, frame);
  306. nb_samples = frame_samples(sq, dst);
  307. // make sure frame duration is consistent with sample count
  308. if (nb_samples) {
  309. av_assert0(dst.f->sample_rate > 0);
  310. dst.f->duration = av_rescale_q(nb_samples, (AVRational){ 1, dst.f->sample_rate },
  311. dst.f->time_base);
  312. }
  313. ts = frame_end(sq, dst, 0);
  314. av_log(sq->logctx, AV_LOG_DEBUG, "sq: send %u ts %s\n", stream_idx,
  315. av_ts2timestr(ts, &st->tb));
  316. ret = av_fifo_write(st->fifo, &dst, 1);
  317. if (ret < 0) {
  318. frame_move(sq, frame, dst);
  319. objpool_release(sq->pool, (void**)&dst);
  320. return ret;
  321. }
  322. stream_update_ts(sq, stream_idx, ts);
  323. st->samples_queued += nb_samples;
  324. st->samples_sent += nb_samples;
  325. if (st->frame_samples)
  326. st->frames_sent = st->samples_sent / st->frame_samples;
  327. else
  328. st->frames_sent++;
  329. if (st->frames_sent >= st->frames_max) {
  330. av_log(sq->logctx, AV_LOG_DEBUG, "sq: %u frames_max %"PRIu64" reached\n",
  331. stream_idx, st->frames_max);
  332. finish_stream(sq, stream_idx);
  333. }
  334. return 0;
  335. }
  336. static void offset_audio(AVFrame *f, int nb_samples)
  337. {
  338. const int planar = av_sample_fmt_is_planar(f->format);
  339. const int planes = planar ? f->ch_layout.nb_channels : 1;
  340. const int bps = av_get_bytes_per_sample(f->format);
  341. const int offset = nb_samples * bps * (planar ? 1 : f->ch_layout.nb_channels);
  342. av_assert0(bps > 0);
  343. av_assert0(nb_samples < f->nb_samples);
  344. for (int i = 0; i < planes; i++) {
  345. f->extended_data[i] += offset;
  346. if (i < FF_ARRAY_ELEMS(f->data))
  347. f->data[i] = f->extended_data[i];
  348. }
  349. f->linesize[0] -= offset;
  350. f->nb_samples -= nb_samples;
  351. f->duration = av_rescale_q(f->nb_samples, (AVRational){ 1, f->sample_rate },
  352. f->time_base);
  353. f->pts += av_rescale_q(nb_samples, (AVRational){ 1, f->sample_rate },
  354. f->time_base);
  355. }
  356. static int frame_is_aligned(const SyncQueue *sq, const AVFrame *frame)
  357. {
  358. // only checks linesize[0], so only works for audio
  359. av_assert0(frame->nb_samples > 0);
  360. av_assert0(sq->align_mask);
  361. // only check data[0], because we always offset all data pointers
  362. // by the same offset, so if one is aligned, all are
  363. if (!((uintptr_t)frame->data[0] & sq->align_mask) &&
  364. !(frame->linesize[0] & sq->align_mask) &&
  365. frame->linesize[0] > sq->align_mask)
  366. return 1;
  367. return 0;
  368. }
  369. static int receive_samples(SyncQueue *sq, SyncQueueStream *st,
  370. AVFrame *dst, int nb_samples)
  371. {
  372. SyncQueueFrame src;
  373. int ret;
  374. av_assert0(st->samples_queued >= nb_samples);
  375. ret = av_fifo_peek(st->fifo, &src, 1, 0);
  376. av_assert0(ret >= 0);
  377. // peeked frame has enough samples and its data is aligned
  378. // -> we can just make a reference and limit its sample count
  379. if (src.f->nb_samples > nb_samples && frame_is_aligned(sq, src.f)) {
  380. ret = av_frame_ref(dst, src.f);
  381. if (ret < 0)
  382. return ret;
  383. dst->nb_samples = nb_samples;
  384. offset_audio(src.f, nb_samples);
  385. st->samples_queued -= nb_samples;
  386. goto finish;
  387. }
  388. // otherwise allocate a new frame and copy the data
  389. ret = av_channel_layout_copy(&dst->ch_layout, &src.f->ch_layout);
  390. if (ret < 0)
  391. return ret;
  392. dst->format = src.f->format;
  393. dst->nb_samples = nb_samples;
  394. ret = av_frame_get_buffer(dst, 0);
  395. if (ret < 0)
  396. goto fail;
  397. ret = av_frame_copy_props(dst, src.f);
  398. if (ret < 0)
  399. goto fail;
  400. dst->nb_samples = 0;
  401. while (dst->nb_samples < nb_samples) {
  402. int to_copy;
  403. ret = av_fifo_peek(st->fifo, &src, 1, 0);
  404. av_assert0(ret >= 0);
  405. to_copy = FFMIN(nb_samples - dst->nb_samples, src.f->nb_samples);
  406. av_samples_copy(dst->extended_data, src.f->extended_data, dst->nb_samples,
  407. 0, to_copy, dst->ch_layout.nb_channels, dst->format);
  408. if (to_copy < src.f->nb_samples)
  409. offset_audio(src.f, to_copy);
  410. else {
  411. av_frame_unref(src.f);
  412. objpool_release(sq->pool, (void**)&src);
  413. av_fifo_drain2(st->fifo, 1);
  414. }
  415. st->samples_queued -= to_copy;
  416. dst->nb_samples += to_copy;
  417. }
  418. finish:
  419. dst->duration = av_rescale_q(nb_samples, (AVRational){ 1, dst->sample_rate },
  420. dst->time_base);
  421. return 0;
  422. fail:
  423. av_frame_unref(dst);
  424. return ret;
  425. }
  426. static int receive_for_stream(SyncQueue *sq, unsigned int stream_idx,
  427. SyncQueueFrame frame)
  428. {
  429. const SyncQueueStream *st_head = sq->head_stream >= 0 ?
  430. &sq->streams[sq->head_stream] : NULL;
  431. SyncQueueStream *st;
  432. av_assert0(stream_idx < sq->nb_streams);
  433. st = &sq->streams[stream_idx];
  434. if (av_fifo_can_read(st->fifo) &&
  435. (st->frame_samples <= st->samples_queued || st->finished)) {
  436. int nb_samples = st->frame_samples;
  437. SyncQueueFrame peek;
  438. int64_t ts;
  439. int cmp = 1;
  440. if (st->finished)
  441. nb_samples = FFMIN(nb_samples, st->samples_queued);
  442. av_fifo_peek(st->fifo, &peek, 1, 0);
  443. ts = frame_end(sq, peek, nb_samples);
  444. /* check if this stream's tail timestamp does not overtake
  445. * the overall queue head */
  446. if (ts != AV_NOPTS_VALUE && st_head)
  447. cmp = av_compare_ts(ts, st->tb, st_head->head_ts, st_head->tb);
  448. /* We can release frames that do not end after the queue head.
  449. * Frames with no timestamps are just passed through with no conditions.
  450. * Frames are also passed through when there are no limiting streams.
  451. */
  452. if (cmp <= 0 || ts == AV_NOPTS_VALUE || !sq->have_limiting) {
  453. if (nb_samples &&
  454. (nb_samples != peek.f->nb_samples || !frame_is_aligned(sq, peek.f))) {
  455. int ret = receive_samples(sq, st, frame.f, nb_samples);
  456. if (ret < 0)
  457. return ret;
  458. } else {
  459. frame_move(sq, frame, peek);
  460. objpool_release(sq->pool, (void**)&peek);
  461. av_fifo_drain2(st->fifo, 1);
  462. av_assert0(st->samples_queued >= frame_samples(sq, frame));
  463. st->samples_queued -= frame_samples(sq, frame);
  464. }
  465. av_log(sq->logctx, AV_LOG_DEBUG,
  466. "sq: receive %u ts %s queue head %d ts %s\n", stream_idx,
  467. av_ts2timestr(frame_end(sq, frame, 0), &st->tb),
  468. sq->head_stream,
  469. st_head ? av_ts2timestr(st_head->head_ts, &st_head->tb) : "N/A");
  470. return 0;
  471. }
  472. }
  473. return (sq->finished || (st->finished && !av_fifo_can_read(st->fifo))) ?
  474. AVERROR_EOF : AVERROR(EAGAIN);
  475. }
  476. static int receive_internal(SyncQueue *sq, int stream_idx, SyncQueueFrame frame)
  477. {
  478. int nb_eof = 0;
  479. int ret;
  480. /* read a frame for a specific stream */
  481. if (stream_idx >= 0) {
  482. ret = receive_for_stream(sq, stream_idx, frame);
  483. return (ret < 0) ? ret : stream_idx;
  484. }
  485. /* read a frame for any stream with available output */
  486. for (unsigned int i = 0; i < sq->nb_streams; i++) {
  487. ret = receive_for_stream(sq, i, frame);
  488. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN)) {
  489. nb_eof += (ret == AVERROR_EOF);
  490. continue;
  491. }
  492. return (ret < 0) ? ret : i;
  493. }
  494. return (nb_eof == sq->nb_streams) ? AVERROR_EOF : AVERROR(EAGAIN);
  495. }
  496. int sq_receive(SyncQueue *sq, int stream_idx, SyncQueueFrame frame)
  497. {
  498. int ret = receive_internal(sq, stream_idx, frame);
  499. /* try again if the queue overflowed and triggered a fake heartbeat
  500. * for lagging streams */
  501. if (ret == AVERROR(EAGAIN) && overflow_heartbeat(sq, stream_idx))
  502. ret = receive_internal(sq, stream_idx, frame);
  503. return ret;
  504. }
  505. int sq_add_stream(SyncQueue *sq, int limiting)
  506. {
  507. SyncQueueStream *tmp, *st;
  508. tmp = av_realloc_array(sq->streams, sq->nb_streams + 1, sizeof(*sq->streams));
  509. if (!tmp)
  510. return AVERROR(ENOMEM);
  511. sq->streams = tmp;
  512. st = &sq->streams[sq->nb_streams];
  513. memset(st, 0, sizeof(*st));
  514. st->fifo = av_fifo_alloc2(1, sizeof(SyncQueueFrame), AV_FIFO_FLAG_AUTO_GROW);
  515. if (!st->fifo)
  516. return AVERROR(ENOMEM);
  517. /* we set a valid default, so that a pathological stream that never
  518. * receives even a real timebase (and no frames) won't stall all other
  519. * streams forever; cf. overflow_heartbeat() */
  520. st->tb = (AVRational){ 1, 1 };
  521. st->head_ts = AV_NOPTS_VALUE;
  522. st->frames_max = UINT64_MAX;
  523. st->limiting = limiting;
  524. sq->have_limiting |= limiting;
  525. return sq->nb_streams++;
  526. }
  527. void sq_limit_frames(SyncQueue *sq, unsigned int stream_idx, uint64_t frames)
  528. {
  529. SyncQueueStream *st;
  530. av_assert0(stream_idx < sq->nb_streams);
  531. st = &sq->streams[stream_idx];
  532. st->frames_max = frames;
  533. if (st->frames_sent >= st->frames_max)
  534. finish_stream(sq, stream_idx);
  535. }
  536. void sq_frame_samples(SyncQueue *sq, unsigned int stream_idx,
  537. int frame_samples)
  538. {
  539. SyncQueueStream *st;
  540. av_assert0(sq->type == SYNC_QUEUE_FRAMES);
  541. av_assert0(stream_idx < sq->nb_streams);
  542. st = &sq->streams[stream_idx];
  543. st->frame_samples = frame_samples;
  544. sq->align_mask = av_cpu_max_align() - 1;
  545. }
  546. SyncQueue *sq_alloc(enum SyncQueueType type, int64_t buf_size_us, void *logctx)
  547. {
  548. SyncQueue *sq = av_mallocz(sizeof(*sq));
  549. if (!sq)
  550. return NULL;
  551. sq->type = type;
  552. sq->buf_size_us = buf_size_us;
  553. sq->logctx = logctx;
  554. sq->head_stream = -1;
  555. sq->head_finished_stream = -1;
  556. sq->pool = (type == SYNC_QUEUE_PACKETS) ? objpool_alloc_packets() :
  557. objpool_alloc_frames();
  558. if (!sq->pool) {
  559. av_freep(&sq);
  560. return NULL;
  561. }
  562. return sq;
  563. }
  564. void sq_free(SyncQueue **psq)
  565. {
  566. SyncQueue *sq = *psq;
  567. if (!sq)
  568. return;
  569. for (unsigned int i = 0; i < sq->nb_streams; i++) {
  570. SyncQueueFrame frame;
  571. while (av_fifo_read(sq->streams[i].fifo, &frame, 1) >= 0)
  572. objpool_release(sq->pool, (void**)&frame);
  573. av_fifo_freep2(&sq->streams[i].fifo);
  574. }
  575. av_freep(&sq->streams);
  576. objpool_free(&sq->pool);
  577. av_freep(psq);
  578. }