ffmpeg_sched.c 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540
  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. SchEnc *enc;
  751. av_assert0(src.idx < sch->nb_filters &&
  752. src.idx_stream < sch->filters[src.idx].nb_outputs);
  753. // filtered frames go to encoding
  754. av_assert0(dst.type == SCH_NODE_TYPE_ENC &&
  755. dst.idx < sch->nb_enc);
  756. fo = &sch->filters[src.idx].outputs[src.idx_stream];
  757. enc = &sch->enc[dst.idx];
  758. av_assert0(!fo->dst.type && !enc->src.type);
  759. fo->dst = dst;
  760. enc->src = src;
  761. break;
  762. }
  763. case SCH_NODE_TYPE_ENC: {
  764. SchEnc *enc;
  765. av_assert0(src.idx < sch->nb_enc);
  766. enc = &sch->enc[src.idx];
  767. ret = GROW_ARRAY(enc->dst, enc->nb_dst);
  768. if (ret < 0)
  769. return ret;
  770. enc->dst[enc->nb_dst - 1] = dst;
  771. // encoding packets go to muxing or decoding
  772. switch (dst.type) {
  773. case SCH_NODE_TYPE_MUX: {
  774. SchMuxStream *ms;
  775. av_assert0(dst.idx < sch->nb_mux &&
  776. dst.idx_stream < sch->mux[dst.idx].nb_streams);
  777. ms = &sch->mux[dst.idx].streams[dst.idx_stream];
  778. av_assert0(!ms->src.type);
  779. ms->src = src;
  780. break;
  781. }
  782. case SCH_NODE_TYPE_DEC: {
  783. SchDec *dec;
  784. av_assert0(dst.idx < sch->nb_dec);
  785. dec = &sch->dec[dst.idx];
  786. av_assert0(!dec->src.type);
  787. dec->src = src;
  788. break;
  789. }
  790. default: av_assert0(0);
  791. }
  792. break;
  793. }
  794. default: av_assert0(0);
  795. }
  796. return 0;
  797. }
  798. static int mux_task_start(SchMux *mux)
  799. {
  800. int ret = 0;
  801. ret = task_start(&mux->task);
  802. if (ret < 0)
  803. return ret;
  804. /* flush the pre-muxing queues */
  805. for (unsigned i = 0; i < mux->nb_streams; i++) {
  806. SchMuxStream *ms = &mux->streams[i];
  807. AVPacket *pkt;
  808. while (av_fifo_read(ms->pre_mux_queue.fifo, &pkt, 1) >= 0) {
  809. if (pkt) {
  810. if (!ms->init_eof)
  811. ret = tq_send(mux->queue, i, pkt);
  812. av_packet_free(&pkt);
  813. if (ret == AVERROR_EOF)
  814. ms->init_eof = 1;
  815. else if (ret < 0)
  816. return ret;
  817. } else
  818. tq_send_finish(mux->queue, i);
  819. }
  820. }
  821. atomic_store(&mux->mux_started, 1);
  822. return 0;
  823. }
  824. int print_sdp(const char *filename);
  825. static int mux_init(Scheduler *sch, SchMux *mux)
  826. {
  827. int ret;
  828. ret = mux->init(mux->task.func_arg);
  829. if (ret < 0)
  830. return ret;
  831. sch->nb_mux_ready++;
  832. if (sch->sdp_filename || sch->sdp_auto) {
  833. if (sch->nb_mux_ready < sch->nb_mux)
  834. return 0;
  835. ret = print_sdp(sch->sdp_filename);
  836. if (ret < 0) {
  837. av_log(sch, AV_LOG_ERROR, "Error writing the SDP.\n");
  838. return ret;
  839. }
  840. /* SDP is written only after all the muxers are ready, so now we
  841. * start ALL the threads */
  842. for (unsigned i = 0; i < sch->nb_mux; i++) {
  843. ret = mux_task_start(&sch->mux[i]);
  844. if (ret < 0)
  845. return ret;
  846. }
  847. } else {
  848. ret = mux_task_start(mux);
  849. if (ret < 0)
  850. return ret;
  851. }
  852. return 0;
  853. }
  854. void sch_mux_stream_buffering(Scheduler *sch, unsigned mux_idx, unsigned stream_idx,
  855. size_t data_threshold, int max_packets)
  856. {
  857. SchMux *mux;
  858. SchMuxStream *ms;
  859. av_assert0(mux_idx < sch->nb_mux);
  860. mux = &sch->mux[mux_idx];
  861. av_assert0(stream_idx < mux->nb_streams);
  862. ms = &mux->streams[stream_idx];
  863. ms->pre_mux_queue.max_packets = max_packets;
  864. ms->pre_mux_queue.data_threshold = data_threshold;
  865. }
  866. int sch_mux_stream_ready(Scheduler *sch, unsigned mux_idx, unsigned stream_idx)
  867. {
  868. SchMux *mux;
  869. int ret = 0;
  870. av_assert0(mux_idx < sch->nb_mux);
  871. mux = &sch->mux[mux_idx];
  872. av_assert0(stream_idx < mux->nb_streams);
  873. pthread_mutex_lock(&sch->mux_ready_lock);
  874. av_assert0(mux->nb_streams_ready < mux->nb_streams);
  875. // this may be called during initialization - do not start
  876. // threads before sch_start() is called
  877. if (++mux->nb_streams_ready == mux->nb_streams &&
  878. sch->state >= SCH_STATE_STARTED)
  879. ret = mux_init(sch, mux);
  880. pthread_mutex_unlock(&sch->mux_ready_lock);
  881. return ret;
  882. }
  883. int sch_mux_sub_heartbeat_add(Scheduler *sch, unsigned mux_idx, unsigned stream_idx,
  884. unsigned dec_idx)
  885. {
  886. SchMux *mux;
  887. SchMuxStream *ms;
  888. int ret = 0;
  889. av_assert0(mux_idx < sch->nb_mux);
  890. mux = &sch->mux[mux_idx];
  891. av_assert0(stream_idx < mux->nb_streams);
  892. ms = &mux->streams[stream_idx];
  893. ret = GROW_ARRAY(ms->sub_heartbeat_dst, ms->nb_sub_heartbeat_dst);
  894. if (ret < 0)
  895. return ret;
  896. av_assert0(dec_idx < sch->nb_dec);
  897. ms->sub_heartbeat_dst[ms->nb_sub_heartbeat_dst - 1] = dec_idx;
  898. if (!mux->sub_heartbeat_pkt) {
  899. mux->sub_heartbeat_pkt = av_packet_alloc();
  900. if (!mux->sub_heartbeat_pkt)
  901. return AVERROR(ENOMEM);
  902. }
  903. return 0;
  904. }
  905. static void unchoke_for_stream(Scheduler *sch, SchedulerNode src)
  906. {
  907. while (1) {
  908. SchFilterGraph *fg;
  909. // fed directly by a demuxer (i.e. not through a filtergraph)
  910. if (src.type == SCH_NODE_TYPE_DEMUX) {
  911. sch->demux[src.idx].waiter.choked_next = 0;
  912. return;
  913. }
  914. av_assert0(src.type == SCH_NODE_TYPE_FILTER_OUT);
  915. fg = &sch->filters[src.idx];
  916. // the filtergraph contains internal sources and
  917. // requested to be scheduled directly
  918. if (fg->best_input == fg->nb_inputs) {
  919. fg->waiter.choked_next = 0;
  920. return;
  921. }
  922. src = fg->inputs[fg->best_input].src_sched;
  923. }
  924. }
  925. static void schedule_update_locked(Scheduler *sch)
  926. {
  927. int64_t dts;
  928. int have_unchoked = 0;
  929. // on termination request all waiters are choked,
  930. // we are not to unchoke them
  931. if (atomic_load(&sch->terminate))
  932. return;
  933. dts = trailing_dts(sch, 0);
  934. atomic_store(&sch->last_dts, dts);
  935. // initialize our internal state
  936. for (unsigned type = 0; type < 2; type++)
  937. for (unsigned i = 0; i < (type ? sch->nb_filters : sch->nb_demux); i++) {
  938. SchWaiter *w = type ? &sch->filters[i].waiter : &sch->demux[i].waiter;
  939. w->choked_prev = atomic_load(&w->choked);
  940. w->choked_next = 1;
  941. }
  942. // figure out the sources that are allowed to proceed
  943. for (unsigned i = 0; i < sch->nb_mux; i++) {
  944. SchMux *mux = &sch->mux[i];
  945. for (unsigned j = 0; j < mux->nb_streams; j++) {
  946. SchMuxStream *ms = &mux->streams[j];
  947. // unblock sources for output streams that are not finished
  948. // and not too far ahead of the trailing stream
  949. if (ms->source_finished)
  950. continue;
  951. if (dts == AV_NOPTS_VALUE && ms->last_dts != AV_NOPTS_VALUE)
  952. continue;
  953. if (dts != AV_NOPTS_VALUE && ms->last_dts - dts >= SCHEDULE_TOLERANCE)
  954. continue;
  955. // resolve the source to unchoke
  956. unchoke_for_stream(sch, ms->src_sched);
  957. have_unchoked = 1;
  958. }
  959. }
  960. // make sure to unchoke at least one source, if still available
  961. for (unsigned type = 0; !have_unchoked && type < 2; type++)
  962. for (unsigned i = 0; i < (type ? sch->nb_filters : sch->nb_demux); i++) {
  963. int exited = type ? sch->filters[i].task_exited : sch->demux[i].task_exited;
  964. SchWaiter *w = type ? &sch->filters[i].waiter : &sch->demux[i].waiter;
  965. if (!exited) {
  966. w->choked_next = 0;
  967. have_unchoked = 1;
  968. break;
  969. }
  970. }
  971. for (unsigned type = 0; type < 2; type++)
  972. for (unsigned i = 0; i < (type ? sch->nb_filters : sch->nb_demux); i++) {
  973. SchWaiter *w = type ? &sch->filters[i].waiter : &sch->demux[i].waiter;
  974. if (w->choked_prev != w->choked_next)
  975. waiter_set(w, w->choked_next);
  976. }
  977. }
  978. enum {
  979. CYCLE_NODE_NEW = 0,
  980. CYCLE_NODE_STARTED,
  981. CYCLE_NODE_DONE,
  982. };
  983. static int
  984. check_acyclic_for_output(const Scheduler *sch, SchedulerNode src,
  985. uint8_t *filters_visited, SchedulerNode *filters_stack)
  986. {
  987. unsigned nb_filters_stack = 0;
  988. memset(filters_visited, 0, sch->nb_filters * sizeof(*filters_visited));
  989. while (1) {
  990. const SchFilterGraph *fg = &sch->filters[src.idx];
  991. filters_visited[src.idx] = CYCLE_NODE_STARTED;
  992. // descend into every input, depth first
  993. if (src.idx_stream < fg->nb_inputs) {
  994. const SchFilterIn *fi = &fg->inputs[src.idx_stream++];
  995. // connected to demuxer, no cycles possible
  996. if (fi->src_sched.type == SCH_NODE_TYPE_DEMUX)
  997. continue;
  998. // otherwise connected to another filtergraph
  999. av_assert0(fi->src_sched.type == SCH_NODE_TYPE_FILTER_OUT);
  1000. // found a cycle
  1001. if (filters_visited[fi->src_sched.idx] == CYCLE_NODE_STARTED)
  1002. return AVERROR(EINVAL);
  1003. // place current position on stack and descend
  1004. av_assert0(nb_filters_stack < sch->nb_filters);
  1005. filters_stack[nb_filters_stack++] = src;
  1006. src = (SchedulerNode){ .idx = fi->src_sched.idx, .idx_stream = 0 };
  1007. continue;
  1008. }
  1009. filters_visited[src.idx] = CYCLE_NODE_DONE;
  1010. // previous search finished,
  1011. if (nb_filters_stack) {
  1012. src = filters_stack[--nb_filters_stack];
  1013. continue;
  1014. }
  1015. return 0;
  1016. }
  1017. }
  1018. static int check_acyclic(Scheduler *sch)
  1019. {
  1020. uint8_t *filters_visited = NULL;
  1021. SchedulerNode *filters_stack = NULL;
  1022. int ret = 0;
  1023. if (!sch->nb_filters)
  1024. return 0;
  1025. filters_visited = av_malloc_array(sch->nb_filters, sizeof(*filters_visited));
  1026. if (!filters_visited)
  1027. return AVERROR(ENOMEM);
  1028. filters_stack = av_malloc_array(sch->nb_filters, sizeof(*filters_stack));
  1029. if (!filters_stack) {
  1030. ret = AVERROR(ENOMEM);
  1031. goto fail;
  1032. }
  1033. // trace the transcoding graph upstream from every output stream
  1034. // fed by a filtergraph
  1035. for (unsigned i = 0; i < sch->nb_mux; i++) {
  1036. SchMux *mux = &sch->mux[i];
  1037. for (unsigned j = 0; j < mux->nb_streams; j++) {
  1038. SchMuxStream *ms = &mux->streams[j];
  1039. SchedulerNode src = ms->src_sched;
  1040. if (src.type != SCH_NODE_TYPE_FILTER_OUT)
  1041. continue;
  1042. src.idx_stream = 0;
  1043. ret = check_acyclic_for_output(sch, src, filters_visited, filters_stack);
  1044. if (ret < 0) {
  1045. av_log(mux, AV_LOG_ERROR, "Transcoding graph has a cycle\n");
  1046. goto fail;
  1047. }
  1048. }
  1049. }
  1050. fail:
  1051. av_freep(&filters_visited);
  1052. av_freep(&filters_stack);
  1053. return ret;
  1054. }
  1055. static int start_prepare(Scheduler *sch)
  1056. {
  1057. int ret;
  1058. for (unsigned i = 0; i < sch->nb_demux; i++) {
  1059. SchDemux *d = &sch->demux[i];
  1060. for (unsigned j = 0; j < d->nb_streams; j++) {
  1061. SchDemuxStream *ds = &d->streams[j];
  1062. if (!ds->nb_dst) {
  1063. av_log(d, AV_LOG_ERROR,
  1064. "Demuxer stream %u not connected to any sink\n", j);
  1065. return AVERROR(EINVAL);
  1066. }
  1067. ds->dst_finished = av_calloc(ds->nb_dst, sizeof(*ds->dst_finished));
  1068. if (!ds->dst_finished)
  1069. return AVERROR(ENOMEM);
  1070. }
  1071. }
  1072. for (unsigned i = 0; i < sch->nb_dec; i++) {
  1073. SchDec *dec = &sch->dec[i];
  1074. if (!dec->src.type) {
  1075. av_log(dec, AV_LOG_ERROR,
  1076. "Decoder not connected to a source\n");
  1077. return AVERROR(EINVAL);
  1078. }
  1079. if (!dec->nb_dst) {
  1080. av_log(dec, AV_LOG_ERROR,
  1081. "Decoder not connected to any sink\n");
  1082. return AVERROR(EINVAL);
  1083. }
  1084. dec->dst_finished = av_calloc(dec->nb_dst, sizeof(*dec->dst_finished));
  1085. if (!dec->dst_finished)
  1086. return AVERROR(ENOMEM);
  1087. }
  1088. for (unsigned i = 0; i < sch->nb_enc; i++) {
  1089. SchEnc *enc = &sch->enc[i];
  1090. if (!enc->src.type) {
  1091. av_log(enc, AV_LOG_ERROR,
  1092. "Encoder not connected to a source\n");
  1093. return AVERROR(EINVAL);
  1094. }
  1095. if (!enc->nb_dst) {
  1096. av_log(enc, AV_LOG_ERROR,
  1097. "Encoder not connected to any sink\n");
  1098. return AVERROR(EINVAL);
  1099. }
  1100. enc->dst_finished = av_calloc(enc->nb_dst, sizeof(*enc->dst_finished));
  1101. if (!enc->dst_finished)
  1102. return AVERROR(ENOMEM);
  1103. }
  1104. for (unsigned i = 0; i < sch->nb_mux; i++) {
  1105. SchMux *mux = &sch->mux[i];
  1106. for (unsigned j = 0; j < mux->nb_streams; j++) {
  1107. SchMuxStream *ms = &mux->streams[j];
  1108. switch (ms->src.type) {
  1109. case SCH_NODE_TYPE_ENC: {
  1110. SchEnc *enc = &sch->enc[ms->src.idx];
  1111. if (enc->src.type == SCH_NODE_TYPE_DEC) {
  1112. ms->src_sched = sch->dec[enc->src.idx].src;
  1113. av_assert0(ms->src_sched.type == SCH_NODE_TYPE_DEMUX);
  1114. } else {
  1115. ms->src_sched = enc->src;
  1116. av_assert0(ms->src_sched.type == SCH_NODE_TYPE_FILTER_OUT);
  1117. }
  1118. break;
  1119. }
  1120. case SCH_NODE_TYPE_DEMUX:
  1121. ms->src_sched = ms->src;
  1122. break;
  1123. default:
  1124. av_log(mux, AV_LOG_ERROR,
  1125. "Muxer stream #%u not connected to a source\n", j);
  1126. return AVERROR(EINVAL);
  1127. }
  1128. }
  1129. ret = queue_alloc(&mux->queue, mux->nb_streams, mux->queue_size,
  1130. QUEUE_PACKETS);
  1131. if (ret < 0)
  1132. return ret;
  1133. }
  1134. for (unsigned i = 0; i < sch->nb_filters; i++) {
  1135. SchFilterGraph *fg = &sch->filters[i];
  1136. for (unsigned j = 0; j < fg->nb_inputs; j++) {
  1137. SchFilterIn *fi = &fg->inputs[j];
  1138. SchDec *dec;
  1139. if (!fi->src.type) {
  1140. av_log(fg, AV_LOG_ERROR,
  1141. "Filtergraph input %u not connected to a source\n", j);
  1142. return AVERROR(EINVAL);
  1143. }
  1144. av_assert0(fi->src.type == SCH_NODE_TYPE_DEC);
  1145. dec = &sch->dec[fi->src.idx];
  1146. switch (dec->src.type) {
  1147. case SCH_NODE_TYPE_DEMUX: fi->src_sched = dec->src; break;
  1148. case SCH_NODE_TYPE_ENC: fi->src_sched = sch->enc[dec->src.idx].src; break;
  1149. default: av_assert0(0);
  1150. }
  1151. }
  1152. for (unsigned j = 0; j < fg->nb_outputs; j++) {
  1153. SchFilterOut *fo = &fg->outputs[j];
  1154. if (!fo->dst.type) {
  1155. av_log(fg, AV_LOG_ERROR,
  1156. "Filtergraph %u output %u not connected to a sink\n", i, j);
  1157. return AVERROR(EINVAL);
  1158. }
  1159. }
  1160. }
  1161. // Check that the transcoding graph has no cycles.
  1162. ret = check_acyclic(sch);
  1163. if (ret < 0)
  1164. return ret;
  1165. return 0;
  1166. }
  1167. int sch_start(Scheduler *sch)
  1168. {
  1169. int ret;
  1170. ret = start_prepare(sch);
  1171. if (ret < 0)
  1172. return ret;
  1173. av_assert0(sch->state == SCH_STATE_UNINIT);
  1174. sch->state = SCH_STATE_STARTED;
  1175. for (unsigned i = 0; i < sch->nb_mux; i++) {
  1176. SchMux *mux = &sch->mux[i];
  1177. if (mux->nb_streams_ready == mux->nb_streams) {
  1178. ret = mux_init(sch, mux);
  1179. if (ret < 0)
  1180. goto fail;
  1181. }
  1182. }
  1183. for (unsigned i = 0; i < sch->nb_enc; i++) {
  1184. SchEnc *enc = &sch->enc[i];
  1185. ret = task_start(&enc->task);
  1186. if (ret < 0)
  1187. goto fail;
  1188. }
  1189. for (unsigned i = 0; i < sch->nb_filters; i++) {
  1190. SchFilterGraph *fg = &sch->filters[i];
  1191. ret = task_start(&fg->task);
  1192. if (ret < 0)
  1193. goto fail;
  1194. }
  1195. for (unsigned i = 0; i < sch->nb_dec; i++) {
  1196. SchDec *dec = &sch->dec[i];
  1197. ret = task_start(&dec->task);
  1198. if (ret < 0)
  1199. goto fail;
  1200. }
  1201. for (unsigned i = 0; i < sch->nb_demux; i++) {
  1202. SchDemux *d = &sch->demux[i];
  1203. if (!d->nb_streams)
  1204. continue;
  1205. ret = task_start(&d->task);
  1206. if (ret < 0)
  1207. goto fail;
  1208. }
  1209. pthread_mutex_lock(&sch->schedule_lock);
  1210. schedule_update_locked(sch);
  1211. pthread_mutex_unlock(&sch->schedule_lock);
  1212. return 0;
  1213. fail:
  1214. sch_stop(sch, NULL);
  1215. return ret;
  1216. }
  1217. int sch_wait(Scheduler *sch, uint64_t timeout_us, int64_t *transcode_ts)
  1218. {
  1219. int ret, err;
  1220. // convert delay to absolute timestamp
  1221. timeout_us += av_gettime();
  1222. pthread_mutex_lock(&sch->mux_done_lock);
  1223. if (sch->nb_mux_done < sch->nb_mux) {
  1224. struct timespec tv = { .tv_sec = timeout_us / 1000000,
  1225. .tv_nsec = (timeout_us % 1000000) * 1000 };
  1226. pthread_cond_timedwait(&sch->mux_done_cond, &sch->mux_done_lock, &tv);
  1227. }
  1228. ret = sch->nb_mux_done == sch->nb_mux;
  1229. pthread_mutex_unlock(&sch->mux_done_lock);
  1230. *transcode_ts = atomic_load(&sch->last_dts);
  1231. // abort transcoding if any task failed
  1232. err = atomic_load(&sch->task_failed);
  1233. return ret || err;
  1234. }
  1235. static int enc_open(Scheduler *sch, SchEnc *enc, const AVFrame *frame)
  1236. {
  1237. int ret;
  1238. ret = enc->open_cb(enc->task.func_arg, frame);
  1239. if (ret < 0)
  1240. return ret;
  1241. // ret>0 signals audio frame size, which means sync queue must
  1242. // have been enabled during encoder creation
  1243. if (ret > 0) {
  1244. SchSyncQueue *sq;
  1245. av_assert0(enc->sq_idx[0] >= 0);
  1246. sq = &sch->sq_enc[enc->sq_idx[0]];
  1247. pthread_mutex_lock(&sq->lock);
  1248. sq_frame_samples(sq->sq, enc->sq_idx[1], ret);
  1249. pthread_mutex_unlock(&sq->lock);
  1250. }
  1251. return 0;
  1252. }
  1253. static int send_to_enc_thread(Scheduler *sch, SchEnc *enc, AVFrame *frame)
  1254. {
  1255. int ret;
  1256. if (!frame) {
  1257. tq_send_finish(enc->queue, 0);
  1258. return 0;
  1259. }
  1260. if (enc->in_finished)
  1261. return AVERROR_EOF;
  1262. ret = tq_send(enc->queue, 0, frame);
  1263. if (ret < 0)
  1264. enc->in_finished = 1;
  1265. return ret;
  1266. }
  1267. static int send_to_enc_sq(Scheduler *sch, SchEnc *enc, AVFrame *frame)
  1268. {
  1269. SchSyncQueue *sq = &sch->sq_enc[enc->sq_idx[0]];
  1270. int ret = 0;
  1271. // inform the scheduling code that no more input will arrive along this path;
  1272. // this is necessary because the sync queue may not send an EOF downstream
  1273. // until other streams finish
  1274. // TODO: consider a cleaner way of passing this information through
  1275. // the pipeline
  1276. if (!frame) {
  1277. for (unsigned i = 0; i < enc->nb_dst; i++) {
  1278. SchMux *mux;
  1279. SchMuxStream *ms;
  1280. if (enc->dst[i].type != SCH_NODE_TYPE_MUX)
  1281. continue;
  1282. mux = &sch->mux[enc->dst[i].idx];
  1283. ms = &mux->streams[enc->dst[i].idx_stream];
  1284. pthread_mutex_lock(&sch->schedule_lock);
  1285. ms->source_finished = 1;
  1286. schedule_update_locked(sch);
  1287. pthread_mutex_unlock(&sch->schedule_lock);
  1288. }
  1289. }
  1290. pthread_mutex_lock(&sq->lock);
  1291. ret = sq_send(sq->sq, enc->sq_idx[1], SQFRAME(frame));
  1292. if (ret < 0)
  1293. goto finish;
  1294. while (1) {
  1295. SchEnc *enc;
  1296. // TODO: the SQ API should be extended to allow returning EOF
  1297. // for individual streams
  1298. ret = sq_receive(sq->sq, -1, SQFRAME(sq->frame));
  1299. if (ret < 0) {
  1300. ret = (ret == AVERROR(EAGAIN)) ? 0 : ret;
  1301. break;
  1302. }
  1303. enc = &sch->enc[sq->enc_idx[ret]];
  1304. ret = send_to_enc_thread(sch, enc, sq->frame);
  1305. if (ret < 0) {
  1306. av_frame_unref(sq->frame);
  1307. if (ret != AVERROR_EOF)
  1308. break;
  1309. sq_send(sq->sq, enc->sq_idx[1], SQFRAME(NULL));
  1310. continue;
  1311. }
  1312. }
  1313. if (ret < 0) {
  1314. // close all encoders fed from this sync queue
  1315. for (unsigned i = 0; i < sq->nb_enc_idx; i++) {
  1316. int err = send_to_enc_thread(sch, &sch->enc[sq->enc_idx[i]], NULL);
  1317. // if the sync queue error is EOF and closing the encoder
  1318. // produces a more serious error, make sure to pick the latter
  1319. ret = err_merge((ret == AVERROR_EOF && err < 0) ? 0 : ret, err);
  1320. }
  1321. }
  1322. finish:
  1323. pthread_mutex_unlock(&sq->lock);
  1324. return ret;
  1325. }
  1326. static int send_to_enc(Scheduler *sch, SchEnc *enc, AVFrame *frame)
  1327. {
  1328. if (enc->open_cb && frame && !enc->opened) {
  1329. int ret = enc_open(sch, enc, frame);
  1330. if (ret < 0)
  1331. return ret;
  1332. enc->opened = 1;
  1333. // discard empty frames that only carry encoder init parameters
  1334. if (!frame->buf[0]) {
  1335. av_frame_unref(frame);
  1336. return 0;
  1337. }
  1338. }
  1339. return (enc->sq_idx[0] >= 0) ?
  1340. send_to_enc_sq (sch, enc, frame) :
  1341. send_to_enc_thread(sch, enc, frame);
  1342. }
  1343. static int mux_queue_packet(SchMux *mux, SchMuxStream *ms, AVPacket *pkt)
  1344. {
  1345. PreMuxQueue *q = &ms->pre_mux_queue;
  1346. AVPacket *tmp_pkt = NULL;
  1347. int ret;
  1348. if (!av_fifo_can_write(q->fifo)) {
  1349. size_t packets = av_fifo_can_read(q->fifo);
  1350. size_t pkt_size = pkt ? pkt->size : 0;
  1351. int thresh_reached = (q->data_size + pkt_size) > q->data_threshold;
  1352. size_t max_packets = thresh_reached ? q->max_packets : SIZE_MAX;
  1353. size_t new_size = FFMIN(2 * packets, max_packets);
  1354. if (new_size <= packets) {
  1355. av_log(mux, AV_LOG_ERROR,
  1356. "Too many packets buffered for output stream.\n");
  1357. return AVERROR(ENOSPC);
  1358. }
  1359. ret = av_fifo_grow2(q->fifo, new_size - packets);
  1360. if (ret < 0)
  1361. return ret;
  1362. }
  1363. if (pkt) {
  1364. tmp_pkt = av_packet_alloc();
  1365. if (!tmp_pkt)
  1366. return AVERROR(ENOMEM);
  1367. av_packet_move_ref(tmp_pkt, pkt);
  1368. q->data_size += tmp_pkt->size;
  1369. }
  1370. av_fifo_write(q->fifo, &tmp_pkt, 1);
  1371. return 0;
  1372. }
  1373. static int send_to_mux(Scheduler *sch, SchMux *mux, unsigned stream_idx,
  1374. AVPacket *pkt)
  1375. {
  1376. SchMuxStream *ms = &mux->streams[stream_idx];
  1377. int64_t dts = (pkt && pkt->dts != AV_NOPTS_VALUE) ?
  1378. av_rescale_q(pkt->dts + pkt->duration, pkt->time_base, AV_TIME_BASE_Q) :
  1379. AV_NOPTS_VALUE;
  1380. // queue the packet if the muxer cannot be started yet
  1381. if (!atomic_load(&mux->mux_started)) {
  1382. int queued = 0;
  1383. // the muxer could have started between the above atomic check and
  1384. // locking the mutex, then this block falls through to normal send path
  1385. pthread_mutex_lock(&sch->mux_ready_lock);
  1386. if (!atomic_load(&mux->mux_started)) {
  1387. int ret = mux_queue_packet(mux, ms, pkt);
  1388. queued = ret < 0 ? ret : 1;
  1389. }
  1390. pthread_mutex_unlock(&sch->mux_ready_lock);
  1391. if (queued < 0)
  1392. return queued;
  1393. else if (queued)
  1394. goto update_schedule;
  1395. }
  1396. if (pkt) {
  1397. int ret;
  1398. if (ms->init_eof)
  1399. return AVERROR_EOF;
  1400. ret = tq_send(mux->queue, stream_idx, pkt);
  1401. if (ret < 0)
  1402. return ret;
  1403. } else
  1404. tq_send_finish(mux->queue, stream_idx);
  1405. update_schedule:
  1406. // TODO: use atomics to check whether this changes trailing dts
  1407. // to avoid locking unnecesarily
  1408. if (dts != AV_NOPTS_VALUE || !pkt) {
  1409. pthread_mutex_lock(&sch->schedule_lock);
  1410. if (pkt) ms->last_dts = dts;
  1411. else ms->source_finished = 1;
  1412. schedule_update_locked(sch);
  1413. pthread_mutex_unlock(&sch->schedule_lock);
  1414. }
  1415. return 0;
  1416. }
  1417. static int
  1418. demux_stream_send_to_dst(Scheduler *sch, const SchedulerNode dst,
  1419. uint8_t *dst_finished, AVPacket *pkt, unsigned flags)
  1420. {
  1421. int ret;
  1422. if (*dst_finished)
  1423. return AVERROR_EOF;
  1424. if (pkt && dst.type == SCH_NODE_TYPE_MUX &&
  1425. (flags & DEMUX_SEND_STREAMCOPY_EOF)) {
  1426. av_packet_unref(pkt);
  1427. pkt = NULL;
  1428. }
  1429. if (!pkt)
  1430. goto finish;
  1431. ret = (dst.type == SCH_NODE_TYPE_MUX) ?
  1432. send_to_mux(sch, &sch->mux[dst.idx], dst.idx_stream, pkt) :
  1433. tq_send(sch->dec[dst.idx].queue, 0, pkt);
  1434. if (ret == AVERROR_EOF)
  1435. goto finish;
  1436. return ret;
  1437. finish:
  1438. if (dst.type == SCH_NODE_TYPE_MUX)
  1439. send_to_mux(sch, &sch->mux[dst.idx], dst.idx_stream, NULL);
  1440. else
  1441. tq_send_finish(sch->dec[dst.idx].queue, 0);
  1442. *dst_finished = 1;
  1443. return AVERROR_EOF;
  1444. }
  1445. static int demux_send_for_stream(Scheduler *sch, SchDemux *d, SchDemuxStream *ds,
  1446. AVPacket *pkt, unsigned flags)
  1447. {
  1448. unsigned nb_done = 0;
  1449. for (unsigned i = 0; i < ds->nb_dst; i++) {
  1450. AVPacket *to_send = pkt;
  1451. uint8_t *finished = &ds->dst_finished[i];
  1452. int ret;
  1453. // sending a packet consumes it, so make a temporary reference if needed
  1454. if (pkt && i < ds->nb_dst - 1) {
  1455. to_send = d->send_pkt;
  1456. ret = av_packet_ref(to_send, pkt);
  1457. if (ret < 0)
  1458. return ret;
  1459. }
  1460. ret = demux_stream_send_to_dst(sch, ds->dst[i], finished, to_send, flags);
  1461. if (to_send)
  1462. av_packet_unref(to_send);
  1463. if (ret == AVERROR_EOF)
  1464. nb_done++;
  1465. else if (ret < 0)
  1466. return ret;
  1467. }
  1468. return (nb_done == ds->nb_dst) ? AVERROR_EOF : 0;
  1469. }
  1470. static int demux_flush(Scheduler *sch, SchDemux *d, AVPacket *pkt)
  1471. {
  1472. Timestamp max_end_ts = (Timestamp){ .ts = AV_NOPTS_VALUE };
  1473. av_assert0(!pkt->buf && !pkt->data && !pkt->side_data_elems);
  1474. for (unsigned i = 0; i < d->nb_streams; i++) {
  1475. SchDemuxStream *ds = &d->streams[i];
  1476. for (unsigned j = 0; j < ds->nb_dst; j++) {
  1477. const SchedulerNode *dst = &ds->dst[j];
  1478. SchDec *dec;
  1479. int ret;
  1480. if (ds->dst_finished[j] || dst->type != SCH_NODE_TYPE_DEC)
  1481. continue;
  1482. dec = &sch->dec[dst->idx];
  1483. ret = tq_send(dec->queue, 0, pkt);
  1484. if (ret < 0)
  1485. return ret;
  1486. if (dec->queue_end_ts) {
  1487. Timestamp ts;
  1488. ret = av_thread_message_queue_recv(dec->queue_end_ts, &ts, 0);
  1489. if (ret < 0)
  1490. return ret;
  1491. if (max_end_ts.ts == AV_NOPTS_VALUE ||
  1492. (ts.ts != AV_NOPTS_VALUE &&
  1493. av_compare_ts(max_end_ts.ts, max_end_ts.tb, ts.ts, ts.tb) < 0))
  1494. max_end_ts = ts;
  1495. }
  1496. }
  1497. }
  1498. pkt->pts = max_end_ts.ts;
  1499. pkt->time_base = max_end_ts.tb;
  1500. return 0;
  1501. }
  1502. int sch_demux_send(Scheduler *sch, unsigned demux_idx, AVPacket *pkt,
  1503. unsigned flags)
  1504. {
  1505. SchDemux *d;
  1506. int terminate;
  1507. av_assert0(demux_idx < sch->nb_demux);
  1508. d = &sch->demux[demux_idx];
  1509. terminate = waiter_wait(sch, &d->waiter);
  1510. if (terminate)
  1511. return AVERROR_EXIT;
  1512. // flush the downstreams after seek
  1513. if (pkt->stream_index == -1)
  1514. return demux_flush(sch, d, pkt);
  1515. av_assert0(pkt->stream_index < d->nb_streams);
  1516. return demux_send_for_stream(sch, d, &d->streams[pkt->stream_index], pkt, flags);
  1517. }
  1518. static int demux_done(Scheduler *sch, unsigned demux_idx)
  1519. {
  1520. SchDemux *d = &sch->demux[demux_idx];
  1521. int ret = 0;
  1522. for (unsigned i = 0; i < d->nb_streams; i++) {
  1523. int err = demux_send_for_stream(sch, d, &d->streams[i], NULL, 0);
  1524. if (err != AVERROR_EOF)
  1525. ret = err_merge(ret, err);
  1526. }
  1527. pthread_mutex_lock(&sch->schedule_lock);
  1528. d->task_exited = 1;
  1529. schedule_update_locked(sch);
  1530. pthread_mutex_unlock(&sch->schedule_lock);
  1531. return ret;
  1532. }
  1533. int sch_mux_receive(Scheduler *sch, unsigned mux_idx, AVPacket *pkt)
  1534. {
  1535. SchMux *mux;
  1536. int ret, stream_idx;
  1537. av_assert0(mux_idx < sch->nb_mux);
  1538. mux = &sch->mux[mux_idx];
  1539. ret = tq_receive(mux->queue, &stream_idx, pkt);
  1540. pkt->stream_index = stream_idx;
  1541. return ret;
  1542. }
  1543. void sch_mux_receive_finish(Scheduler *sch, unsigned mux_idx, unsigned stream_idx)
  1544. {
  1545. SchMux *mux;
  1546. av_assert0(mux_idx < sch->nb_mux);
  1547. mux = &sch->mux[mux_idx];
  1548. av_assert0(stream_idx < mux->nb_streams);
  1549. tq_receive_finish(mux->queue, stream_idx);
  1550. pthread_mutex_lock(&sch->schedule_lock);
  1551. mux->streams[stream_idx].source_finished = 1;
  1552. schedule_update_locked(sch);
  1553. pthread_mutex_unlock(&sch->schedule_lock);
  1554. }
  1555. int sch_mux_sub_heartbeat(Scheduler *sch, unsigned mux_idx, unsigned stream_idx,
  1556. const AVPacket *pkt)
  1557. {
  1558. SchMux *mux;
  1559. SchMuxStream *ms;
  1560. av_assert0(mux_idx < sch->nb_mux);
  1561. mux = &sch->mux[mux_idx];
  1562. av_assert0(stream_idx < mux->nb_streams);
  1563. ms = &mux->streams[stream_idx];
  1564. for (unsigned i = 0; i < ms->nb_sub_heartbeat_dst; i++) {
  1565. SchDec *dst = &sch->dec[ms->sub_heartbeat_dst[i]];
  1566. int ret;
  1567. ret = av_packet_copy_props(mux->sub_heartbeat_pkt, pkt);
  1568. if (ret < 0)
  1569. return ret;
  1570. tq_send(dst->queue, 0, mux->sub_heartbeat_pkt);
  1571. }
  1572. return 0;
  1573. }
  1574. static int mux_done(Scheduler *sch, unsigned mux_idx)
  1575. {
  1576. SchMux *mux = &sch->mux[mux_idx];
  1577. pthread_mutex_lock(&sch->schedule_lock);
  1578. for (unsigned i = 0; i < mux->nb_streams; i++) {
  1579. tq_receive_finish(mux->queue, i);
  1580. mux->streams[i].source_finished = 1;
  1581. }
  1582. schedule_update_locked(sch);
  1583. pthread_mutex_unlock(&sch->schedule_lock);
  1584. pthread_mutex_lock(&sch->mux_done_lock);
  1585. av_assert0(sch->nb_mux_done < sch->nb_mux);
  1586. sch->nb_mux_done++;
  1587. pthread_cond_signal(&sch->mux_done_cond);
  1588. pthread_mutex_unlock(&sch->mux_done_lock);
  1589. return 0;
  1590. }
  1591. int sch_dec_receive(Scheduler *sch, unsigned dec_idx, AVPacket *pkt)
  1592. {
  1593. SchDec *dec;
  1594. int ret, dummy;
  1595. av_assert0(dec_idx < sch->nb_dec);
  1596. dec = &sch->dec[dec_idx];
  1597. // the decoder should have given us post-flush end timestamp in pkt
  1598. if (dec->expect_end_ts) {
  1599. Timestamp ts = (Timestamp){ .ts = pkt->pts, .tb = pkt->time_base };
  1600. ret = av_thread_message_queue_send(dec->queue_end_ts, &ts, 0);
  1601. if (ret < 0)
  1602. return ret;
  1603. dec->expect_end_ts = 0;
  1604. }
  1605. ret = tq_receive(dec->queue, &dummy, pkt);
  1606. av_assert0(dummy <= 0);
  1607. // got a flush packet, on the next call to this function the decoder
  1608. // will give us post-flush end timestamp
  1609. if (ret >= 0 && !pkt->data && !pkt->side_data_elems && dec->queue_end_ts)
  1610. dec->expect_end_ts = 1;
  1611. return ret;
  1612. }
  1613. static int send_to_filter(Scheduler *sch, SchFilterGraph *fg,
  1614. unsigned in_idx, AVFrame *frame)
  1615. {
  1616. if (frame)
  1617. return tq_send(fg->queue, in_idx, frame);
  1618. if (!fg->inputs[in_idx].send_finished) {
  1619. fg->inputs[in_idx].send_finished = 1;
  1620. tq_send_finish(fg->queue, in_idx);
  1621. // close the control stream when all actual inputs are done
  1622. if (atomic_fetch_add(&fg->nb_inputs_finished_send, 1) == fg->nb_inputs - 1)
  1623. tq_send_finish(fg->queue, fg->nb_inputs);
  1624. }
  1625. return 0;
  1626. }
  1627. static int dec_send_to_dst(Scheduler *sch, const SchedulerNode dst,
  1628. uint8_t *dst_finished, AVFrame *frame)
  1629. {
  1630. int ret;
  1631. if (*dst_finished)
  1632. return AVERROR_EOF;
  1633. if (!frame)
  1634. goto finish;
  1635. ret = (dst.type == SCH_NODE_TYPE_FILTER_IN) ?
  1636. send_to_filter(sch, &sch->filters[dst.idx], dst.idx_stream, frame) :
  1637. send_to_enc(sch, &sch->enc[dst.idx], frame);
  1638. if (ret == AVERROR_EOF)
  1639. goto finish;
  1640. return ret;
  1641. finish:
  1642. if (dst.type == SCH_NODE_TYPE_FILTER_IN)
  1643. send_to_filter(sch, &sch->filters[dst.idx], dst.idx_stream, NULL);
  1644. else
  1645. send_to_enc(sch, &sch->enc[dst.idx], NULL);
  1646. *dst_finished = 1;
  1647. return AVERROR_EOF;
  1648. }
  1649. int sch_dec_send(Scheduler *sch, unsigned dec_idx, AVFrame *frame)
  1650. {
  1651. SchDec *dec;
  1652. int ret = 0;
  1653. unsigned nb_done = 0;
  1654. av_assert0(dec_idx < sch->nb_dec);
  1655. dec = &sch->dec[dec_idx];
  1656. for (unsigned i = 0; i < dec->nb_dst; i++) {
  1657. uint8_t *finished = &dec->dst_finished[i];
  1658. AVFrame *to_send = frame;
  1659. // sending a frame consumes it, so make a temporary reference if needed
  1660. if (i < dec->nb_dst - 1) {
  1661. to_send = dec->send_frame;
  1662. // frame may sometimes contain props only,
  1663. // e.g. to signal EOF timestamp
  1664. ret = frame->buf[0] ? av_frame_ref(to_send, frame) :
  1665. av_frame_copy_props(to_send, frame);
  1666. if (ret < 0)
  1667. return ret;
  1668. }
  1669. ret = dec_send_to_dst(sch, dec->dst[i], finished, to_send);
  1670. if (ret < 0) {
  1671. av_frame_unref(to_send);
  1672. if (ret == AVERROR_EOF) {
  1673. nb_done++;
  1674. ret = 0;
  1675. continue;
  1676. }
  1677. return ret;
  1678. }
  1679. }
  1680. return (nb_done == dec->nb_dst) ? AVERROR_EOF : 0;
  1681. }
  1682. static int dec_done(Scheduler *sch, unsigned dec_idx)
  1683. {
  1684. SchDec *dec = &sch->dec[dec_idx];
  1685. int ret = 0;
  1686. tq_receive_finish(dec->queue, 0);
  1687. // make sure our source does not get stuck waiting for end timestamps
  1688. // that will never arrive
  1689. if (dec->queue_end_ts)
  1690. av_thread_message_queue_set_err_recv(dec->queue_end_ts, AVERROR_EOF);
  1691. for (unsigned i = 0; i < dec->nb_dst; i++) {
  1692. int err = dec_send_to_dst(sch, dec->dst[i], &dec->dst_finished[i], NULL);
  1693. if (err < 0 && err != AVERROR_EOF)
  1694. ret = err_merge(ret, err);
  1695. }
  1696. return ret;
  1697. }
  1698. int sch_enc_receive(Scheduler *sch, unsigned enc_idx, AVFrame *frame)
  1699. {
  1700. SchEnc *enc;
  1701. int ret, dummy;
  1702. av_assert0(enc_idx < sch->nb_enc);
  1703. enc = &sch->enc[enc_idx];
  1704. ret = tq_receive(enc->queue, &dummy, frame);
  1705. av_assert0(dummy <= 0);
  1706. return ret;
  1707. }
  1708. static int enc_send_to_dst(Scheduler *sch, const SchedulerNode dst,
  1709. uint8_t *dst_finished, AVPacket *pkt)
  1710. {
  1711. int ret;
  1712. if (*dst_finished)
  1713. return AVERROR_EOF;
  1714. if (!pkt)
  1715. goto finish;
  1716. ret = (dst.type == SCH_NODE_TYPE_MUX) ?
  1717. send_to_mux(sch, &sch->mux[dst.idx], dst.idx_stream, pkt) :
  1718. tq_send(sch->dec[dst.idx].queue, 0, pkt);
  1719. if (ret == AVERROR_EOF)
  1720. goto finish;
  1721. return ret;
  1722. finish:
  1723. if (dst.type == SCH_NODE_TYPE_MUX)
  1724. send_to_mux(sch, &sch->mux[dst.idx], dst.idx_stream, NULL);
  1725. else
  1726. tq_send_finish(sch->dec[dst.idx].queue, 0);
  1727. *dst_finished = 1;
  1728. return AVERROR_EOF;
  1729. }
  1730. int sch_enc_send(Scheduler *sch, unsigned enc_idx, AVPacket *pkt)
  1731. {
  1732. SchEnc *enc;
  1733. int ret;
  1734. av_assert0(enc_idx < sch->nb_enc);
  1735. enc = &sch->enc[enc_idx];
  1736. for (unsigned i = 0; i < enc->nb_dst; i++) {
  1737. uint8_t *finished = &enc->dst_finished[i];
  1738. AVPacket *to_send = pkt;
  1739. // sending a packet consumes it, so make a temporary reference if needed
  1740. if (i < enc->nb_dst - 1) {
  1741. to_send = enc->send_pkt;
  1742. ret = av_packet_ref(to_send, pkt);
  1743. if (ret < 0)
  1744. return ret;
  1745. }
  1746. ret = enc_send_to_dst(sch, enc->dst[i], finished, to_send);
  1747. if (ret < 0) {
  1748. av_packet_unref(to_send);
  1749. if (ret == AVERROR_EOF) {
  1750. ret = 0;
  1751. continue;
  1752. }
  1753. return ret;
  1754. }
  1755. }
  1756. return ret;
  1757. }
  1758. static int enc_done(Scheduler *sch, unsigned enc_idx)
  1759. {
  1760. SchEnc *enc = &sch->enc[enc_idx];
  1761. int ret = 0;
  1762. tq_receive_finish(enc->queue, 0);
  1763. for (unsigned i = 0; i < enc->nb_dst; i++) {
  1764. int err = enc_send_to_dst(sch, enc->dst[i], &enc->dst_finished[i], NULL);
  1765. if (err < 0 && err != AVERROR_EOF)
  1766. ret = err_merge(ret, err);
  1767. }
  1768. return ret;
  1769. }
  1770. int sch_filter_receive(Scheduler *sch, unsigned fg_idx,
  1771. unsigned *in_idx, AVFrame *frame)
  1772. {
  1773. SchFilterGraph *fg;
  1774. av_assert0(fg_idx < sch->nb_filters);
  1775. fg = &sch->filters[fg_idx];
  1776. av_assert0(*in_idx <= fg->nb_inputs);
  1777. // update scheduling to account for desired input stream, if it changed
  1778. //
  1779. // this check needs no locking because only the filtering thread
  1780. // updates this value
  1781. if (*in_idx != fg->best_input) {
  1782. pthread_mutex_lock(&sch->schedule_lock);
  1783. fg->best_input = *in_idx;
  1784. schedule_update_locked(sch);
  1785. pthread_mutex_unlock(&sch->schedule_lock);
  1786. }
  1787. if (*in_idx == fg->nb_inputs) {
  1788. int terminate = waiter_wait(sch, &fg->waiter);
  1789. return terminate ? AVERROR_EOF : AVERROR(EAGAIN);
  1790. }
  1791. while (1) {
  1792. int ret, idx;
  1793. ret = tq_receive(fg->queue, &idx, frame);
  1794. if (idx < 0)
  1795. return AVERROR_EOF;
  1796. else if (ret >= 0) {
  1797. *in_idx = idx;
  1798. return 0;
  1799. }
  1800. // disregard EOFs for specific streams - they should always be
  1801. // preceded by an EOF frame
  1802. }
  1803. }
  1804. void sch_filter_receive_finish(Scheduler *sch, unsigned fg_idx, unsigned in_idx)
  1805. {
  1806. SchFilterGraph *fg;
  1807. SchFilterIn *fi;
  1808. av_assert0(fg_idx < sch->nb_filters);
  1809. fg = &sch->filters[fg_idx];
  1810. av_assert0(in_idx < fg->nb_inputs);
  1811. fi = &fg->inputs[in_idx];
  1812. if (!fi->receive_finished) {
  1813. fi->receive_finished = 1;
  1814. tq_receive_finish(fg->queue, in_idx);
  1815. // close the control stream when all actual inputs are done
  1816. if (++fg->nb_inputs_finished_receive == fg->nb_inputs)
  1817. tq_receive_finish(fg->queue, fg->nb_inputs);
  1818. }
  1819. }
  1820. int sch_filter_send(Scheduler *sch, unsigned fg_idx, unsigned out_idx, AVFrame *frame)
  1821. {
  1822. SchFilterGraph *fg;
  1823. av_assert0(fg_idx < sch->nb_filters);
  1824. fg = &sch->filters[fg_idx];
  1825. av_assert0(out_idx < fg->nb_outputs);
  1826. return send_to_enc(sch, &sch->enc[fg->outputs[out_idx].dst.idx], frame);
  1827. }
  1828. static int filter_done(Scheduler *sch, unsigned fg_idx)
  1829. {
  1830. SchFilterGraph *fg = &sch->filters[fg_idx];
  1831. int ret = 0;
  1832. for (unsigned i = 0; i <= fg->nb_inputs; i++)
  1833. tq_receive_finish(fg->queue, i);
  1834. for (unsigned i = 0; i < fg->nb_outputs; i++) {
  1835. SchEnc *enc = &sch->enc[fg->outputs[i].dst.idx];
  1836. int err = send_to_enc(sch, enc, NULL);
  1837. if (err < 0 && err != AVERROR_EOF)
  1838. ret = err_merge(ret, err);
  1839. }
  1840. pthread_mutex_lock(&sch->schedule_lock);
  1841. fg->task_exited = 1;
  1842. schedule_update_locked(sch);
  1843. pthread_mutex_unlock(&sch->schedule_lock);
  1844. return ret;
  1845. }
  1846. int sch_filter_command(Scheduler *sch, unsigned fg_idx, AVFrame *frame)
  1847. {
  1848. SchFilterGraph *fg;
  1849. av_assert0(fg_idx < sch->nb_filters);
  1850. fg = &sch->filters[fg_idx];
  1851. return send_to_filter(sch, fg, fg->nb_inputs, frame);
  1852. }
  1853. static int task_cleanup(Scheduler *sch, SchedulerNode node)
  1854. {
  1855. switch (node.type) {
  1856. case SCH_NODE_TYPE_DEMUX: return demux_done (sch, node.idx);
  1857. case SCH_NODE_TYPE_MUX: return mux_done (sch, node.idx);
  1858. case SCH_NODE_TYPE_DEC: return dec_done (sch, node.idx);
  1859. case SCH_NODE_TYPE_ENC: return enc_done (sch, node.idx);
  1860. case SCH_NODE_TYPE_FILTER_IN: return filter_done(sch, node.idx);
  1861. default: av_assert0(0);
  1862. }
  1863. }
  1864. static void *task_wrapper(void *arg)
  1865. {
  1866. SchTask *task = arg;
  1867. Scheduler *sch = task->parent;
  1868. int ret;
  1869. int err = 0;
  1870. ret = task->func(task->func_arg);
  1871. if (ret < 0)
  1872. av_log(task->func_arg, AV_LOG_ERROR,
  1873. "Task finished with error code: %d (%s)\n", ret, av_err2str(ret));
  1874. err = task_cleanup(sch, task->node);
  1875. ret = err_merge(ret, err);
  1876. // EOF is considered normal termination
  1877. if (ret == AVERROR_EOF)
  1878. ret = 0;
  1879. if (ret < 0)
  1880. atomic_store(&sch->task_failed, 1);
  1881. av_log(task->func_arg, ret < 0 ? AV_LOG_ERROR : AV_LOG_VERBOSE,
  1882. "Terminating thread with return code %d (%s)\n", ret,
  1883. ret < 0 ? av_err2str(ret) : "success");
  1884. return (void*)(intptr_t)ret;
  1885. }
  1886. static int task_stop(Scheduler *sch, SchTask *task)
  1887. {
  1888. int ret;
  1889. void *thread_ret;
  1890. if (!task->thread_running)
  1891. return task_cleanup(sch, task->node);
  1892. ret = pthread_join(task->thread, &thread_ret);
  1893. av_assert0(ret == 0);
  1894. task->thread_running = 0;
  1895. return (intptr_t)thread_ret;
  1896. }
  1897. int sch_stop(Scheduler *sch, int64_t *finish_ts)
  1898. {
  1899. int ret = 0, err;
  1900. if (sch->state != SCH_STATE_STARTED)
  1901. return 0;
  1902. atomic_store(&sch->terminate, 1);
  1903. for (unsigned type = 0; type < 2; type++)
  1904. for (unsigned i = 0; i < (type ? sch->nb_demux : sch->nb_filters); i++) {
  1905. SchWaiter *w = type ? &sch->demux[i].waiter : &sch->filters[i].waiter;
  1906. waiter_set(w, 1);
  1907. }
  1908. for (unsigned i = 0; i < sch->nb_demux; i++) {
  1909. SchDemux *d = &sch->demux[i];
  1910. err = task_stop(sch, &d->task);
  1911. ret = err_merge(ret, err);
  1912. }
  1913. for (unsigned i = 0; i < sch->nb_dec; i++) {
  1914. SchDec *dec = &sch->dec[i];
  1915. err = task_stop(sch, &dec->task);
  1916. ret = err_merge(ret, err);
  1917. }
  1918. for (unsigned i = 0; i < sch->nb_filters; i++) {
  1919. SchFilterGraph *fg = &sch->filters[i];
  1920. err = task_stop(sch, &fg->task);
  1921. ret = err_merge(ret, err);
  1922. }
  1923. for (unsigned i = 0; i < sch->nb_enc; i++) {
  1924. SchEnc *enc = &sch->enc[i];
  1925. err = task_stop(sch, &enc->task);
  1926. ret = err_merge(ret, err);
  1927. }
  1928. for (unsigned i = 0; i < sch->nb_mux; i++) {
  1929. SchMux *mux = &sch->mux[i];
  1930. err = task_stop(sch, &mux->task);
  1931. ret = err_merge(ret, err);
  1932. }
  1933. if (finish_ts)
  1934. *finish_ts = trailing_dts(sch, 1);
  1935. sch->state = SCH_STATE_STOPPED;
  1936. return ret;
  1937. }