ffmpeg_sched.c 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559
  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. #include <stdatomic.h>
  22. #include <stddef.h>
  23. #include <stdint.h>
  24. #include "cmdutils.h"
  25. #include "ffmpeg_sched.h"
  26. #include "ffmpeg_utils.h"
  27. #include "sync_queue.h"
  28. #include "thread_queue.h"
  29. #include "libavcodec/packet.h"
  30. #include "libavutil/avassert.h"
  31. #include "libavutil/error.h"
  32. #include "libavutil/fifo.h"
  33. #include "libavutil/frame.h"
  34. #include "libavutil/mem.h"
  35. #include "libavutil/thread.h"
  36. #include "libavutil/threadmessage.h"
  37. #include "libavutil/time.h"
  38. // 100 ms
  39. // FIXME: some other value? make this dynamic?
  40. #define SCHEDULE_TOLERANCE (100 * 1000)
  41. enum QueueType {
  42. QUEUE_PACKETS,
  43. QUEUE_FRAMES,
  44. };
  45. typedef struct SchWaiter {
  46. pthread_mutex_t lock;
  47. pthread_cond_t cond;
  48. atomic_int choked;
  49. // the following are internal state of schedule_update_locked() and must not
  50. // be accessed outside of it
  51. int choked_prev;
  52. int choked_next;
  53. } SchWaiter;
  54. typedef struct SchTask {
  55. Scheduler *parent;
  56. SchedulerNode node;
  57. SchThreadFunc func;
  58. void *func_arg;
  59. pthread_t thread;
  60. int thread_running;
  61. } SchTask;
  62. typedef struct SchDec {
  63. const AVClass *class;
  64. SchedulerNode src;
  65. SchedulerNode *dst;
  66. uint8_t *dst_finished;
  67. unsigned nb_dst;
  68. SchTask task;
  69. // Queue for receiving input packets, one stream.
  70. ThreadQueue *queue;
  71. // Queue for sending post-flush end timestamps back to the source
  72. AVThreadMessageQueue *queue_end_ts;
  73. int expect_end_ts;
  74. // temporary storage used by sch_dec_send()
  75. AVFrame *send_frame;
  76. } SchDec;
  77. typedef struct SchSyncQueue {
  78. SyncQueue *sq;
  79. AVFrame *frame;
  80. pthread_mutex_t lock;
  81. unsigned *enc_idx;
  82. unsigned nb_enc_idx;
  83. } SchSyncQueue;
  84. typedef struct SchEnc {
  85. const AVClass *class;
  86. SchedulerNode src;
  87. SchedulerNode *dst;
  88. uint8_t *dst_finished;
  89. unsigned nb_dst;
  90. // [0] - index of the sync queue in Scheduler.sq_enc,
  91. // [1] - index of this encoder in the sq
  92. int sq_idx[2];
  93. /* Opening encoders is somewhat nontrivial due to their interaction with
  94. * sync queues, which are (among other things) responsible for maintaining
  95. * constant audio frame size, when it is required by the encoder.
  96. *
  97. * Opening the encoder requires stream parameters, obtained from the first
  98. * frame. However, that frame cannot be properly chunked by the sync queue
  99. * without knowing the required frame size, which is only available after
  100. * opening the encoder.
  101. *
  102. * This apparent circular dependency is resolved in the following way:
  103. * - the caller creating the encoder gives us a callback which opens the
  104. * encoder and returns the required frame size (if any)
  105. * - when the first frame is sent to the encoder, the sending thread
  106. * - calls this callback, opening the encoder
  107. * - passes the returned frame size to the sync queue
  108. */
  109. int (*open_cb)(void *opaque, const AVFrame *frame);
  110. int opened;
  111. SchTask task;
  112. // Queue for receiving input frames, one stream.
  113. ThreadQueue *queue;
  114. // tq_send() to queue returned EOF
  115. int in_finished;
  116. // temporary storage used by sch_enc_send()
  117. AVPacket *send_pkt;
  118. } SchEnc;
  119. typedef struct SchDemuxStream {
  120. SchedulerNode *dst;
  121. uint8_t *dst_finished;
  122. unsigned nb_dst;
  123. } SchDemuxStream;
  124. typedef struct SchDemux {
  125. const AVClass *class;
  126. SchDemuxStream *streams;
  127. unsigned nb_streams;
  128. SchTask task;
  129. SchWaiter waiter;
  130. // temporary storage used by sch_demux_send()
  131. AVPacket *send_pkt;
  132. // protected by schedule_lock
  133. int task_exited;
  134. } SchDemux;
  135. typedef struct PreMuxQueue {
  136. /**
  137. * Queue for buffering the packets before the muxer task can be started.
  138. */
  139. AVFifo *fifo;
  140. /**
  141. * Maximum number of packets in fifo.
  142. */
  143. int max_packets;
  144. /*
  145. * The size of the AVPackets' buffers in queue.
  146. * Updated when a packet is either pushed or pulled from the queue.
  147. */
  148. size_t data_size;
  149. /* Threshold after which max_packets will be in effect */
  150. size_t data_threshold;
  151. } PreMuxQueue;
  152. typedef struct SchMuxStream {
  153. SchedulerNode src;
  154. SchedulerNode src_sched;
  155. unsigned *sub_heartbeat_dst;
  156. unsigned nb_sub_heartbeat_dst;
  157. PreMuxQueue pre_mux_queue;
  158. // an EOF was generated while flushing the pre-mux queue
  159. int init_eof;
  160. ////////////////////////////////////////////////////////////
  161. // The following are protected by Scheduler.schedule_lock //
  162. /* dts+duration of the last packet sent to this stream
  163. in AV_TIME_BASE_Q */
  164. int64_t last_dts;
  165. // this stream no longer accepts input
  166. int source_finished;
  167. ////////////////////////////////////////////////////////////
  168. } SchMuxStream;
  169. typedef struct SchMux {
  170. const AVClass *class;
  171. SchMuxStream *streams;
  172. unsigned nb_streams;
  173. unsigned nb_streams_ready;
  174. int (*init)(void *arg);
  175. SchTask task;
  176. /**
  177. * Set to 1 after starting the muxer task and flushing the
  178. * pre-muxing queues.
  179. * Set either before any tasks have started, or with
  180. * Scheduler.mux_ready_lock held.
  181. */
  182. atomic_int mux_started;
  183. ThreadQueue *queue;
  184. unsigned queue_size;
  185. AVPacket *sub_heartbeat_pkt;
  186. } SchMux;
  187. typedef struct SchFilterIn {
  188. SchedulerNode src;
  189. SchedulerNode src_sched;
  190. int send_finished;
  191. int receive_finished;
  192. } SchFilterIn;
  193. typedef struct SchFilterOut {
  194. SchedulerNode dst;
  195. } SchFilterOut;
  196. typedef struct SchFilterGraph {
  197. const AVClass *class;
  198. SchFilterIn *inputs;
  199. unsigned nb_inputs;
  200. atomic_uint nb_inputs_finished_send;
  201. unsigned nb_inputs_finished_receive;
  202. SchFilterOut *outputs;
  203. unsigned nb_outputs;
  204. SchTask task;
  205. // input queue, nb_inputs+1 streams
  206. // last stream is control
  207. ThreadQueue *queue;
  208. SchWaiter waiter;
  209. // protected by schedule_lock
  210. unsigned best_input;
  211. int task_exited;
  212. } SchFilterGraph;
  213. enum SchedulerState {
  214. SCH_STATE_UNINIT,
  215. SCH_STATE_STARTED,
  216. SCH_STATE_STOPPED,
  217. };
  218. struct Scheduler {
  219. const AVClass *class;
  220. SchDemux *demux;
  221. unsigned nb_demux;
  222. SchMux *mux;
  223. unsigned nb_mux;
  224. unsigned nb_mux_ready;
  225. pthread_mutex_t mux_ready_lock;
  226. unsigned nb_mux_done;
  227. pthread_mutex_t mux_done_lock;
  228. pthread_cond_t mux_done_cond;
  229. SchDec *dec;
  230. unsigned nb_dec;
  231. SchEnc *enc;
  232. unsigned nb_enc;
  233. SchSyncQueue *sq_enc;
  234. unsigned nb_sq_enc;
  235. SchFilterGraph *filters;
  236. unsigned nb_filters;
  237. char *sdp_filename;
  238. int sdp_auto;
  239. enum SchedulerState state;
  240. atomic_int terminate;
  241. atomic_int task_failed;
  242. pthread_mutex_t schedule_lock;
  243. atomic_int_least64_t last_dts;
  244. };
  245. /**
  246. * Wait until this task is allowed to proceed.
  247. *
  248. * @retval 0 the caller should proceed
  249. * @retval 1 the caller should terminate
  250. */
  251. static int waiter_wait(Scheduler *sch, SchWaiter *w)
  252. {
  253. int terminate;
  254. if (!atomic_load(&w->choked))
  255. return 0;
  256. pthread_mutex_lock(&w->lock);
  257. while (atomic_load(&w->choked) && !atomic_load(&sch->terminate))
  258. pthread_cond_wait(&w->cond, &w->lock);
  259. terminate = atomic_load(&sch->terminate);
  260. pthread_mutex_unlock(&w->lock);
  261. return terminate;
  262. }
  263. static void waiter_set(SchWaiter *w, int choked)
  264. {
  265. pthread_mutex_lock(&w->lock);
  266. atomic_store(&w->choked, choked);
  267. pthread_cond_signal(&w->cond);
  268. pthread_mutex_unlock(&w->lock);
  269. }
  270. static int waiter_init(SchWaiter *w)
  271. {
  272. int ret;
  273. atomic_init(&w->choked, 0);
  274. ret = pthread_mutex_init(&w->lock, NULL);
  275. if (ret)
  276. return AVERROR(ret);
  277. ret = pthread_cond_init(&w->cond, NULL);
  278. if (ret)
  279. return AVERROR(ret);
  280. return 0;
  281. }
  282. static void waiter_uninit(SchWaiter *w)
  283. {
  284. pthread_mutex_destroy(&w->lock);
  285. pthread_cond_destroy(&w->cond);
  286. }
  287. static int queue_alloc(ThreadQueue **ptq, unsigned nb_streams, unsigned queue_size,
  288. enum QueueType type)
  289. {
  290. ThreadQueue *tq;
  291. ObjPool *op;
  292. if (queue_size <= 0) {
  293. if (type == QUEUE_FRAMES)
  294. queue_size = DEFAULT_FRAME_THREAD_QUEUE_SIZE;
  295. else
  296. queue_size = DEFAULT_PACKET_THREAD_QUEUE_SIZE;
  297. }
  298. if (type == QUEUE_FRAMES) {
  299. // This queue length is used in the decoder code to ensure that
  300. // there are enough entries in fixed-size frame pools to account
  301. // for frames held in queues inside the ffmpeg utility. If this
  302. // can ever dynamically change then the corresponding decode
  303. // code needs to be updated as well.
  304. av_assert0(queue_size == DEFAULT_FRAME_THREAD_QUEUE_SIZE);
  305. }
  306. op = (type == QUEUE_PACKETS) ? objpool_alloc_packets() :
  307. objpool_alloc_frames();
  308. if (!op)
  309. return AVERROR(ENOMEM);
  310. tq = tq_alloc(nb_streams, queue_size, op,
  311. (type == QUEUE_PACKETS) ? pkt_move : frame_move);
  312. if (!tq) {
  313. objpool_free(&op);
  314. return AVERROR(ENOMEM);
  315. }
  316. *ptq = tq;
  317. return 0;
  318. }
  319. static void *task_wrapper(void *arg);
  320. static int task_start(SchTask *task)
  321. {
  322. int ret;
  323. av_log(task->func_arg, AV_LOG_VERBOSE, "Starting thread...\n");
  324. av_assert0(!task->thread_running);
  325. ret = pthread_create(&task->thread, NULL, task_wrapper, task);
  326. if (ret) {
  327. av_log(task->func_arg, AV_LOG_ERROR, "pthread_create() failed: %s\n",
  328. strerror(ret));
  329. return AVERROR(ret);
  330. }
  331. task->thread_running = 1;
  332. return 0;
  333. }
  334. static void task_init(Scheduler *sch, SchTask *task, enum SchedulerNodeType type, unsigned idx,
  335. SchThreadFunc func, void *func_arg)
  336. {
  337. task->parent = sch;
  338. task->node.type = type;
  339. task->node.idx = idx;
  340. task->func = func;
  341. task->func_arg = func_arg;
  342. }
  343. static int64_t trailing_dts(const Scheduler *sch, int count_finished)
  344. {
  345. int64_t min_dts = INT64_MAX;
  346. for (unsigned i = 0; i < sch->nb_mux; i++) {
  347. const SchMux *mux = &sch->mux[i];
  348. for (unsigned j = 0; j < mux->nb_streams; j++) {
  349. const SchMuxStream *ms = &mux->streams[j];
  350. if (ms->source_finished && !count_finished)
  351. continue;
  352. if (ms->last_dts == AV_NOPTS_VALUE)
  353. return AV_NOPTS_VALUE;
  354. min_dts = FFMIN(min_dts, ms->last_dts);
  355. }
  356. }
  357. return min_dts == INT64_MAX ? AV_NOPTS_VALUE : min_dts;
  358. }
  359. void sch_free(Scheduler **psch)
  360. {
  361. Scheduler *sch = *psch;
  362. if (!sch)
  363. return;
  364. sch_stop(sch, NULL);
  365. for (unsigned i = 0; i < sch->nb_demux; i++) {
  366. SchDemux *d = &sch->demux[i];
  367. for (unsigned j = 0; j < d->nb_streams; j++) {
  368. SchDemuxStream *ds = &d->streams[j];
  369. av_freep(&ds->dst);
  370. av_freep(&ds->dst_finished);
  371. }
  372. av_freep(&d->streams);
  373. av_packet_free(&d->send_pkt);
  374. waiter_uninit(&d->waiter);
  375. }
  376. av_freep(&sch->demux);
  377. for (unsigned i = 0; i < sch->nb_mux; i++) {
  378. SchMux *mux = &sch->mux[i];
  379. for (unsigned j = 0; j < mux->nb_streams; j++) {
  380. SchMuxStream *ms = &mux->streams[j];
  381. if (ms->pre_mux_queue.fifo) {
  382. AVPacket *pkt;
  383. while (av_fifo_read(ms->pre_mux_queue.fifo, &pkt, 1) >= 0)
  384. av_packet_free(&pkt);
  385. av_fifo_freep2(&ms->pre_mux_queue.fifo);
  386. }
  387. av_freep(&ms->sub_heartbeat_dst);
  388. }
  389. av_freep(&mux->streams);
  390. av_packet_free(&mux->sub_heartbeat_pkt);
  391. tq_free(&mux->queue);
  392. }
  393. av_freep(&sch->mux);
  394. for (unsigned i = 0; i < sch->nb_dec; i++) {
  395. SchDec *dec = &sch->dec[i];
  396. tq_free(&dec->queue);
  397. av_thread_message_queue_free(&dec->queue_end_ts);
  398. av_freep(&dec->dst);
  399. av_freep(&dec->dst_finished);
  400. av_frame_free(&dec->send_frame);
  401. }
  402. av_freep(&sch->dec);
  403. for (unsigned i = 0; i < sch->nb_enc; i++) {
  404. SchEnc *enc = &sch->enc[i];
  405. tq_free(&enc->queue);
  406. av_packet_free(&enc->send_pkt);
  407. av_freep(&enc->dst);
  408. av_freep(&enc->dst_finished);
  409. }
  410. av_freep(&sch->enc);
  411. for (unsigned i = 0; i < sch->nb_sq_enc; i++) {
  412. SchSyncQueue *sq = &sch->sq_enc[i];
  413. sq_free(&sq->sq);
  414. av_frame_free(&sq->frame);
  415. pthread_mutex_destroy(&sq->lock);
  416. av_freep(&sq->enc_idx);
  417. }
  418. av_freep(&sch->sq_enc);
  419. for (unsigned i = 0; i < sch->nb_filters; i++) {
  420. SchFilterGraph *fg = &sch->filters[i];
  421. tq_free(&fg->queue);
  422. av_freep(&fg->inputs);
  423. av_freep(&fg->outputs);
  424. waiter_uninit(&fg->waiter);
  425. }
  426. av_freep(&sch->filters);
  427. av_freep(&sch->sdp_filename);
  428. pthread_mutex_destroy(&sch->schedule_lock);
  429. pthread_mutex_destroy(&sch->mux_ready_lock);
  430. pthread_mutex_destroy(&sch->mux_done_lock);
  431. pthread_cond_destroy(&sch->mux_done_cond);
  432. av_freep(psch);
  433. }
  434. static const AVClass scheduler_class = {
  435. .class_name = "Scheduler",
  436. .version = LIBAVUTIL_VERSION_INT,
  437. };
  438. Scheduler *sch_alloc(void)
  439. {
  440. Scheduler *sch;
  441. int ret;
  442. sch = av_mallocz(sizeof(*sch));
  443. if (!sch)
  444. return NULL;
  445. sch->class = &scheduler_class;
  446. sch->sdp_auto = 1;
  447. ret = pthread_mutex_init(&sch->schedule_lock, NULL);
  448. if (ret)
  449. goto fail;
  450. ret = pthread_mutex_init(&sch->mux_ready_lock, NULL);
  451. if (ret)
  452. goto fail;
  453. ret = pthread_mutex_init(&sch->mux_done_lock, NULL);
  454. if (ret)
  455. goto fail;
  456. ret = pthread_cond_init(&sch->mux_done_cond, NULL);
  457. if (ret)
  458. goto fail;
  459. return sch;
  460. fail:
  461. sch_free(&sch);
  462. return NULL;
  463. }
  464. int sch_sdp_filename(Scheduler *sch, const char *sdp_filename)
  465. {
  466. av_freep(&sch->sdp_filename);
  467. sch->sdp_filename = av_strdup(sdp_filename);
  468. return sch->sdp_filename ? 0 : AVERROR(ENOMEM);
  469. }
  470. static const AVClass sch_mux_class = {
  471. .class_name = "SchMux",
  472. .version = LIBAVUTIL_VERSION_INT,
  473. .parent_log_context_offset = offsetof(SchMux, task.func_arg),
  474. };
  475. int sch_add_mux(Scheduler *sch, SchThreadFunc func, int (*init)(void *),
  476. void *arg, int sdp_auto, unsigned thread_queue_size)
  477. {
  478. const unsigned idx = sch->nb_mux;
  479. SchMux *mux;
  480. int ret;
  481. ret = GROW_ARRAY(sch->mux, sch->nb_mux);
  482. if (ret < 0)
  483. return ret;
  484. mux = &sch->mux[idx];
  485. mux->class = &sch_mux_class;
  486. mux->init = init;
  487. mux->queue_size = thread_queue_size;
  488. task_init(sch, &mux->task, SCH_NODE_TYPE_MUX, idx, func, arg);
  489. sch->sdp_auto &= sdp_auto;
  490. return idx;
  491. }
  492. int sch_add_mux_stream(Scheduler *sch, unsigned mux_idx)
  493. {
  494. SchMux *mux;
  495. SchMuxStream *ms;
  496. unsigned stream_idx;
  497. int ret;
  498. av_assert0(mux_idx < sch->nb_mux);
  499. mux = &sch->mux[mux_idx];
  500. ret = GROW_ARRAY(mux->streams, mux->nb_streams);
  501. if (ret < 0)
  502. return ret;
  503. stream_idx = mux->nb_streams - 1;
  504. ms = &mux->streams[stream_idx];
  505. ms->pre_mux_queue.fifo = av_fifo_alloc2(8, sizeof(AVPacket*), 0);
  506. if (!ms->pre_mux_queue.fifo)
  507. return AVERROR(ENOMEM);
  508. ms->last_dts = AV_NOPTS_VALUE;
  509. return stream_idx;
  510. }
  511. static const AVClass sch_demux_class = {
  512. .class_name = "SchDemux",
  513. .version = LIBAVUTIL_VERSION_INT,
  514. .parent_log_context_offset = offsetof(SchDemux, task.func_arg),
  515. };
  516. int sch_add_demux(Scheduler *sch, SchThreadFunc func, void *ctx)
  517. {
  518. const unsigned idx = sch->nb_demux;
  519. SchDemux *d;
  520. int ret;
  521. ret = GROW_ARRAY(sch->demux, sch->nb_demux);
  522. if (ret < 0)
  523. return ret;
  524. d = &sch->demux[idx];
  525. task_init(sch, &d->task, SCH_NODE_TYPE_DEMUX, idx, func, ctx);
  526. d->class = &sch_demux_class;
  527. d->send_pkt = av_packet_alloc();
  528. if (!d->send_pkt)
  529. return AVERROR(ENOMEM);
  530. ret = waiter_init(&d->waiter);
  531. if (ret < 0)
  532. return ret;
  533. return idx;
  534. }
  535. int sch_add_demux_stream(Scheduler *sch, unsigned demux_idx)
  536. {
  537. SchDemux *d;
  538. int ret;
  539. av_assert0(demux_idx < sch->nb_demux);
  540. d = &sch->demux[demux_idx];
  541. ret = GROW_ARRAY(d->streams, d->nb_streams);
  542. return ret < 0 ? ret : d->nb_streams - 1;
  543. }
  544. static const AVClass sch_dec_class = {
  545. .class_name = "SchDec",
  546. .version = LIBAVUTIL_VERSION_INT,
  547. .parent_log_context_offset = offsetof(SchDec, task.func_arg),
  548. };
  549. int sch_add_dec(Scheduler *sch, SchThreadFunc func, void *ctx,
  550. int send_end_ts)
  551. {
  552. const unsigned idx = sch->nb_dec;
  553. SchDec *dec;
  554. int ret;
  555. ret = GROW_ARRAY(sch->dec, sch->nb_dec);
  556. if (ret < 0)
  557. return ret;
  558. dec = &sch->dec[idx];
  559. task_init(sch, &dec->task, SCH_NODE_TYPE_DEC, idx, func, ctx);
  560. dec->class = &sch_dec_class;
  561. dec->send_frame = av_frame_alloc();
  562. if (!dec->send_frame)
  563. return AVERROR(ENOMEM);
  564. ret = queue_alloc(&dec->queue, 1, 0, QUEUE_PACKETS);
  565. if (ret < 0)
  566. return ret;
  567. if (send_end_ts) {
  568. ret = av_thread_message_queue_alloc(&dec->queue_end_ts, 1, sizeof(Timestamp));
  569. if (ret < 0)
  570. return ret;
  571. }
  572. return idx;
  573. }
  574. static const AVClass sch_enc_class = {
  575. .class_name = "SchEnc",
  576. .version = LIBAVUTIL_VERSION_INT,
  577. .parent_log_context_offset = offsetof(SchEnc, task.func_arg),
  578. };
  579. int sch_add_enc(Scheduler *sch, SchThreadFunc func, void *ctx,
  580. int (*open_cb)(void *opaque, const AVFrame *frame))
  581. {
  582. const unsigned idx = sch->nb_enc;
  583. SchEnc *enc;
  584. int ret;
  585. ret = GROW_ARRAY(sch->enc, sch->nb_enc);
  586. if (ret < 0)
  587. return ret;
  588. enc = &sch->enc[idx];
  589. enc->class = &sch_enc_class;
  590. enc->open_cb = open_cb;
  591. enc->sq_idx[0] = -1;
  592. enc->sq_idx[1] = -1;
  593. task_init(sch, &enc->task, SCH_NODE_TYPE_ENC, idx, func, ctx);
  594. enc->send_pkt = av_packet_alloc();
  595. if (!enc->send_pkt)
  596. return AVERROR(ENOMEM);
  597. ret = queue_alloc(&enc->queue, 1, 0, QUEUE_FRAMES);
  598. if (ret < 0)
  599. return ret;
  600. return idx;
  601. }
  602. static const AVClass sch_fg_class = {
  603. .class_name = "SchFilterGraph",
  604. .version = LIBAVUTIL_VERSION_INT,
  605. .parent_log_context_offset = offsetof(SchFilterGraph, task.func_arg),
  606. };
  607. int sch_add_filtergraph(Scheduler *sch, unsigned nb_inputs, unsigned nb_outputs,
  608. SchThreadFunc func, void *ctx)
  609. {
  610. const unsigned idx = sch->nb_filters;
  611. SchFilterGraph *fg;
  612. int ret;
  613. ret = GROW_ARRAY(sch->filters, sch->nb_filters);
  614. if (ret < 0)
  615. return ret;
  616. fg = &sch->filters[idx];
  617. fg->class = &sch_fg_class;
  618. task_init(sch, &fg->task, SCH_NODE_TYPE_FILTER_IN, idx, func, ctx);
  619. if (nb_inputs) {
  620. fg->inputs = av_calloc(nb_inputs, sizeof(*fg->inputs));
  621. if (!fg->inputs)
  622. return AVERROR(ENOMEM);
  623. fg->nb_inputs = nb_inputs;
  624. }
  625. if (nb_outputs) {
  626. fg->outputs = av_calloc(nb_outputs, sizeof(*fg->outputs));
  627. if (!fg->outputs)
  628. return AVERROR(ENOMEM);
  629. fg->nb_outputs = nb_outputs;
  630. }
  631. ret = waiter_init(&fg->waiter);
  632. if (ret < 0)
  633. return ret;
  634. ret = queue_alloc(&fg->queue, fg->nb_inputs + 1, 0, QUEUE_FRAMES);
  635. if (ret < 0)
  636. return ret;
  637. return idx;
  638. }
  639. int sch_add_sq_enc(Scheduler *sch, uint64_t buf_size_us, void *logctx)
  640. {
  641. SchSyncQueue *sq;
  642. int ret;
  643. ret = GROW_ARRAY(sch->sq_enc, sch->nb_sq_enc);
  644. if (ret < 0)
  645. return ret;
  646. sq = &sch->sq_enc[sch->nb_sq_enc - 1];
  647. sq->sq = sq_alloc(SYNC_QUEUE_FRAMES, buf_size_us, logctx);
  648. if (!sq->sq)
  649. return AVERROR(ENOMEM);
  650. sq->frame = av_frame_alloc();
  651. if (!sq->frame)
  652. return AVERROR(ENOMEM);
  653. ret = pthread_mutex_init(&sq->lock, NULL);
  654. if (ret)
  655. return AVERROR(ret);
  656. return sq - sch->sq_enc;
  657. }
  658. int sch_sq_add_enc(Scheduler *sch, unsigned sq_idx, unsigned enc_idx,
  659. int limiting, uint64_t max_frames)
  660. {
  661. SchSyncQueue *sq;
  662. SchEnc *enc;
  663. int ret;
  664. av_assert0(sq_idx < sch->nb_sq_enc);
  665. sq = &sch->sq_enc[sq_idx];
  666. av_assert0(enc_idx < sch->nb_enc);
  667. enc = &sch->enc[enc_idx];
  668. ret = GROW_ARRAY(sq->enc_idx, sq->nb_enc_idx);
  669. if (ret < 0)
  670. return ret;
  671. sq->enc_idx[sq->nb_enc_idx - 1] = enc_idx;
  672. ret = sq_add_stream(sq->sq, limiting);
  673. if (ret < 0)
  674. return ret;
  675. enc->sq_idx[0] = sq_idx;
  676. enc->sq_idx[1] = ret;
  677. if (max_frames != INT64_MAX)
  678. sq_limit_frames(sq->sq, enc->sq_idx[1], max_frames);
  679. return 0;
  680. }
  681. int sch_connect(Scheduler *sch, SchedulerNode src, SchedulerNode dst)
  682. {
  683. int ret;
  684. switch (src.type) {
  685. case SCH_NODE_TYPE_DEMUX: {
  686. SchDemuxStream *ds;
  687. av_assert0(src.idx < sch->nb_demux &&
  688. src.idx_stream < sch->demux[src.idx].nb_streams);
  689. ds = &sch->demux[src.idx].streams[src.idx_stream];
  690. ret = GROW_ARRAY(ds->dst, ds->nb_dst);
  691. if (ret < 0)
  692. return ret;
  693. ds->dst[ds->nb_dst - 1] = dst;
  694. // demuxed packets go to decoding or streamcopy
  695. switch (dst.type) {
  696. case SCH_NODE_TYPE_DEC: {
  697. SchDec *dec;
  698. av_assert0(dst.idx < sch->nb_dec);
  699. dec = &sch->dec[dst.idx];
  700. av_assert0(!dec->src.type);
  701. dec->src = src;
  702. break;
  703. }
  704. case SCH_NODE_TYPE_MUX: {
  705. SchMuxStream *ms;
  706. av_assert0(dst.idx < sch->nb_mux &&
  707. dst.idx_stream < sch->mux[dst.idx].nb_streams);
  708. ms = &sch->mux[dst.idx].streams[dst.idx_stream];
  709. av_assert0(!ms->src.type);
  710. ms->src = src;
  711. break;
  712. }
  713. default: av_assert0(0);
  714. }
  715. break;
  716. }
  717. case SCH_NODE_TYPE_DEC: {
  718. SchDec *dec;
  719. av_assert0(src.idx < sch->nb_dec);
  720. dec = &sch->dec[src.idx];
  721. ret = GROW_ARRAY(dec->dst, dec->nb_dst);
  722. if (ret < 0)
  723. return ret;
  724. dec->dst[dec->nb_dst - 1] = dst;
  725. // decoded frames go to filters or encoding
  726. switch (dst.type) {
  727. case SCH_NODE_TYPE_FILTER_IN: {
  728. SchFilterIn *fi;
  729. av_assert0(dst.idx < sch->nb_filters &&
  730. dst.idx_stream < sch->filters[dst.idx].nb_inputs);
  731. fi = &sch->filters[dst.idx].inputs[dst.idx_stream];
  732. av_assert0(!fi->src.type);
  733. fi->src = src;
  734. break;
  735. }
  736. case SCH_NODE_TYPE_ENC: {
  737. SchEnc *enc;
  738. av_assert0(dst.idx < sch->nb_enc);
  739. enc = &sch->enc[dst.idx];
  740. av_assert0(!enc->src.type);
  741. enc->src = src;
  742. break;
  743. }
  744. default: av_assert0(0);
  745. }
  746. break;
  747. }
  748. case SCH_NODE_TYPE_FILTER_OUT: {
  749. SchFilterOut *fo;
  750. av_assert0(src.idx < sch->nb_filters &&
  751. src.idx_stream < sch->filters[src.idx].nb_outputs);
  752. fo = &sch->filters[src.idx].outputs[src.idx_stream];
  753. av_assert0(!fo->dst.type);
  754. fo->dst = dst;
  755. // filtered frames go to encoding or another filtergraph
  756. switch (dst.type) {
  757. case SCH_NODE_TYPE_ENC: {
  758. SchEnc *enc;
  759. av_assert0(dst.idx < sch->nb_enc);
  760. enc = &sch->enc[dst.idx];
  761. av_assert0(!enc->src.type);
  762. enc->src = src;
  763. break;
  764. }
  765. case SCH_NODE_TYPE_FILTER_IN: {
  766. SchFilterIn *fi;
  767. av_assert0(dst.idx < sch->nb_filters &&
  768. dst.idx_stream < sch->filters[dst.idx].nb_inputs);
  769. fi = &sch->filters[dst.idx].inputs[dst.idx_stream];
  770. av_assert0(!fi->src.type);
  771. fi->src = src;
  772. break;
  773. }
  774. default: av_assert0(0);
  775. }
  776. break;
  777. }
  778. case SCH_NODE_TYPE_ENC: {
  779. SchEnc *enc;
  780. av_assert0(src.idx < sch->nb_enc);
  781. enc = &sch->enc[src.idx];
  782. ret = GROW_ARRAY(enc->dst, enc->nb_dst);
  783. if (ret < 0)
  784. return ret;
  785. enc->dst[enc->nb_dst - 1] = dst;
  786. // encoding packets go to muxing or decoding
  787. switch (dst.type) {
  788. case SCH_NODE_TYPE_MUX: {
  789. SchMuxStream *ms;
  790. av_assert0(dst.idx < sch->nb_mux &&
  791. dst.idx_stream < sch->mux[dst.idx].nb_streams);
  792. ms = &sch->mux[dst.idx].streams[dst.idx_stream];
  793. av_assert0(!ms->src.type);
  794. ms->src = src;
  795. break;
  796. }
  797. case SCH_NODE_TYPE_DEC: {
  798. SchDec *dec;
  799. av_assert0(dst.idx < sch->nb_dec);
  800. dec = &sch->dec[dst.idx];
  801. av_assert0(!dec->src.type);
  802. dec->src = src;
  803. break;
  804. }
  805. default: av_assert0(0);
  806. }
  807. break;
  808. }
  809. default: av_assert0(0);
  810. }
  811. return 0;
  812. }
  813. static int mux_task_start(SchMux *mux)
  814. {
  815. int ret = 0;
  816. ret = task_start(&mux->task);
  817. if (ret < 0)
  818. return ret;
  819. /* flush the pre-muxing queues */
  820. for (unsigned i = 0; i < mux->nb_streams; i++) {
  821. SchMuxStream *ms = &mux->streams[i];
  822. AVPacket *pkt;
  823. while (av_fifo_read(ms->pre_mux_queue.fifo, &pkt, 1) >= 0) {
  824. if (pkt) {
  825. if (!ms->init_eof)
  826. ret = tq_send(mux->queue, i, pkt);
  827. av_packet_free(&pkt);
  828. if (ret == AVERROR_EOF)
  829. ms->init_eof = 1;
  830. else if (ret < 0)
  831. return ret;
  832. } else
  833. tq_send_finish(mux->queue, i);
  834. }
  835. }
  836. atomic_store(&mux->mux_started, 1);
  837. return 0;
  838. }
  839. int print_sdp(const char *filename);
  840. static int mux_init(Scheduler *sch, SchMux *mux)
  841. {
  842. int ret;
  843. ret = mux->init(mux->task.func_arg);
  844. if (ret < 0)
  845. return ret;
  846. sch->nb_mux_ready++;
  847. if (sch->sdp_filename || sch->sdp_auto) {
  848. if (sch->nb_mux_ready < sch->nb_mux)
  849. return 0;
  850. ret = print_sdp(sch->sdp_filename);
  851. if (ret < 0) {
  852. av_log(sch, AV_LOG_ERROR, "Error writing the SDP.\n");
  853. return ret;
  854. }
  855. /* SDP is written only after all the muxers are ready, so now we
  856. * start ALL the threads */
  857. for (unsigned i = 0; i < sch->nb_mux; i++) {
  858. ret = mux_task_start(&sch->mux[i]);
  859. if (ret < 0)
  860. return ret;
  861. }
  862. } else {
  863. ret = mux_task_start(mux);
  864. if (ret < 0)
  865. return ret;
  866. }
  867. return 0;
  868. }
  869. void sch_mux_stream_buffering(Scheduler *sch, unsigned mux_idx, unsigned stream_idx,
  870. size_t data_threshold, int max_packets)
  871. {
  872. SchMux *mux;
  873. SchMuxStream *ms;
  874. av_assert0(mux_idx < sch->nb_mux);
  875. mux = &sch->mux[mux_idx];
  876. av_assert0(stream_idx < mux->nb_streams);
  877. ms = &mux->streams[stream_idx];
  878. ms->pre_mux_queue.max_packets = max_packets;
  879. ms->pre_mux_queue.data_threshold = data_threshold;
  880. }
  881. int sch_mux_stream_ready(Scheduler *sch, unsigned mux_idx, unsigned stream_idx)
  882. {
  883. SchMux *mux;
  884. int ret = 0;
  885. av_assert0(mux_idx < sch->nb_mux);
  886. mux = &sch->mux[mux_idx];
  887. av_assert0(stream_idx < mux->nb_streams);
  888. pthread_mutex_lock(&sch->mux_ready_lock);
  889. av_assert0(mux->nb_streams_ready < mux->nb_streams);
  890. // this may be called during initialization - do not start
  891. // threads before sch_start() is called
  892. if (++mux->nb_streams_ready == mux->nb_streams &&
  893. sch->state >= SCH_STATE_STARTED)
  894. ret = mux_init(sch, mux);
  895. pthread_mutex_unlock(&sch->mux_ready_lock);
  896. return ret;
  897. }
  898. int sch_mux_sub_heartbeat_add(Scheduler *sch, unsigned mux_idx, unsigned stream_idx,
  899. unsigned dec_idx)
  900. {
  901. SchMux *mux;
  902. SchMuxStream *ms;
  903. int ret = 0;
  904. av_assert0(mux_idx < sch->nb_mux);
  905. mux = &sch->mux[mux_idx];
  906. av_assert0(stream_idx < mux->nb_streams);
  907. ms = &mux->streams[stream_idx];
  908. ret = GROW_ARRAY(ms->sub_heartbeat_dst, ms->nb_sub_heartbeat_dst);
  909. if (ret < 0)
  910. return ret;
  911. av_assert0(dec_idx < sch->nb_dec);
  912. ms->sub_heartbeat_dst[ms->nb_sub_heartbeat_dst - 1] = dec_idx;
  913. if (!mux->sub_heartbeat_pkt) {
  914. mux->sub_heartbeat_pkt = av_packet_alloc();
  915. if (!mux->sub_heartbeat_pkt)
  916. return AVERROR(ENOMEM);
  917. }
  918. return 0;
  919. }
  920. static void unchoke_for_stream(Scheduler *sch, SchedulerNode src)
  921. {
  922. while (1) {
  923. SchFilterGraph *fg;
  924. // fed directly by a demuxer (i.e. not through a filtergraph)
  925. if (src.type == SCH_NODE_TYPE_DEMUX) {
  926. sch->demux[src.idx].waiter.choked_next = 0;
  927. return;
  928. }
  929. av_assert0(src.type == SCH_NODE_TYPE_FILTER_OUT);
  930. fg = &sch->filters[src.idx];
  931. // the filtergraph contains internal sources and
  932. // requested to be scheduled directly
  933. if (fg->best_input == fg->nb_inputs) {
  934. fg->waiter.choked_next = 0;
  935. return;
  936. }
  937. src = fg->inputs[fg->best_input].src_sched;
  938. }
  939. }
  940. static void schedule_update_locked(Scheduler *sch)
  941. {
  942. int64_t dts;
  943. int have_unchoked = 0;
  944. // on termination request all waiters are choked,
  945. // we are not to unchoke them
  946. if (atomic_load(&sch->terminate))
  947. return;
  948. dts = trailing_dts(sch, 0);
  949. atomic_store(&sch->last_dts, dts);
  950. // initialize our internal state
  951. for (unsigned type = 0; type < 2; type++)
  952. for (unsigned i = 0; i < (type ? sch->nb_filters : sch->nb_demux); i++) {
  953. SchWaiter *w = type ? &sch->filters[i].waiter : &sch->demux[i].waiter;
  954. w->choked_prev = atomic_load(&w->choked);
  955. w->choked_next = 1;
  956. }
  957. // figure out the sources that are allowed to proceed
  958. for (unsigned i = 0; i < sch->nb_mux; i++) {
  959. SchMux *mux = &sch->mux[i];
  960. for (unsigned j = 0; j < mux->nb_streams; j++) {
  961. SchMuxStream *ms = &mux->streams[j];
  962. // unblock sources for output streams that are not finished
  963. // and not too far ahead of the trailing stream
  964. if (ms->source_finished)
  965. continue;
  966. if (dts == AV_NOPTS_VALUE && ms->last_dts != AV_NOPTS_VALUE)
  967. continue;
  968. if (dts != AV_NOPTS_VALUE && ms->last_dts - dts >= SCHEDULE_TOLERANCE)
  969. continue;
  970. // resolve the source to unchoke
  971. unchoke_for_stream(sch, ms->src_sched);
  972. have_unchoked = 1;
  973. }
  974. }
  975. // make sure to unchoke at least one source, if still available
  976. for (unsigned type = 0; !have_unchoked && type < 2; type++)
  977. for (unsigned i = 0; i < (type ? sch->nb_filters : sch->nb_demux); i++) {
  978. int exited = type ? sch->filters[i].task_exited : sch->demux[i].task_exited;
  979. SchWaiter *w = type ? &sch->filters[i].waiter : &sch->demux[i].waiter;
  980. if (!exited) {
  981. w->choked_next = 0;
  982. have_unchoked = 1;
  983. break;
  984. }
  985. }
  986. for (unsigned type = 0; type < 2; type++)
  987. for (unsigned i = 0; i < (type ? sch->nb_filters : sch->nb_demux); i++) {
  988. SchWaiter *w = type ? &sch->filters[i].waiter : &sch->demux[i].waiter;
  989. if (w->choked_prev != w->choked_next)
  990. waiter_set(w, w->choked_next);
  991. }
  992. }
  993. enum {
  994. CYCLE_NODE_NEW = 0,
  995. CYCLE_NODE_STARTED,
  996. CYCLE_NODE_DONE,
  997. };
  998. static int
  999. check_acyclic_for_output(const Scheduler *sch, SchedulerNode src,
  1000. uint8_t *filters_visited, SchedulerNode *filters_stack)
  1001. {
  1002. unsigned nb_filters_stack = 0;
  1003. memset(filters_visited, 0, sch->nb_filters * sizeof(*filters_visited));
  1004. while (1) {
  1005. const SchFilterGraph *fg = &sch->filters[src.idx];
  1006. filters_visited[src.idx] = CYCLE_NODE_STARTED;
  1007. // descend into every input, depth first
  1008. if (src.idx_stream < fg->nb_inputs) {
  1009. const SchFilterIn *fi = &fg->inputs[src.idx_stream++];
  1010. // connected to demuxer, no cycles possible
  1011. if (fi->src_sched.type == SCH_NODE_TYPE_DEMUX)
  1012. continue;
  1013. // otherwise connected to another filtergraph
  1014. av_assert0(fi->src_sched.type == SCH_NODE_TYPE_FILTER_OUT);
  1015. // found a cycle
  1016. if (filters_visited[fi->src_sched.idx] == CYCLE_NODE_STARTED)
  1017. return AVERROR(EINVAL);
  1018. // place current position on stack and descend
  1019. av_assert0(nb_filters_stack < sch->nb_filters);
  1020. filters_stack[nb_filters_stack++] = src;
  1021. src = (SchedulerNode){ .idx = fi->src_sched.idx, .idx_stream = 0 };
  1022. continue;
  1023. }
  1024. filters_visited[src.idx] = CYCLE_NODE_DONE;
  1025. // previous search finished,
  1026. if (nb_filters_stack) {
  1027. src = filters_stack[--nb_filters_stack];
  1028. continue;
  1029. }
  1030. return 0;
  1031. }
  1032. }
  1033. static int check_acyclic(Scheduler *sch)
  1034. {
  1035. uint8_t *filters_visited = NULL;
  1036. SchedulerNode *filters_stack = NULL;
  1037. int ret = 0;
  1038. if (!sch->nb_filters)
  1039. return 0;
  1040. filters_visited = av_malloc_array(sch->nb_filters, sizeof(*filters_visited));
  1041. if (!filters_visited)
  1042. return AVERROR(ENOMEM);
  1043. filters_stack = av_malloc_array(sch->nb_filters, sizeof(*filters_stack));
  1044. if (!filters_stack) {
  1045. ret = AVERROR(ENOMEM);
  1046. goto fail;
  1047. }
  1048. // trace the transcoding graph upstream from every filtegraph
  1049. for (unsigned i = 0; i < sch->nb_filters; i++) {
  1050. ret = check_acyclic_for_output(sch, (SchedulerNode){ .idx = i },
  1051. filters_visited, filters_stack);
  1052. if (ret < 0) {
  1053. av_log(&sch->filters[i], AV_LOG_ERROR, "Transcoding graph has a cycle\n");
  1054. goto fail;
  1055. }
  1056. }
  1057. fail:
  1058. av_freep(&filters_visited);
  1059. av_freep(&filters_stack);
  1060. return ret;
  1061. }
  1062. static int start_prepare(Scheduler *sch)
  1063. {
  1064. int ret;
  1065. for (unsigned i = 0; i < sch->nb_demux; i++) {
  1066. SchDemux *d = &sch->demux[i];
  1067. for (unsigned j = 0; j < d->nb_streams; j++) {
  1068. SchDemuxStream *ds = &d->streams[j];
  1069. if (!ds->nb_dst) {
  1070. av_log(d, AV_LOG_ERROR,
  1071. "Demuxer stream %u not connected to any sink\n", j);
  1072. return AVERROR(EINVAL);
  1073. }
  1074. ds->dst_finished = av_calloc(ds->nb_dst, sizeof(*ds->dst_finished));
  1075. if (!ds->dst_finished)
  1076. return AVERROR(ENOMEM);
  1077. }
  1078. }
  1079. for (unsigned i = 0; i < sch->nb_dec; i++) {
  1080. SchDec *dec = &sch->dec[i];
  1081. if (!dec->src.type) {
  1082. av_log(dec, AV_LOG_ERROR,
  1083. "Decoder not connected to a source\n");
  1084. return AVERROR(EINVAL);
  1085. }
  1086. if (!dec->nb_dst) {
  1087. av_log(dec, AV_LOG_ERROR,
  1088. "Decoder not connected to any sink\n");
  1089. return AVERROR(EINVAL);
  1090. }
  1091. dec->dst_finished = av_calloc(dec->nb_dst, sizeof(*dec->dst_finished));
  1092. if (!dec->dst_finished)
  1093. return AVERROR(ENOMEM);
  1094. }
  1095. for (unsigned i = 0; i < sch->nb_enc; i++) {
  1096. SchEnc *enc = &sch->enc[i];
  1097. if (!enc->src.type) {
  1098. av_log(enc, AV_LOG_ERROR,
  1099. "Encoder not connected to a source\n");
  1100. return AVERROR(EINVAL);
  1101. }
  1102. if (!enc->nb_dst) {
  1103. av_log(enc, AV_LOG_ERROR,
  1104. "Encoder not connected to any sink\n");
  1105. return AVERROR(EINVAL);
  1106. }
  1107. enc->dst_finished = av_calloc(enc->nb_dst, sizeof(*enc->dst_finished));
  1108. if (!enc->dst_finished)
  1109. return AVERROR(ENOMEM);
  1110. }
  1111. for (unsigned i = 0; i < sch->nb_mux; i++) {
  1112. SchMux *mux = &sch->mux[i];
  1113. for (unsigned j = 0; j < mux->nb_streams; j++) {
  1114. SchMuxStream *ms = &mux->streams[j];
  1115. switch (ms->src.type) {
  1116. case SCH_NODE_TYPE_ENC: {
  1117. SchEnc *enc = &sch->enc[ms->src.idx];
  1118. if (enc->src.type == SCH_NODE_TYPE_DEC) {
  1119. ms->src_sched = sch->dec[enc->src.idx].src;
  1120. av_assert0(ms->src_sched.type == SCH_NODE_TYPE_DEMUX);
  1121. } else {
  1122. ms->src_sched = enc->src;
  1123. av_assert0(ms->src_sched.type == SCH_NODE_TYPE_FILTER_OUT);
  1124. }
  1125. break;
  1126. }
  1127. case SCH_NODE_TYPE_DEMUX:
  1128. ms->src_sched = ms->src;
  1129. break;
  1130. default:
  1131. av_log(mux, AV_LOG_ERROR,
  1132. "Muxer stream #%u not connected to a source\n", j);
  1133. return AVERROR(EINVAL);
  1134. }
  1135. }
  1136. ret = queue_alloc(&mux->queue, mux->nb_streams, mux->queue_size,
  1137. QUEUE_PACKETS);
  1138. if (ret < 0)
  1139. return ret;
  1140. }
  1141. for (unsigned i = 0; i < sch->nb_filters; i++) {
  1142. SchFilterGraph *fg = &sch->filters[i];
  1143. for (unsigned j = 0; j < fg->nb_inputs; j++) {
  1144. SchFilterIn *fi = &fg->inputs[j];
  1145. SchDec *dec;
  1146. if (!fi->src.type) {
  1147. av_log(fg, AV_LOG_ERROR,
  1148. "Filtergraph input %u not connected to a source\n", j);
  1149. return AVERROR(EINVAL);
  1150. }
  1151. if (fi->src.type == SCH_NODE_TYPE_FILTER_OUT)
  1152. fi->src_sched = fi->src;
  1153. else {
  1154. av_assert0(fi->src.type == SCH_NODE_TYPE_DEC);
  1155. dec = &sch->dec[fi->src.idx];
  1156. switch (dec->src.type) {
  1157. case SCH_NODE_TYPE_DEMUX: fi->src_sched = dec->src; break;
  1158. case SCH_NODE_TYPE_ENC: fi->src_sched = sch->enc[dec->src.idx].src; break;
  1159. default: av_assert0(0);
  1160. }
  1161. }
  1162. }
  1163. for (unsigned j = 0; j < fg->nb_outputs; j++) {
  1164. SchFilterOut *fo = &fg->outputs[j];
  1165. if (!fo->dst.type) {
  1166. av_log(fg, AV_LOG_ERROR,
  1167. "Filtergraph %u output %u not connected to a sink\n", i, j);
  1168. return AVERROR(EINVAL);
  1169. }
  1170. }
  1171. }
  1172. // Check that the transcoding graph has no cycles.
  1173. ret = check_acyclic(sch);
  1174. if (ret < 0)
  1175. return ret;
  1176. return 0;
  1177. }
  1178. int sch_start(Scheduler *sch)
  1179. {
  1180. int ret;
  1181. ret = start_prepare(sch);
  1182. if (ret < 0)
  1183. return ret;
  1184. av_assert0(sch->state == SCH_STATE_UNINIT);
  1185. sch->state = SCH_STATE_STARTED;
  1186. for (unsigned i = 0; i < sch->nb_mux; i++) {
  1187. SchMux *mux = &sch->mux[i];
  1188. if (mux->nb_streams_ready == mux->nb_streams) {
  1189. ret = mux_init(sch, mux);
  1190. if (ret < 0)
  1191. goto fail;
  1192. }
  1193. }
  1194. for (unsigned i = 0; i < sch->nb_enc; i++) {
  1195. SchEnc *enc = &sch->enc[i];
  1196. ret = task_start(&enc->task);
  1197. if (ret < 0)
  1198. goto fail;
  1199. }
  1200. for (unsigned i = 0; i < sch->nb_filters; i++) {
  1201. SchFilterGraph *fg = &sch->filters[i];
  1202. ret = task_start(&fg->task);
  1203. if (ret < 0)
  1204. goto fail;
  1205. }
  1206. for (unsigned i = 0; i < sch->nb_dec; i++) {
  1207. SchDec *dec = &sch->dec[i];
  1208. ret = task_start(&dec->task);
  1209. if (ret < 0)
  1210. goto fail;
  1211. }
  1212. for (unsigned i = 0; i < sch->nb_demux; i++) {
  1213. SchDemux *d = &sch->demux[i];
  1214. if (!d->nb_streams)
  1215. continue;
  1216. ret = task_start(&d->task);
  1217. if (ret < 0)
  1218. goto fail;
  1219. }
  1220. pthread_mutex_lock(&sch->schedule_lock);
  1221. schedule_update_locked(sch);
  1222. pthread_mutex_unlock(&sch->schedule_lock);
  1223. return 0;
  1224. fail:
  1225. sch_stop(sch, NULL);
  1226. return ret;
  1227. }
  1228. int sch_wait(Scheduler *sch, uint64_t timeout_us, int64_t *transcode_ts)
  1229. {
  1230. int ret, err;
  1231. // convert delay to absolute timestamp
  1232. timeout_us += av_gettime();
  1233. pthread_mutex_lock(&sch->mux_done_lock);
  1234. if (sch->nb_mux_done < sch->nb_mux) {
  1235. struct timespec tv = { .tv_sec = timeout_us / 1000000,
  1236. .tv_nsec = (timeout_us % 1000000) * 1000 };
  1237. pthread_cond_timedwait(&sch->mux_done_cond, &sch->mux_done_lock, &tv);
  1238. }
  1239. ret = sch->nb_mux_done == sch->nb_mux;
  1240. pthread_mutex_unlock(&sch->mux_done_lock);
  1241. *transcode_ts = atomic_load(&sch->last_dts);
  1242. // abort transcoding if any task failed
  1243. err = atomic_load(&sch->task_failed);
  1244. return ret || err;
  1245. }
  1246. static int enc_open(Scheduler *sch, SchEnc *enc, const AVFrame *frame)
  1247. {
  1248. int ret;
  1249. ret = enc->open_cb(enc->task.func_arg, frame);
  1250. if (ret < 0)
  1251. return ret;
  1252. // ret>0 signals audio frame size, which means sync queue must
  1253. // have been enabled during encoder creation
  1254. if (ret > 0) {
  1255. SchSyncQueue *sq;
  1256. av_assert0(enc->sq_idx[0] >= 0);
  1257. sq = &sch->sq_enc[enc->sq_idx[0]];
  1258. pthread_mutex_lock(&sq->lock);
  1259. sq_frame_samples(sq->sq, enc->sq_idx[1], ret);
  1260. pthread_mutex_unlock(&sq->lock);
  1261. }
  1262. return 0;
  1263. }
  1264. static int send_to_enc_thread(Scheduler *sch, SchEnc *enc, AVFrame *frame)
  1265. {
  1266. int ret;
  1267. if (!frame) {
  1268. tq_send_finish(enc->queue, 0);
  1269. return 0;
  1270. }
  1271. if (enc->in_finished)
  1272. return AVERROR_EOF;
  1273. ret = tq_send(enc->queue, 0, frame);
  1274. if (ret < 0)
  1275. enc->in_finished = 1;
  1276. return ret;
  1277. }
  1278. static int send_to_enc_sq(Scheduler *sch, SchEnc *enc, AVFrame *frame)
  1279. {
  1280. SchSyncQueue *sq = &sch->sq_enc[enc->sq_idx[0]];
  1281. int ret = 0;
  1282. // inform the scheduling code that no more input will arrive along this path;
  1283. // this is necessary because the sync queue may not send an EOF downstream
  1284. // until other streams finish
  1285. // TODO: consider a cleaner way of passing this information through
  1286. // the pipeline
  1287. if (!frame) {
  1288. for (unsigned i = 0; i < enc->nb_dst; i++) {
  1289. SchMux *mux;
  1290. SchMuxStream *ms;
  1291. if (enc->dst[i].type != SCH_NODE_TYPE_MUX)
  1292. continue;
  1293. mux = &sch->mux[enc->dst[i].idx];
  1294. ms = &mux->streams[enc->dst[i].idx_stream];
  1295. pthread_mutex_lock(&sch->schedule_lock);
  1296. ms->source_finished = 1;
  1297. schedule_update_locked(sch);
  1298. pthread_mutex_unlock(&sch->schedule_lock);
  1299. }
  1300. }
  1301. pthread_mutex_lock(&sq->lock);
  1302. ret = sq_send(sq->sq, enc->sq_idx[1], SQFRAME(frame));
  1303. if (ret < 0)
  1304. goto finish;
  1305. while (1) {
  1306. SchEnc *enc;
  1307. // TODO: the SQ API should be extended to allow returning EOF
  1308. // for individual streams
  1309. ret = sq_receive(sq->sq, -1, SQFRAME(sq->frame));
  1310. if (ret < 0) {
  1311. ret = (ret == AVERROR(EAGAIN)) ? 0 : ret;
  1312. break;
  1313. }
  1314. enc = &sch->enc[sq->enc_idx[ret]];
  1315. ret = send_to_enc_thread(sch, enc, sq->frame);
  1316. if (ret < 0) {
  1317. av_frame_unref(sq->frame);
  1318. if (ret != AVERROR_EOF)
  1319. break;
  1320. sq_send(sq->sq, enc->sq_idx[1], SQFRAME(NULL));
  1321. continue;
  1322. }
  1323. }
  1324. if (ret < 0) {
  1325. // close all encoders fed from this sync queue
  1326. for (unsigned i = 0; i < sq->nb_enc_idx; i++) {
  1327. int err = send_to_enc_thread(sch, &sch->enc[sq->enc_idx[i]], NULL);
  1328. // if the sync queue error is EOF and closing the encoder
  1329. // produces a more serious error, make sure to pick the latter
  1330. ret = err_merge((ret == AVERROR_EOF && err < 0) ? 0 : ret, err);
  1331. }
  1332. }
  1333. finish:
  1334. pthread_mutex_unlock(&sq->lock);
  1335. return ret;
  1336. }
  1337. static int send_to_enc(Scheduler *sch, SchEnc *enc, AVFrame *frame)
  1338. {
  1339. if (enc->open_cb && frame && !enc->opened) {
  1340. int ret = enc_open(sch, enc, frame);
  1341. if (ret < 0)
  1342. return ret;
  1343. enc->opened = 1;
  1344. // discard empty frames that only carry encoder init parameters
  1345. if (!frame->buf[0]) {
  1346. av_frame_unref(frame);
  1347. return 0;
  1348. }
  1349. }
  1350. return (enc->sq_idx[0] >= 0) ?
  1351. send_to_enc_sq (sch, enc, frame) :
  1352. send_to_enc_thread(sch, enc, frame);
  1353. }
  1354. static int mux_queue_packet(SchMux *mux, SchMuxStream *ms, AVPacket *pkt)
  1355. {
  1356. PreMuxQueue *q = &ms->pre_mux_queue;
  1357. AVPacket *tmp_pkt = NULL;
  1358. int ret;
  1359. if (!av_fifo_can_write(q->fifo)) {
  1360. size_t packets = av_fifo_can_read(q->fifo);
  1361. size_t pkt_size = pkt ? pkt->size : 0;
  1362. int thresh_reached = (q->data_size + pkt_size) > q->data_threshold;
  1363. size_t max_packets = thresh_reached ? q->max_packets : SIZE_MAX;
  1364. size_t new_size = FFMIN(2 * packets, max_packets);
  1365. if (new_size <= packets) {
  1366. av_log(mux, AV_LOG_ERROR,
  1367. "Too many packets buffered for output stream.\n");
  1368. return AVERROR(ENOSPC);
  1369. }
  1370. ret = av_fifo_grow2(q->fifo, new_size - packets);
  1371. if (ret < 0)
  1372. return ret;
  1373. }
  1374. if (pkt) {
  1375. tmp_pkt = av_packet_alloc();
  1376. if (!tmp_pkt)
  1377. return AVERROR(ENOMEM);
  1378. av_packet_move_ref(tmp_pkt, pkt);
  1379. q->data_size += tmp_pkt->size;
  1380. }
  1381. av_fifo_write(q->fifo, &tmp_pkt, 1);
  1382. return 0;
  1383. }
  1384. static int send_to_mux(Scheduler *sch, SchMux *mux, unsigned stream_idx,
  1385. AVPacket *pkt)
  1386. {
  1387. SchMuxStream *ms = &mux->streams[stream_idx];
  1388. int64_t dts = (pkt && pkt->dts != AV_NOPTS_VALUE) ?
  1389. av_rescale_q(pkt->dts + pkt->duration, pkt->time_base, AV_TIME_BASE_Q) :
  1390. AV_NOPTS_VALUE;
  1391. // queue the packet if the muxer cannot be started yet
  1392. if (!atomic_load(&mux->mux_started)) {
  1393. int queued = 0;
  1394. // the muxer could have started between the above atomic check and
  1395. // locking the mutex, then this block falls through to normal send path
  1396. pthread_mutex_lock(&sch->mux_ready_lock);
  1397. if (!atomic_load(&mux->mux_started)) {
  1398. int ret = mux_queue_packet(mux, ms, pkt);
  1399. queued = ret < 0 ? ret : 1;
  1400. }
  1401. pthread_mutex_unlock(&sch->mux_ready_lock);
  1402. if (queued < 0)
  1403. return queued;
  1404. else if (queued)
  1405. goto update_schedule;
  1406. }
  1407. if (pkt) {
  1408. int ret;
  1409. if (ms->init_eof)
  1410. return AVERROR_EOF;
  1411. ret = tq_send(mux->queue, stream_idx, pkt);
  1412. if (ret < 0)
  1413. return ret;
  1414. } else
  1415. tq_send_finish(mux->queue, stream_idx);
  1416. update_schedule:
  1417. // TODO: use atomics to check whether this changes trailing dts
  1418. // to avoid locking unnecesarily
  1419. if (dts != AV_NOPTS_VALUE || !pkt) {
  1420. pthread_mutex_lock(&sch->schedule_lock);
  1421. if (pkt) ms->last_dts = dts;
  1422. else ms->source_finished = 1;
  1423. schedule_update_locked(sch);
  1424. pthread_mutex_unlock(&sch->schedule_lock);
  1425. }
  1426. return 0;
  1427. }
  1428. static int
  1429. demux_stream_send_to_dst(Scheduler *sch, const SchedulerNode dst,
  1430. uint8_t *dst_finished, AVPacket *pkt, unsigned flags)
  1431. {
  1432. int ret;
  1433. if (*dst_finished)
  1434. return AVERROR_EOF;
  1435. if (pkt && dst.type == SCH_NODE_TYPE_MUX &&
  1436. (flags & DEMUX_SEND_STREAMCOPY_EOF)) {
  1437. av_packet_unref(pkt);
  1438. pkt = NULL;
  1439. }
  1440. if (!pkt)
  1441. goto finish;
  1442. ret = (dst.type == SCH_NODE_TYPE_MUX) ?
  1443. send_to_mux(sch, &sch->mux[dst.idx], dst.idx_stream, pkt) :
  1444. tq_send(sch->dec[dst.idx].queue, 0, pkt);
  1445. if (ret == AVERROR_EOF)
  1446. goto finish;
  1447. return ret;
  1448. finish:
  1449. if (dst.type == SCH_NODE_TYPE_MUX)
  1450. send_to_mux(sch, &sch->mux[dst.idx], dst.idx_stream, NULL);
  1451. else
  1452. tq_send_finish(sch->dec[dst.idx].queue, 0);
  1453. *dst_finished = 1;
  1454. return AVERROR_EOF;
  1455. }
  1456. static int demux_send_for_stream(Scheduler *sch, SchDemux *d, SchDemuxStream *ds,
  1457. AVPacket *pkt, unsigned flags)
  1458. {
  1459. unsigned nb_done = 0;
  1460. for (unsigned i = 0; i < ds->nb_dst; i++) {
  1461. AVPacket *to_send = pkt;
  1462. uint8_t *finished = &ds->dst_finished[i];
  1463. int ret;
  1464. // sending a packet consumes it, so make a temporary reference if needed
  1465. if (pkt && i < ds->nb_dst - 1) {
  1466. to_send = d->send_pkt;
  1467. ret = av_packet_ref(to_send, pkt);
  1468. if (ret < 0)
  1469. return ret;
  1470. }
  1471. ret = demux_stream_send_to_dst(sch, ds->dst[i], finished, to_send, flags);
  1472. if (to_send)
  1473. av_packet_unref(to_send);
  1474. if (ret == AVERROR_EOF)
  1475. nb_done++;
  1476. else if (ret < 0)
  1477. return ret;
  1478. }
  1479. return (nb_done == ds->nb_dst) ? AVERROR_EOF : 0;
  1480. }
  1481. static int demux_flush(Scheduler *sch, SchDemux *d, AVPacket *pkt)
  1482. {
  1483. Timestamp max_end_ts = (Timestamp){ .ts = AV_NOPTS_VALUE };
  1484. av_assert0(!pkt->buf && !pkt->data && !pkt->side_data_elems);
  1485. for (unsigned i = 0; i < d->nb_streams; i++) {
  1486. SchDemuxStream *ds = &d->streams[i];
  1487. for (unsigned j = 0; j < ds->nb_dst; j++) {
  1488. const SchedulerNode *dst = &ds->dst[j];
  1489. SchDec *dec;
  1490. int ret;
  1491. if (ds->dst_finished[j] || dst->type != SCH_NODE_TYPE_DEC)
  1492. continue;
  1493. dec = &sch->dec[dst->idx];
  1494. ret = tq_send(dec->queue, 0, pkt);
  1495. if (ret < 0)
  1496. return ret;
  1497. if (dec->queue_end_ts) {
  1498. Timestamp ts;
  1499. ret = av_thread_message_queue_recv(dec->queue_end_ts, &ts, 0);
  1500. if (ret < 0)
  1501. return ret;
  1502. if (max_end_ts.ts == AV_NOPTS_VALUE ||
  1503. (ts.ts != AV_NOPTS_VALUE &&
  1504. av_compare_ts(max_end_ts.ts, max_end_ts.tb, ts.ts, ts.tb) < 0))
  1505. max_end_ts = ts;
  1506. }
  1507. }
  1508. }
  1509. pkt->pts = max_end_ts.ts;
  1510. pkt->time_base = max_end_ts.tb;
  1511. return 0;
  1512. }
  1513. int sch_demux_send(Scheduler *sch, unsigned demux_idx, AVPacket *pkt,
  1514. unsigned flags)
  1515. {
  1516. SchDemux *d;
  1517. int terminate;
  1518. av_assert0(demux_idx < sch->nb_demux);
  1519. d = &sch->demux[demux_idx];
  1520. terminate = waiter_wait(sch, &d->waiter);
  1521. if (terminate)
  1522. return AVERROR_EXIT;
  1523. // flush the downstreams after seek
  1524. if (pkt->stream_index == -1)
  1525. return demux_flush(sch, d, pkt);
  1526. av_assert0(pkt->stream_index < d->nb_streams);
  1527. return demux_send_for_stream(sch, d, &d->streams[pkt->stream_index], pkt, flags);
  1528. }
  1529. static int demux_done(Scheduler *sch, unsigned demux_idx)
  1530. {
  1531. SchDemux *d = &sch->demux[demux_idx];
  1532. int ret = 0;
  1533. for (unsigned i = 0; i < d->nb_streams; i++) {
  1534. int err = demux_send_for_stream(sch, d, &d->streams[i], NULL, 0);
  1535. if (err != AVERROR_EOF)
  1536. ret = err_merge(ret, err);
  1537. }
  1538. pthread_mutex_lock(&sch->schedule_lock);
  1539. d->task_exited = 1;
  1540. schedule_update_locked(sch);
  1541. pthread_mutex_unlock(&sch->schedule_lock);
  1542. return ret;
  1543. }
  1544. int sch_mux_receive(Scheduler *sch, unsigned mux_idx, AVPacket *pkt)
  1545. {
  1546. SchMux *mux;
  1547. int ret, stream_idx;
  1548. av_assert0(mux_idx < sch->nb_mux);
  1549. mux = &sch->mux[mux_idx];
  1550. ret = tq_receive(mux->queue, &stream_idx, pkt);
  1551. pkt->stream_index = stream_idx;
  1552. return ret;
  1553. }
  1554. void sch_mux_receive_finish(Scheduler *sch, unsigned mux_idx, unsigned stream_idx)
  1555. {
  1556. SchMux *mux;
  1557. av_assert0(mux_idx < sch->nb_mux);
  1558. mux = &sch->mux[mux_idx];
  1559. av_assert0(stream_idx < mux->nb_streams);
  1560. tq_receive_finish(mux->queue, stream_idx);
  1561. pthread_mutex_lock(&sch->schedule_lock);
  1562. mux->streams[stream_idx].source_finished = 1;
  1563. schedule_update_locked(sch);
  1564. pthread_mutex_unlock(&sch->schedule_lock);
  1565. }
  1566. int sch_mux_sub_heartbeat(Scheduler *sch, unsigned mux_idx, unsigned stream_idx,
  1567. const AVPacket *pkt)
  1568. {
  1569. SchMux *mux;
  1570. SchMuxStream *ms;
  1571. av_assert0(mux_idx < sch->nb_mux);
  1572. mux = &sch->mux[mux_idx];
  1573. av_assert0(stream_idx < mux->nb_streams);
  1574. ms = &mux->streams[stream_idx];
  1575. for (unsigned i = 0; i < ms->nb_sub_heartbeat_dst; i++) {
  1576. SchDec *dst = &sch->dec[ms->sub_heartbeat_dst[i]];
  1577. int ret;
  1578. ret = av_packet_copy_props(mux->sub_heartbeat_pkt, pkt);
  1579. if (ret < 0)
  1580. return ret;
  1581. tq_send(dst->queue, 0, mux->sub_heartbeat_pkt);
  1582. }
  1583. return 0;
  1584. }
  1585. static int mux_done(Scheduler *sch, unsigned mux_idx)
  1586. {
  1587. SchMux *mux = &sch->mux[mux_idx];
  1588. pthread_mutex_lock(&sch->schedule_lock);
  1589. for (unsigned i = 0; i < mux->nb_streams; i++) {
  1590. tq_receive_finish(mux->queue, i);
  1591. mux->streams[i].source_finished = 1;
  1592. }
  1593. schedule_update_locked(sch);
  1594. pthread_mutex_unlock(&sch->schedule_lock);
  1595. pthread_mutex_lock(&sch->mux_done_lock);
  1596. av_assert0(sch->nb_mux_done < sch->nb_mux);
  1597. sch->nb_mux_done++;
  1598. pthread_cond_signal(&sch->mux_done_cond);
  1599. pthread_mutex_unlock(&sch->mux_done_lock);
  1600. return 0;
  1601. }
  1602. int sch_dec_receive(Scheduler *sch, unsigned dec_idx, AVPacket *pkt)
  1603. {
  1604. SchDec *dec;
  1605. int ret, dummy;
  1606. av_assert0(dec_idx < sch->nb_dec);
  1607. dec = &sch->dec[dec_idx];
  1608. // the decoder should have given us post-flush end timestamp in pkt
  1609. if (dec->expect_end_ts) {
  1610. Timestamp ts = (Timestamp){ .ts = pkt->pts, .tb = pkt->time_base };
  1611. ret = av_thread_message_queue_send(dec->queue_end_ts, &ts, 0);
  1612. if (ret < 0)
  1613. return ret;
  1614. dec->expect_end_ts = 0;
  1615. }
  1616. ret = tq_receive(dec->queue, &dummy, pkt);
  1617. av_assert0(dummy <= 0);
  1618. // got a flush packet, on the next call to this function the decoder
  1619. // will give us post-flush end timestamp
  1620. if (ret >= 0 && !pkt->data && !pkt->side_data_elems && dec->queue_end_ts)
  1621. dec->expect_end_ts = 1;
  1622. return ret;
  1623. }
  1624. static int send_to_filter(Scheduler *sch, SchFilterGraph *fg,
  1625. unsigned in_idx, AVFrame *frame)
  1626. {
  1627. if (frame)
  1628. return tq_send(fg->queue, in_idx, frame);
  1629. if (!fg->inputs[in_idx].send_finished) {
  1630. fg->inputs[in_idx].send_finished = 1;
  1631. tq_send_finish(fg->queue, in_idx);
  1632. // close the control stream when all actual inputs are done
  1633. if (atomic_fetch_add(&fg->nb_inputs_finished_send, 1) == fg->nb_inputs - 1)
  1634. tq_send_finish(fg->queue, fg->nb_inputs);
  1635. }
  1636. return 0;
  1637. }
  1638. static int dec_send_to_dst(Scheduler *sch, const SchedulerNode dst,
  1639. uint8_t *dst_finished, AVFrame *frame)
  1640. {
  1641. int ret;
  1642. if (*dst_finished)
  1643. return AVERROR_EOF;
  1644. if (!frame)
  1645. goto finish;
  1646. ret = (dst.type == SCH_NODE_TYPE_FILTER_IN) ?
  1647. send_to_filter(sch, &sch->filters[dst.idx], dst.idx_stream, frame) :
  1648. send_to_enc(sch, &sch->enc[dst.idx], frame);
  1649. if (ret == AVERROR_EOF)
  1650. goto finish;
  1651. return ret;
  1652. finish:
  1653. if (dst.type == SCH_NODE_TYPE_FILTER_IN)
  1654. send_to_filter(sch, &sch->filters[dst.idx], dst.idx_stream, NULL);
  1655. else
  1656. send_to_enc(sch, &sch->enc[dst.idx], NULL);
  1657. *dst_finished = 1;
  1658. return AVERROR_EOF;
  1659. }
  1660. int sch_dec_send(Scheduler *sch, unsigned dec_idx, AVFrame *frame)
  1661. {
  1662. SchDec *dec;
  1663. int ret;
  1664. unsigned nb_done = 0;
  1665. av_assert0(dec_idx < sch->nb_dec);
  1666. dec = &sch->dec[dec_idx];
  1667. for (unsigned i = 0; i < dec->nb_dst; i++) {
  1668. uint8_t *finished = &dec->dst_finished[i];
  1669. AVFrame *to_send = frame;
  1670. // sending a frame consumes it, so make a temporary reference if needed
  1671. if (i < dec->nb_dst - 1) {
  1672. to_send = dec->send_frame;
  1673. // frame may sometimes contain props only,
  1674. // e.g. to signal EOF timestamp
  1675. ret = frame->buf[0] ? av_frame_ref(to_send, frame) :
  1676. av_frame_copy_props(to_send, frame);
  1677. if (ret < 0)
  1678. return ret;
  1679. }
  1680. ret = dec_send_to_dst(sch, dec->dst[i], finished, to_send);
  1681. if (ret < 0) {
  1682. av_frame_unref(to_send);
  1683. if (ret == AVERROR_EOF) {
  1684. nb_done++;
  1685. continue;
  1686. }
  1687. return ret;
  1688. }
  1689. }
  1690. return (nb_done == dec->nb_dst) ? AVERROR_EOF : 0;
  1691. }
  1692. static int dec_done(Scheduler *sch, unsigned dec_idx)
  1693. {
  1694. SchDec *dec = &sch->dec[dec_idx];
  1695. int ret = 0;
  1696. tq_receive_finish(dec->queue, 0);
  1697. // make sure our source does not get stuck waiting for end timestamps
  1698. // that will never arrive
  1699. if (dec->queue_end_ts)
  1700. av_thread_message_queue_set_err_recv(dec->queue_end_ts, AVERROR_EOF);
  1701. for (unsigned i = 0; i < dec->nb_dst; i++) {
  1702. int err = dec_send_to_dst(sch, dec->dst[i], &dec->dst_finished[i], NULL);
  1703. if (err < 0 && err != AVERROR_EOF)
  1704. ret = err_merge(ret, err);
  1705. }
  1706. return ret;
  1707. }
  1708. int sch_enc_receive(Scheduler *sch, unsigned enc_idx, AVFrame *frame)
  1709. {
  1710. SchEnc *enc;
  1711. int ret, dummy;
  1712. av_assert0(enc_idx < sch->nb_enc);
  1713. enc = &sch->enc[enc_idx];
  1714. ret = tq_receive(enc->queue, &dummy, frame);
  1715. av_assert0(dummy <= 0);
  1716. return ret;
  1717. }
  1718. static int enc_send_to_dst(Scheduler *sch, const SchedulerNode dst,
  1719. uint8_t *dst_finished, AVPacket *pkt)
  1720. {
  1721. int ret;
  1722. if (*dst_finished)
  1723. return AVERROR_EOF;
  1724. if (!pkt)
  1725. goto finish;
  1726. ret = (dst.type == SCH_NODE_TYPE_MUX) ?
  1727. send_to_mux(sch, &sch->mux[dst.idx], dst.idx_stream, pkt) :
  1728. tq_send(sch->dec[dst.idx].queue, 0, pkt);
  1729. if (ret == AVERROR_EOF)
  1730. goto finish;
  1731. return ret;
  1732. finish:
  1733. if (dst.type == SCH_NODE_TYPE_MUX)
  1734. send_to_mux(sch, &sch->mux[dst.idx], dst.idx_stream, NULL);
  1735. else
  1736. tq_send_finish(sch->dec[dst.idx].queue, 0);
  1737. *dst_finished = 1;
  1738. return AVERROR_EOF;
  1739. }
  1740. int sch_enc_send(Scheduler *sch, unsigned enc_idx, AVPacket *pkt)
  1741. {
  1742. SchEnc *enc;
  1743. int ret;
  1744. av_assert0(enc_idx < sch->nb_enc);
  1745. enc = &sch->enc[enc_idx];
  1746. for (unsigned i = 0; i < enc->nb_dst; i++) {
  1747. uint8_t *finished = &enc->dst_finished[i];
  1748. AVPacket *to_send = pkt;
  1749. // sending a packet consumes it, so make a temporary reference if needed
  1750. if (i < enc->nb_dst - 1) {
  1751. to_send = enc->send_pkt;
  1752. ret = av_packet_ref(to_send, pkt);
  1753. if (ret < 0)
  1754. return ret;
  1755. }
  1756. ret = enc_send_to_dst(sch, enc->dst[i], finished, to_send);
  1757. if (ret < 0) {
  1758. av_packet_unref(to_send);
  1759. if (ret == AVERROR_EOF)
  1760. continue;
  1761. return ret;
  1762. }
  1763. }
  1764. return 0;
  1765. }
  1766. static int enc_done(Scheduler *sch, unsigned enc_idx)
  1767. {
  1768. SchEnc *enc = &sch->enc[enc_idx];
  1769. int ret = 0;
  1770. tq_receive_finish(enc->queue, 0);
  1771. for (unsigned i = 0; i < enc->nb_dst; i++) {
  1772. int err = enc_send_to_dst(sch, enc->dst[i], &enc->dst_finished[i], NULL);
  1773. if (err < 0 && err != AVERROR_EOF)
  1774. ret = err_merge(ret, err);
  1775. }
  1776. return ret;
  1777. }
  1778. int sch_filter_receive(Scheduler *sch, unsigned fg_idx,
  1779. unsigned *in_idx, AVFrame *frame)
  1780. {
  1781. SchFilterGraph *fg;
  1782. av_assert0(fg_idx < sch->nb_filters);
  1783. fg = &sch->filters[fg_idx];
  1784. av_assert0(*in_idx <= fg->nb_inputs);
  1785. // update scheduling to account for desired input stream, if it changed
  1786. //
  1787. // this check needs no locking because only the filtering thread
  1788. // updates this value
  1789. if (*in_idx != fg->best_input) {
  1790. pthread_mutex_lock(&sch->schedule_lock);
  1791. fg->best_input = *in_idx;
  1792. schedule_update_locked(sch);
  1793. pthread_mutex_unlock(&sch->schedule_lock);
  1794. }
  1795. if (*in_idx == fg->nb_inputs) {
  1796. int terminate = waiter_wait(sch, &fg->waiter);
  1797. return terminate ? AVERROR_EOF : AVERROR(EAGAIN);
  1798. }
  1799. while (1) {
  1800. int ret, idx;
  1801. ret = tq_receive(fg->queue, &idx, frame);
  1802. if (idx < 0)
  1803. return AVERROR_EOF;
  1804. else if (ret >= 0) {
  1805. *in_idx = idx;
  1806. return 0;
  1807. }
  1808. // disregard EOFs for specific streams - they should always be
  1809. // preceded by an EOF frame
  1810. }
  1811. }
  1812. void sch_filter_receive_finish(Scheduler *sch, unsigned fg_idx, unsigned in_idx)
  1813. {
  1814. SchFilterGraph *fg;
  1815. SchFilterIn *fi;
  1816. av_assert0(fg_idx < sch->nb_filters);
  1817. fg = &sch->filters[fg_idx];
  1818. av_assert0(in_idx < fg->nb_inputs);
  1819. fi = &fg->inputs[in_idx];
  1820. if (!fi->receive_finished) {
  1821. fi->receive_finished = 1;
  1822. tq_receive_finish(fg->queue, in_idx);
  1823. // close the control stream when all actual inputs are done
  1824. if (++fg->nb_inputs_finished_receive == fg->nb_inputs)
  1825. tq_receive_finish(fg->queue, fg->nb_inputs);
  1826. }
  1827. }
  1828. int sch_filter_send(Scheduler *sch, unsigned fg_idx, unsigned out_idx, AVFrame *frame)
  1829. {
  1830. SchFilterGraph *fg;
  1831. SchedulerNode dst;
  1832. av_assert0(fg_idx < sch->nb_filters);
  1833. fg = &sch->filters[fg_idx];
  1834. av_assert0(out_idx < fg->nb_outputs);
  1835. dst = fg->outputs[out_idx].dst;
  1836. return (dst.type == SCH_NODE_TYPE_ENC) ?
  1837. send_to_enc (sch, &sch->enc[dst.idx], frame) :
  1838. send_to_filter(sch, &sch->filters[dst.idx], dst.idx_stream, frame);
  1839. }
  1840. static int filter_done(Scheduler *sch, unsigned fg_idx)
  1841. {
  1842. SchFilterGraph *fg = &sch->filters[fg_idx];
  1843. int ret = 0;
  1844. for (unsigned i = 0; i <= fg->nb_inputs; i++)
  1845. tq_receive_finish(fg->queue, i);
  1846. for (unsigned i = 0; i < fg->nb_outputs; i++) {
  1847. SchedulerNode dst = fg->outputs[i].dst;
  1848. int err = (dst.type == SCH_NODE_TYPE_ENC) ?
  1849. send_to_enc (sch, &sch->enc[dst.idx], NULL) :
  1850. send_to_filter(sch, &sch->filters[dst.idx], dst.idx_stream, NULL);
  1851. if (err < 0 && err != AVERROR_EOF)
  1852. ret = err_merge(ret, err);
  1853. }
  1854. pthread_mutex_lock(&sch->schedule_lock);
  1855. fg->task_exited = 1;
  1856. schedule_update_locked(sch);
  1857. pthread_mutex_unlock(&sch->schedule_lock);
  1858. return ret;
  1859. }
  1860. int sch_filter_command(Scheduler *sch, unsigned fg_idx, AVFrame *frame)
  1861. {
  1862. SchFilterGraph *fg;
  1863. av_assert0(fg_idx < sch->nb_filters);
  1864. fg = &sch->filters[fg_idx];
  1865. return send_to_filter(sch, fg, fg->nb_inputs, frame);
  1866. }
  1867. static int task_cleanup(Scheduler *sch, SchedulerNode node)
  1868. {
  1869. switch (node.type) {
  1870. case SCH_NODE_TYPE_DEMUX: return demux_done (sch, node.idx);
  1871. case SCH_NODE_TYPE_MUX: return mux_done (sch, node.idx);
  1872. case SCH_NODE_TYPE_DEC: return dec_done (sch, node.idx);
  1873. case SCH_NODE_TYPE_ENC: return enc_done (sch, node.idx);
  1874. case SCH_NODE_TYPE_FILTER_IN: return filter_done(sch, node.idx);
  1875. default: av_assert0(0);
  1876. }
  1877. }
  1878. static void *task_wrapper(void *arg)
  1879. {
  1880. SchTask *task = arg;
  1881. Scheduler *sch = task->parent;
  1882. int ret;
  1883. int err = 0;
  1884. ret = task->func(task->func_arg);
  1885. if (ret < 0)
  1886. av_log(task->func_arg, AV_LOG_ERROR,
  1887. "Task finished with error code: %d (%s)\n", ret, av_err2str(ret));
  1888. err = task_cleanup(sch, task->node);
  1889. ret = err_merge(ret, err);
  1890. // EOF is considered normal termination
  1891. if (ret == AVERROR_EOF)
  1892. ret = 0;
  1893. if (ret < 0)
  1894. atomic_store(&sch->task_failed, 1);
  1895. av_log(task->func_arg, ret < 0 ? AV_LOG_ERROR : AV_LOG_VERBOSE,
  1896. "Terminating thread with return code %d (%s)\n", ret,
  1897. ret < 0 ? av_err2str(ret) : "success");
  1898. return (void*)(intptr_t)ret;
  1899. }
  1900. static int task_stop(Scheduler *sch, SchTask *task)
  1901. {
  1902. int ret;
  1903. void *thread_ret;
  1904. if (!task->thread_running)
  1905. return task_cleanup(sch, task->node);
  1906. ret = pthread_join(task->thread, &thread_ret);
  1907. av_assert0(ret == 0);
  1908. task->thread_running = 0;
  1909. return (intptr_t)thread_ret;
  1910. }
  1911. int sch_stop(Scheduler *sch, int64_t *finish_ts)
  1912. {
  1913. int ret = 0, err;
  1914. if (sch->state != SCH_STATE_STARTED)
  1915. return 0;
  1916. atomic_store(&sch->terminate, 1);
  1917. for (unsigned type = 0; type < 2; type++)
  1918. for (unsigned i = 0; i < (type ? sch->nb_demux : sch->nb_filters); i++) {
  1919. SchWaiter *w = type ? &sch->demux[i].waiter : &sch->filters[i].waiter;
  1920. waiter_set(w, 1);
  1921. }
  1922. for (unsigned i = 0; i < sch->nb_demux; i++) {
  1923. SchDemux *d = &sch->demux[i];
  1924. err = task_stop(sch, &d->task);
  1925. ret = err_merge(ret, err);
  1926. }
  1927. for (unsigned i = 0; i < sch->nb_dec; i++) {
  1928. SchDec *dec = &sch->dec[i];
  1929. err = task_stop(sch, &dec->task);
  1930. ret = err_merge(ret, err);
  1931. }
  1932. for (unsigned i = 0; i < sch->nb_filters; i++) {
  1933. SchFilterGraph *fg = &sch->filters[i];
  1934. err = task_stop(sch, &fg->task);
  1935. ret = err_merge(ret, err);
  1936. }
  1937. for (unsigned i = 0; i < sch->nb_enc; i++) {
  1938. SchEnc *enc = &sch->enc[i];
  1939. err = task_stop(sch, &enc->task);
  1940. ret = err_merge(ret, err);
  1941. }
  1942. for (unsigned i = 0; i < sch->nb_mux; i++) {
  1943. SchMux *mux = &sch->mux[i];
  1944. err = task_stop(sch, &mux->task);
  1945. ret = err_merge(ret, err);
  1946. }
  1947. if (finish_ts)
  1948. *finish_ts = trailing_dts(sch, 1);
  1949. sch->state = SCH_STATE_STOPPED;
  1950. return ret;
  1951. }