ffmpeg_sched.c 68 KB

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