ffmpeg_sched.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. /*
  2. * Inter-thread scheduling/synchronization.
  3. * Copyright (c) 2023 Anton Khirnov
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #ifndef FFTOOLS_FFMPEG_SCHED_H
  22. #define FFTOOLS_FFMPEG_SCHED_H
  23. #include <stddef.h>
  24. #include <stdint.h>
  25. #include "ffmpeg_utils.h"
  26. /*
  27. * This file contains the API for the transcode scheduler.
  28. *
  29. * Overall architecture of the transcoding process involves instances of the
  30. * following components:
  31. * - demuxers, each containing any number of demuxed streams; demuxed packets
  32. * belonging to some stream are sent to any number of decoders (transcoding)
  33. * and/or muxers (streamcopy);
  34. * - decoders, which receive encoded packets from some demuxed stream or
  35. * encoder, decode them, and send decoded frames to any number of filtergraph
  36. * inputs (audio/video) or encoders (subtitles);
  37. * - filtergraphs, each containing zero or more inputs (0 in case the
  38. * filtergraph contains a lavfi source filter), and one or more outputs; the
  39. * inputs and outputs need not have matching media types;
  40. * each filtergraph input receives decoded frames from some decoder;
  41. * filtered frames from each output are sent to some encoder;
  42. * - encoders, which receive decoded frames from some decoder (subtitles) or
  43. * some filtergraph output (audio/video), encode them, and send encoded
  44. * packets to any number of muxed streams or decoders;
  45. * - muxers, each containing any number of muxed streams; each muxed stream
  46. * receives encoded packets from some demuxed stream (streamcopy) or some
  47. * encoder (transcoding); those packets are interleaved and written out by the
  48. * muxer.
  49. *
  50. * There must be at least one muxer instance, otherwise the transcode produces
  51. * no output and is meaningless. Otherwise, in a generic transcoding scenario
  52. * there may be arbitrary number of instances of any of the above components,
  53. * interconnected in various ways.
  54. *
  55. * The code tries to keep all the output streams across all the muxers in sync
  56. * (i.e. at the same DTS), which is accomplished by varying the rates at which
  57. * packets are read from different demuxers and lavfi sources. Note that the
  58. * degree of control we have over synchronization is fundamentally limited - if
  59. * some demuxed streams in the same input are interleaved at different rates
  60. * than that at which they are to be muxed (e.g. because an input file is badly
  61. * interleaved, or the user changed their speed by mismatching amounts), then
  62. * there will be increasing amounts of buffering followed by eventual
  63. * transcoding failure.
  64. *
  65. * N.B. 1: there are meaningful transcode scenarios with no demuxers, e.g.
  66. * - encoding and muxing output from filtergraph(s) that have no inputs;
  67. * - creating a file that contains nothing but attachments and/or metadata.
  68. *
  69. * N.B. 2: a filtergraph output could, in principle, feed multiple encoders, but
  70. * this is unnecessary because the (a)split filter provides the same
  71. * functionality.
  72. *
  73. * The scheduler, in the above model, is the master object that oversees and
  74. * facilitates the transcoding process. The basic idea is that all instances
  75. * of the abovementioned components communicate only with the scheduler and not
  76. * with each other. The scheduler is then the single place containing the
  77. * knowledge about the whole transcoding pipeline.
  78. */
  79. struct AVFrame;
  80. struct AVPacket;
  81. typedef struct Scheduler Scheduler;
  82. enum SchedulerNodeType {
  83. SCH_NODE_TYPE_NONE = 0,
  84. SCH_NODE_TYPE_DEMUX,
  85. SCH_NODE_TYPE_MUX,
  86. SCH_NODE_TYPE_DEC,
  87. SCH_NODE_TYPE_ENC,
  88. SCH_NODE_TYPE_FILTER_IN,
  89. SCH_NODE_TYPE_FILTER_OUT,
  90. };
  91. typedef struct SchedulerNode {
  92. enum SchedulerNodeType type;
  93. unsigned idx;
  94. unsigned idx_stream;
  95. } SchedulerNode;
  96. typedef int (*SchThreadFunc)(void *arg);
  97. #define SCH_DSTREAM(file, stream) \
  98. (SchedulerNode){ .type = SCH_NODE_TYPE_DEMUX, \
  99. .idx = file, .idx_stream = stream }
  100. #define SCH_MSTREAM(file, stream) \
  101. (SchedulerNode){ .type = SCH_NODE_TYPE_MUX, \
  102. .idx = file, .idx_stream = stream }
  103. #define SCH_DEC(decoder) \
  104. (SchedulerNode){ .type = SCH_NODE_TYPE_DEC, \
  105. .idx = decoder }
  106. #define SCH_ENC(encoder) \
  107. (SchedulerNode){ .type = SCH_NODE_TYPE_ENC, \
  108. .idx = encoder }
  109. #define SCH_FILTER_IN(filter, input) \
  110. (SchedulerNode){ .type = SCH_NODE_TYPE_FILTER_IN, \
  111. .idx = filter, .idx_stream = input }
  112. #define SCH_FILTER_OUT(filter, output) \
  113. (SchedulerNode){ .type = SCH_NODE_TYPE_FILTER_OUT, \
  114. .idx = filter, .idx_stream = output }
  115. Scheduler *sch_alloc(void);
  116. void sch_free(Scheduler **sch);
  117. int sch_start(Scheduler *sch);
  118. int sch_stop(Scheduler *sch, int64_t *finish_ts);
  119. /**
  120. * Wait until transcoding terminates or the specified timeout elapses.
  121. *
  122. * @param timeout_us Amount of time in microseconds after which this function
  123. * will timeout.
  124. * @param transcode_ts Current transcode timestamp in AV_TIME_BASE_Q, for
  125. * informational purposes only.
  126. *
  127. * @retval 0 waiting timed out, transcoding is not finished
  128. * @retval 1 transcoding is finished
  129. */
  130. int sch_wait(Scheduler *sch, uint64_t timeout_us, int64_t *transcode_ts);
  131. /**
  132. * Add a demuxer to the scheduler.
  133. *
  134. * @param func Function executed as the demuxer task.
  135. * @param ctx Demuxer state; will be passed to func and used for logging.
  136. *
  137. * @retval ">=0" Index of the newly-created demuxer.
  138. * @retval "<0" Error code.
  139. */
  140. int sch_add_demux(Scheduler *sch, SchThreadFunc func, void *ctx);
  141. /**
  142. * Add a demuxed stream for a previously added demuxer.
  143. *
  144. * @param demux_idx index previously returned by sch_add_demux()
  145. *
  146. * @retval ">=0" Index of the newly-created demuxed stream.
  147. * @retval "<0" Error code.
  148. */
  149. int sch_add_demux_stream(Scheduler *sch, unsigned demux_idx);
  150. /**
  151. * Add a decoder to the scheduler.
  152. *
  153. * @param func Function executed as the decoder task.
  154. * @param ctx Decoder state; will be passed to func and used for logging.
  155. * @param send_end_ts The decoder will return an end timestamp after flush packets
  156. * are delivered to it. See documentation for
  157. * sch_dec_receive() for more details.
  158. *
  159. * @retval ">=0" Index of the newly-created decoder.
  160. * @retval "<0" Error code.
  161. */
  162. int sch_add_dec(Scheduler *sch, SchThreadFunc func, void *ctx,
  163. int send_end_ts);
  164. /**
  165. * Add a filtergraph to the scheduler.
  166. *
  167. * @param nb_inputs Number of filtergraph inputs.
  168. * @param nb_outputs number of filtergraph outputs
  169. * @param func Function executed as the filtering task.
  170. * @param ctx Filter state; will be passed to func and used for logging.
  171. *
  172. * @retval ">=0" Index of the newly-created filtergraph.
  173. * @retval "<0" Error code.
  174. */
  175. int sch_add_filtergraph(Scheduler *sch, unsigned nb_inputs, unsigned nb_outputs,
  176. SchThreadFunc func, void *ctx);
  177. /**
  178. * Add a muxer to the scheduler.
  179. *
  180. * Note that muxer thread startup is more complicated than for other components,
  181. * because
  182. * - muxer streams fed by audio/video encoders become initialized dynamically at
  183. * runtime, after those encoders receive their first frame and initialize
  184. * themselves, followed by calling sch_mux_stream_ready()
  185. * - the header can be written after all the streams for a muxer are initialized
  186. * - we may need to write an SDP, which must happen
  187. * - AFTER all the headers are written
  188. * - BEFORE any packets are written by any muxer
  189. * - with all the muxers quiescent
  190. * To avoid complicated muxer-thread synchronization dances, we postpone
  191. * starting the muxer threads until after the SDP is written. The sequence of
  192. * events is then as follows:
  193. * - After sch_mux_stream_ready() is called for all the streams in a given muxer,
  194. * the header for that muxer is written (care is taken that headers for
  195. * different muxers are not written concurrently, since they write file
  196. * information to stderr). If SDP is not wanted, the muxer thread then starts
  197. * and muxing begins.
  198. * - When SDP _is_ wanted, no muxer threads start until the header for the last
  199. * muxer is written. After that, the SDP is written, after which all the muxer
  200. * threads are started at once.
  201. *
  202. * In order for the above to work, the scheduler needs to be able to invoke
  203. * just writing the header, which is the reason the init parameter exists.
  204. *
  205. * @param func Function executed as the muxing task.
  206. * @param init Callback that is called to initialize the muxer and write the
  207. * header. Called after sch_mux_stream_ready() is called for all the
  208. * streams in the muxer.
  209. * @param ctx Muxer state; will be passed to func/init and used for logging.
  210. * @param sdp_auto Determines automatic SDP writing - see sch_sdp_filename().
  211. * @param thread_queue_size number of packets that can be buffered before
  212. * sending to the muxer blocks
  213. *
  214. * @retval ">=0" Index of the newly-created muxer.
  215. * @retval "<0" Error code.
  216. */
  217. int sch_add_mux(Scheduler *sch, SchThreadFunc func, int (*init)(void *),
  218. void *ctx, int sdp_auto, unsigned thread_queue_size);
  219. /**
  220. * Default size of a packet thread queue. For muxing this can be overridden by
  221. * the thread_queue_size option as passed to a call to sch_add_mux().
  222. */
  223. #define DEFAULT_PACKET_THREAD_QUEUE_SIZE 8
  224. /**
  225. * Default size of a frame thread queue.
  226. */
  227. #define DEFAULT_FRAME_THREAD_QUEUE_SIZE 8
  228. /**
  229. * Add a muxed stream for a previously added muxer.
  230. *
  231. * @param mux_idx index previously returned by sch_add_mux()
  232. *
  233. * @retval ">=0" Index of the newly-created muxed stream.
  234. * @retval "<0" Error code.
  235. */
  236. int sch_add_mux_stream(Scheduler *sch, unsigned mux_idx);
  237. /**
  238. * Configure limits on packet buffering performed before the muxer task is
  239. * started.
  240. *
  241. * @param mux_idx index previously returned by sch_add_mux()
  242. * @param stream_idx_idx index previously returned by sch_add_mux_stream()
  243. * @param data_threshold Total size of the buffered packets' data after which
  244. * max_packets applies.
  245. * @param max_packets maximum Maximum number of buffered packets after
  246. * data_threshold is reached.
  247. */
  248. void sch_mux_stream_buffering(Scheduler *sch, unsigned mux_idx, unsigned stream_idx,
  249. size_t data_threshold, int max_packets);
  250. /**
  251. * Signal to the scheduler that the specified muxed stream is initialized and
  252. * ready. Muxing is started once all the streams are ready.
  253. */
  254. int sch_mux_stream_ready(Scheduler *sch, unsigned mux_idx, unsigned stream_idx);
  255. /**
  256. * Set the file path for the SDP.
  257. *
  258. * The SDP is written when either of the following is true:
  259. * - this function is called at least once
  260. * - sdp_auto=1 is passed to EVERY call of sch_add_mux()
  261. */
  262. int sch_sdp_filename(Scheduler *sch, const char *sdp_filename);
  263. /**
  264. * Add an encoder to the scheduler.
  265. *
  266. * @param func Function executed as the encoding task.
  267. * @param ctx Encoder state; will be passed to func and used for logging.
  268. * @param open_cb This callback, if specified, will be called when the first
  269. * frame is obtained for this encoder. For audio encoders with a
  270. * fixed frame size (which use a sync queue in the scheduler to
  271. * rechunk frames), it must return that frame size on success.
  272. * Otherwise (non-audio, variable frame size) it should return 0.
  273. *
  274. * @retval ">=0" Index of the newly-created encoder.
  275. * @retval "<0" Error code.
  276. */
  277. int sch_add_enc(Scheduler *sch, SchThreadFunc func, void *ctx,
  278. int (*open_cb)(void *func_arg, const struct AVFrame *frame));
  279. /**
  280. * Add an pre-encoding sync queue to the scheduler.
  281. *
  282. * @param buf_size_us Sync queue buffering size, passed to sq_alloc().
  283. * @param logctx Logging context for the sync queue. passed to sq_alloc().
  284. *
  285. * @retval ">=0" Index of the newly-created sync queue.
  286. * @retval "<0" Error code.
  287. */
  288. int sch_add_sq_enc(Scheduler *sch, uint64_t buf_size_us, void *logctx);
  289. int sch_sq_add_enc(Scheduler *sch, unsigned sq_idx, unsigned enc_idx,
  290. int limiting, uint64_t max_frames);
  291. int sch_connect(Scheduler *sch, SchedulerNode src, SchedulerNode dst);
  292. enum DemuxSendFlags {
  293. /**
  294. * Treat the packet as an EOF for SCH_NODE_TYPE_MUX destinations
  295. * send normally to other types.
  296. */
  297. DEMUX_SEND_STREAMCOPY_EOF = (1 << 0),
  298. };
  299. /**
  300. * Called by demuxer tasks to communicate with their downstreams. The following
  301. * may be sent:
  302. * - a demuxed packet for the stream identified by pkt->stream_index;
  303. * - demuxer discontinuity/reset (e.g. after a seek) - this is signalled by an
  304. * empty packet with stream_index=-1.
  305. *
  306. * @param demux_idx demuxer index
  307. * @param pkt A demuxed packet to send.
  308. * When flushing (i.e. pkt->stream_index=-1 on entry to this
  309. * function), on successful return pkt->pts/pkt->time_base will be
  310. * set to the maximum end timestamp of any decoded audio stream, or
  311. * AV_NOPTS_VALUE if no decoded audio streams are present.
  312. *
  313. * @retval "non-negative value" success
  314. * @retval AVERROR_EOF all consumers for the stream are done
  315. * @retval AVERROR_EXIT all consumers are done, should terminate demuxing
  316. * @retval "anoter negative error code" other failure
  317. */
  318. int sch_demux_send(Scheduler *sch, unsigned demux_idx, struct AVPacket *pkt,
  319. unsigned flags);
  320. /**
  321. * Called by decoder tasks to receive a packet for decoding.
  322. *
  323. * @param dec_idx decoder index
  324. * @param pkt Input packet will be written here on success.
  325. *
  326. * An empty packet signals that the decoder should be flushed, but
  327. * more packets will follow (e.g. after seeking). When a decoder
  328. * created with send_end_ts=1 receives a flush packet, it must write
  329. * the end timestamp of the stream after flushing to
  330. * pkt->pts/time_base on the next call to this function (if any).
  331. *
  332. * @retval "non-negative value" success
  333. * @retval AVERROR_EOF no more packets will arrive, should terminate decoding
  334. * @retval "another negative error code" other failure
  335. */
  336. int sch_dec_receive(Scheduler *sch, unsigned dec_idx, struct AVPacket *pkt);
  337. /**
  338. * Called by decoder tasks to send a decoded frame downstream.
  339. *
  340. * @param dec_idx Decoder index previously returned by sch_add_dec().
  341. * @param frame Decoded frame; on success it is consumed and cleared by this
  342. * function
  343. *
  344. * @retval ">=0" success
  345. * @retval AVERROR_EOF all consumers are done, should terminate decoding
  346. * @retval "another negative error code" other failure
  347. */
  348. int sch_dec_send(Scheduler *sch, unsigned dec_idx, struct AVFrame *frame);
  349. /**
  350. * Called by filtergraph tasks to obtain frames for filtering. Will wait for a
  351. * frame to become available and return it in frame.
  352. *
  353. * Filtergraphs that contain lavfi sources and do not currently require new
  354. * input frames should call this function as a means of rate control - then
  355. * in_idx should be set equal to nb_inputs on entry to this function.
  356. *
  357. * @param fg_idx Filtergraph index previously returned by sch_add_filtergraph().
  358. * @param[in,out] in_idx On input contains the index of the input on which a frame
  359. * is most desired. May be set to nb_inputs to signal that
  360. * the filtergraph does not need more input currently.
  361. *
  362. * On success, will be replaced with the input index of
  363. * the actually returned frame or EOF timestamp.
  364. *
  365. * @retval ">=0" Frame data or EOF timestamp was delivered into frame, in_idx
  366. * contains the index of the input it belongs to.
  367. * @retval AVERROR(EAGAIN) No frame was returned, the filtergraph should
  368. * resume filtering. May only be returned when
  369. * in_idx=nb_inputs on entry to this function.
  370. * @retval AVERROR_EOF No more frames will arrive, should terminate filtering.
  371. */
  372. int sch_filter_receive(Scheduler *sch, unsigned fg_idx,
  373. unsigned *in_idx, struct AVFrame *frame);
  374. /**
  375. * Called by filter tasks to signal that a filter input will no longer accept input.
  376. *
  377. * @param fg_idx Filtergraph index previously returned from sch_add_filtergraph().
  378. * @param in_idx Index of the input to finish.
  379. */
  380. void sch_filter_receive_finish(Scheduler *sch, unsigned fg_idx, unsigned in_idx);
  381. /**
  382. * Called by filtergraph tasks to send a filtered frame or EOF to consumers.
  383. *
  384. * @param fg_idx Filtergraph index previously returned by sch_add_filtergraph().
  385. * @param out_idx Index of the output which produced the frame.
  386. * @param frame The frame to send to consumers. When NULL, signals that no more
  387. * frames will be produced for the specified output. When non-NULL,
  388. * the frame is consumed and cleared by this function on success.
  389. *
  390. * @retval "non-negative value" success
  391. * @retval AVERROR_EOF all consumers are done
  392. * @retval "anoter negative error code" other failure
  393. */
  394. int sch_filter_send(Scheduler *sch, unsigned fg_idx, unsigned out_idx,
  395. struct AVFrame *frame);
  396. int sch_filter_command(Scheduler *sch, unsigned fg_idx, struct AVFrame *frame);
  397. /**
  398. * Called by encoder tasks to obtain frames for encoding. Will wait for a frame
  399. * to become available and return it in frame.
  400. *
  401. * @param enc_idx Encoder index previously returned by sch_add_enc().
  402. * @param frame Newly-received frame will be stored here on success. Must be
  403. * clean on entrance to this function.
  404. *
  405. * @retval 0 A frame was successfully delivered into frame.
  406. * @retval AVERROR_EOF No more frames will be delivered, the encoder should
  407. * flush everything and terminate.
  408. *
  409. */
  410. int sch_enc_receive(Scheduler *sch, unsigned enc_idx, struct AVFrame *frame);
  411. /**
  412. * Called by encoder tasks to send encoded packets downstream.
  413. *
  414. * @param enc_idx Encoder index previously returned by sch_add_enc().
  415. * @param pkt An encoded packet; it will be consumed and cleared by this
  416. * function on success.
  417. *
  418. * @retval 0 success
  419. * @retval "<0" Error code.
  420. */
  421. int sch_enc_send (Scheduler *sch, unsigned enc_idx, struct AVPacket *pkt);
  422. /**
  423. * Called by muxer tasks to obtain packets for muxing. Will wait for a packet
  424. * for any muxed stream to become available and return it in pkt.
  425. *
  426. * @param mux_idx Muxer index previously returned by sch_add_mux().
  427. * @param pkt Newly-received packet will be stored here on success. Must be
  428. * clean on entrance to this function.
  429. *
  430. * @retval 0 A packet was successfully delivered into pkt. Its stream_index
  431. * corresponds to a stream index previously returned from
  432. * sch_add_mux_stream().
  433. * @retval AVERROR_EOF When pkt->stream_index is non-negative, this signals that
  434. * no more packets will be delivered for this stream index.
  435. * Otherwise this indicates that no more packets will be
  436. * delivered for any stream and the muxer should therefore
  437. * flush everything and terminate.
  438. */
  439. int sch_mux_receive(Scheduler *sch, unsigned mux_idx, struct AVPacket *pkt);
  440. /**
  441. * Called by muxer tasks to signal that a stream will no longer accept input.
  442. *
  443. * @param stream_idx Stream index previously returned from sch_add_mux_stream().
  444. */
  445. void sch_mux_receive_finish(Scheduler *sch, unsigned mux_idx, unsigned stream_idx);
  446. int sch_mux_sub_heartbeat_add(Scheduler *sch, unsigned mux_idx, unsigned stream_idx,
  447. unsigned dec_idx);
  448. int sch_mux_sub_heartbeat(Scheduler *sch, unsigned mux_idx, unsigned stream_idx,
  449. const AVPacket *pkt);
  450. #endif /* FFTOOLS_FFMPEG_SCHED_H */