You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

812 lines
25KB

  1. /*
  2. * This file is part of Libav.
  3. *
  4. * Libav is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * Libav is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with Libav; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. /**
  19. * @file
  20. * Frame multithreading support functions
  21. * @see doc/multithreading.txt
  22. */
  23. #include "config.h"
  24. #include <stdatomic.h>
  25. #include <stdint.h>
  26. #if HAVE_PTHREADS
  27. #include <pthread.h>
  28. #elif HAVE_W32THREADS
  29. #include "compat/w32pthreads.h"
  30. #endif
  31. #include "avcodec.h"
  32. #include "internal.h"
  33. #include "pthread_internal.h"
  34. #include "thread.h"
  35. #include "version.h"
  36. #include "libavutil/avassert.h"
  37. #include "libavutil/buffer.h"
  38. #include "libavutil/common.h"
  39. #include "libavutil/cpu.h"
  40. #include "libavutil/frame.h"
  41. #include "libavutil/internal.h"
  42. #include "libavutil/log.h"
  43. #include "libavutil/mem.h"
  44. enum {
  45. ///< Set when the thread is awaiting a packet.
  46. STATE_INPUT_READY,
  47. ///< Set before the codec has called ff_thread_finish_setup().
  48. STATE_SETTING_UP,
  49. /**
  50. * Set when the codec calls get_buffer().
  51. * State is returned to STATE_SETTING_UP afterwards.
  52. */
  53. STATE_GET_BUFFER,
  54. ///< Set after the codec has called ff_thread_finish_setup().
  55. STATE_SETUP_FINISHED,
  56. };
  57. /**
  58. * Context used by codec threads and stored in their AVCodecInternal thread_ctx.
  59. */
  60. typedef struct PerThreadContext {
  61. struct FrameThreadContext *parent;
  62. pthread_t thread;
  63. int thread_init;
  64. pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
  65. pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
  66. pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
  67. pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
  68. pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
  69. AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
  70. AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
  71. AVFrame *frame; ///< Output frame (for decoding) or input (for encoding).
  72. int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
  73. int result; ///< The result of the last codec decode/encode() call.
  74. atomic_int state;
  75. /**
  76. * Array of frames passed to ff_thread_release_buffer().
  77. * Frames are released after all threads referencing them are finished.
  78. */
  79. AVFrame *released_buffers;
  80. int num_released_buffers;
  81. int released_buffers_allocated;
  82. AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
  83. int requested_flags; ///< flags passed to get_buffer() for requested_frame
  84. int die; ///< Set when the thread should exit.
  85. } PerThreadContext;
  86. /**
  87. * Context stored in the client AVCodecInternal thread_ctx.
  88. */
  89. typedef struct FrameThreadContext {
  90. PerThreadContext *threads; ///< The contexts for each thread.
  91. PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
  92. pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
  93. int next_decoding; ///< The next context to submit a packet to.
  94. int next_finished; ///< The next context to return output from.
  95. int delaying; /**<
  96. * Set for the first N packets, where N is the number of threads.
  97. * While it is set, ff_thread_en/decode_frame won't return any results.
  98. */
  99. } FrameThreadContext;
  100. /**
  101. * Codec worker thread.
  102. *
  103. * Automatically calls ff_thread_finish_setup() if the codec does
  104. * not provide an update_thread_context method, or if the codec returns
  105. * before calling it.
  106. */
  107. static attribute_align_arg void *frame_worker_thread(void *arg)
  108. {
  109. PerThreadContext *p = arg;
  110. AVCodecContext *avctx = p->avctx;
  111. const AVCodec *codec = avctx->codec;
  112. while (1) {
  113. if (atomic_load(&p->state) == STATE_INPUT_READY) {
  114. pthread_mutex_lock(&p->mutex);
  115. while (atomic_load(&p->state) == STATE_INPUT_READY) {
  116. if (p->die) {
  117. pthread_mutex_unlock(&p->mutex);
  118. goto die;
  119. }
  120. pthread_cond_wait(&p->input_cond, &p->mutex);
  121. }
  122. pthread_mutex_unlock(&p->mutex);
  123. }
  124. if (!codec->update_thread_context && avctx->thread_safe_callbacks)
  125. ff_thread_finish_setup(avctx);
  126. pthread_mutex_lock(&p->mutex);
  127. av_frame_unref(p->frame);
  128. p->got_frame = 0;
  129. p->result = codec->decode(avctx, p->frame, &p->got_frame, &p->avpkt);
  130. if ((p->result < 0 || !p->got_frame) && p->frame->buf[0]) {
  131. if (avctx->internal->allocate_progress)
  132. av_log(avctx, AV_LOG_ERROR, "A frame threaded decoder did not "
  133. "free the frame on failure. This is a bug, please report it.\n");
  134. av_frame_unref(p->frame);
  135. }
  136. if (atomic_load(&p->state) == STATE_SETTING_UP)
  137. ff_thread_finish_setup(avctx);
  138. atomic_store(&p->state, STATE_INPUT_READY);
  139. pthread_mutex_lock(&p->progress_mutex);
  140. pthread_cond_signal(&p->output_cond);
  141. pthread_mutex_unlock(&p->progress_mutex);
  142. pthread_mutex_unlock(&p->mutex);
  143. }
  144. die:
  145. return NULL;
  146. }
  147. /**
  148. * Update the next thread's AVCodecContext with values from the reference thread's context.
  149. *
  150. * @param dst The destination context.
  151. * @param src The source context.
  152. * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
  153. */
  154. static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
  155. {
  156. int err = 0;
  157. if (dst != src) {
  158. dst->time_base = src->time_base;
  159. dst->framerate = src->framerate;
  160. dst->width = src->width;
  161. dst->height = src->height;
  162. dst->pix_fmt = src->pix_fmt;
  163. dst->coded_width = src->coded_width;
  164. dst->coded_height = src->coded_height;
  165. dst->has_b_frames = src->has_b_frames;
  166. dst->idct_algo = src->idct_algo;
  167. dst->bits_per_coded_sample = src->bits_per_coded_sample;
  168. dst->sample_aspect_ratio = src->sample_aspect_ratio;
  169. #if FF_API_AFD
  170. FF_DISABLE_DEPRECATION_WARNINGS
  171. dst->dtg_active_format = src->dtg_active_format;
  172. FF_ENABLE_DEPRECATION_WARNINGS
  173. #endif /* FF_API_AFD */
  174. dst->profile = src->profile;
  175. dst->level = src->level;
  176. dst->bits_per_raw_sample = src->bits_per_raw_sample;
  177. dst->ticks_per_frame = src->ticks_per_frame;
  178. dst->color_primaries = src->color_primaries;
  179. dst->color_trc = src->color_trc;
  180. dst->colorspace = src->colorspace;
  181. dst->color_range = src->color_range;
  182. dst->chroma_sample_location = src->chroma_sample_location;
  183. dst->hwaccel = src->hwaccel;
  184. dst->hwaccel_context = src->hwaccel_context;
  185. dst->internal->hwaccel_priv_data = src->internal->hwaccel_priv_data;
  186. }
  187. if (for_user) {
  188. #if FF_API_CODED_FRAME
  189. FF_DISABLE_DEPRECATION_WARNINGS
  190. dst->coded_frame = src->coded_frame;
  191. FF_ENABLE_DEPRECATION_WARNINGS
  192. #endif
  193. } else {
  194. if (dst->codec->update_thread_context)
  195. err = dst->codec->update_thread_context(dst, src);
  196. }
  197. return err;
  198. }
  199. /**
  200. * Update the next thread's AVCodecContext with values set by the user.
  201. *
  202. * @param dst The destination context.
  203. * @param src The source context.
  204. * @return 0 on success, negative error code on failure
  205. */
  206. static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
  207. {
  208. #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
  209. dst->flags = src->flags;
  210. dst->draw_horiz_band= src->draw_horiz_band;
  211. dst->get_buffer2 = src->get_buffer2;
  212. dst->opaque = src->opaque;
  213. dst->debug = src->debug;
  214. dst->slice_flags = src->slice_flags;
  215. dst->flags2 = src->flags2;
  216. copy_fields(skip_loop_filter, subtitle_header);
  217. dst->frame_number = src->frame_number;
  218. dst->reordered_opaque = src->reordered_opaque;
  219. if (src->slice_count && src->slice_offset) {
  220. if (dst->slice_count < src->slice_count) {
  221. int *tmp = av_realloc(dst->slice_offset, src->slice_count *
  222. sizeof(*dst->slice_offset));
  223. if (!tmp) {
  224. av_free(dst->slice_offset);
  225. return AVERROR(ENOMEM);
  226. }
  227. dst->slice_offset = tmp;
  228. }
  229. memcpy(dst->slice_offset, src->slice_offset,
  230. src->slice_count * sizeof(*dst->slice_offset));
  231. }
  232. dst->slice_count = src->slice_count;
  233. return 0;
  234. #undef copy_fields
  235. }
  236. /// Releases the buffers that this decoding thread was the last user of.
  237. static void release_delayed_buffers(PerThreadContext *p)
  238. {
  239. FrameThreadContext *fctx = p->parent;
  240. while (p->num_released_buffers > 0) {
  241. AVFrame *f;
  242. pthread_mutex_lock(&fctx->buffer_mutex);
  243. // fix extended data in case the caller screwed it up
  244. av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO);
  245. f = &p->released_buffers[--p->num_released_buffers];
  246. f->extended_data = f->data;
  247. av_frame_unref(f);
  248. pthread_mutex_unlock(&fctx->buffer_mutex);
  249. }
  250. }
  251. static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
  252. {
  253. FrameThreadContext *fctx = p->parent;
  254. PerThreadContext *prev_thread = fctx->prev_thread;
  255. const AVCodec *codec = p->avctx->codec;
  256. if (!avpkt->size && !(codec->capabilities & AV_CODEC_CAP_DELAY))
  257. return 0;
  258. pthread_mutex_lock(&p->mutex);
  259. release_delayed_buffers(p);
  260. if (prev_thread) {
  261. int err;
  262. if (atomic_load(&prev_thread->state) == STATE_SETTING_UP) {
  263. pthread_mutex_lock(&prev_thread->progress_mutex);
  264. while (atomic_load(&prev_thread->state) == STATE_SETTING_UP)
  265. pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
  266. pthread_mutex_unlock(&prev_thread->progress_mutex);
  267. }
  268. err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
  269. if (err) {
  270. pthread_mutex_unlock(&p->mutex);
  271. return err;
  272. }
  273. }
  274. av_packet_unref(&p->avpkt);
  275. av_packet_ref(&p->avpkt, avpkt);
  276. atomic_store(&p->state, STATE_SETTING_UP);
  277. pthread_cond_signal(&p->input_cond);
  278. pthread_mutex_unlock(&p->mutex);
  279. /*
  280. * If the client doesn't have a thread-safe get_buffer(),
  281. * then decoding threads call back to the main thread,
  282. * and it calls back to the client here.
  283. */
  284. if (!p->avctx->thread_safe_callbacks &&
  285. p->avctx->get_buffer2 != avcodec_default_get_buffer2) {
  286. while (atomic_load(&p->state) != STATE_SETUP_FINISHED &&
  287. atomic_load(&p->state) != STATE_INPUT_READY) {
  288. pthread_mutex_lock(&p->progress_mutex);
  289. while (atomic_load(&p->state) == STATE_SETTING_UP)
  290. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  291. if (atomic_load_explicit(&p->state, memory_order_acquire) == STATE_GET_BUFFER) {
  292. p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
  293. atomic_store(&p->state, STATE_SETTING_UP);
  294. pthread_cond_signal(&p->progress_cond);
  295. }
  296. pthread_mutex_unlock(&p->progress_mutex);
  297. }
  298. }
  299. fctx->prev_thread = p;
  300. fctx->next_decoding++;
  301. return 0;
  302. }
  303. int ff_thread_decode_frame(AVCodecContext *avctx,
  304. AVFrame *picture, int *got_picture_ptr,
  305. AVPacket *avpkt)
  306. {
  307. FrameThreadContext *fctx = avctx->internal->thread_ctx;
  308. int finished = fctx->next_finished;
  309. PerThreadContext *p;
  310. int err;
  311. /*
  312. * Submit a packet to the next decoding thread.
  313. */
  314. p = &fctx->threads[fctx->next_decoding];
  315. err = update_context_from_user(p->avctx, avctx);
  316. if (err) return err;
  317. err = submit_packet(p, avpkt);
  318. if (err) return err;
  319. /*
  320. * If we're still receiving the initial packets, don't return a frame.
  321. */
  322. if (fctx->delaying) {
  323. if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
  324. *got_picture_ptr=0;
  325. if (avpkt->size)
  326. return avpkt->size;
  327. }
  328. /*
  329. * Return the next available frame from the oldest thread.
  330. * If we're at the end of the stream, then we have to skip threads that
  331. * didn't output a frame, because we don't want to accidentally signal
  332. * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
  333. */
  334. do {
  335. p = &fctx->threads[finished++];
  336. if (atomic_load(&p->state) != STATE_INPUT_READY) {
  337. pthread_mutex_lock(&p->progress_mutex);
  338. while (atomic_load_explicit(&p->state, memory_order_relaxed) != STATE_INPUT_READY)
  339. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  340. pthread_mutex_unlock(&p->progress_mutex);
  341. }
  342. av_frame_move_ref(picture, p->frame);
  343. *got_picture_ptr = p->got_frame;
  344. picture->pkt_dts = p->avpkt.dts;
  345. /*
  346. * A later call with avkpt->size == 0 may loop over all threads,
  347. * including this one, searching for a frame to return before being
  348. * stopped by the "finished != fctx->next_finished" condition.
  349. * Make sure we don't mistakenly return the same frame again.
  350. */
  351. p->got_frame = 0;
  352. if (finished >= avctx->thread_count) finished = 0;
  353. } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
  354. update_context_from_thread(avctx, p->avctx, 1);
  355. if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
  356. fctx->next_finished = finished;
  357. /* return the size of the consumed packet if no error occurred */
  358. return (p->result >= 0) ? avpkt->size : p->result;
  359. }
  360. void ff_thread_report_progress(ThreadFrame *f, int n, int field)
  361. {
  362. PerThreadContext *p;
  363. atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
  364. if (!progress ||
  365. atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
  366. return;
  367. p = f->owner->internal->thread_ctx;
  368. if (f->owner->debug&FF_DEBUG_THREADS)
  369. av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
  370. pthread_mutex_lock(&p->progress_mutex);
  371. atomic_store(&progress[field], n);
  372. pthread_cond_broadcast(&p->progress_cond);
  373. pthread_mutex_unlock(&p->progress_mutex);
  374. }
  375. void ff_thread_await_progress(ThreadFrame *f, int n, int field)
  376. {
  377. PerThreadContext *p;
  378. atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
  379. if (!progress ||
  380. atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
  381. return;
  382. p = f->owner->internal->thread_ctx;
  383. if (f->owner->debug&FF_DEBUG_THREADS)
  384. av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
  385. pthread_mutex_lock(&p->progress_mutex);
  386. while (atomic_load_explicit(&progress[field], memory_order_relaxed) < n)
  387. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  388. pthread_mutex_unlock(&p->progress_mutex);
  389. }
  390. void ff_thread_finish_setup(AVCodecContext *avctx) {
  391. PerThreadContext *p = avctx->internal->thread_ctx;
  392. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
  393. pthread_mutex_lock(&p->progress_mutex);
  394. atomic_store(&p->state, STATE_SETUP_FINISHED);
  395. pthread_cond_broadcast(&p->progress_cond);
  396. pthread_mutex_unlock(&p->progress_mutex);
  397. }
  398. /// Waits for all threads to finish.
  399. static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
  400. {
  401. int i;
  402. for (i = 0; i < thread_count; i++) {
  403. PerThreadContext *p = &fctx->threads[i];
  404. if (atomic_load(&p->state) != STATE_INPUT_READY) {
  405. pthread_mutex_lock(&p->progress_mutex);
  406. while (atomic_load(&p->state) != STATE_INPUT_READY)
  407. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  408. pthread_mutex_unlock(&p->progress_mutex);
  409. }
  410. }
  411. }
  412. void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
  413. {
  414. FrameThreadContext *fctx = avctx->internal->thread_ctx;
  415. const AVCodec *codec = avctx->codec;
  416. int i;
  417. park_frame_worker_threads(fctx, thread_count);
  418. if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
  419. update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
  420. for (i = 0; i < thread_count; i++) {
  421. PerThreadContext *p = &fctx->threads[i];
  422. pthread_mutex_lock(&p->mutex);
  423. p->die = 1;
  424. pthread_cond_signal(&p->input_cond);
  425. pthread_mutex_unlock(&p->mutex);
  426. if (p->thread_init)
  427. pthread_join(p->thread, NULL);
  428. if (codec->close)
  429. codec->close(p->avctx);
  430. avctx->codec = NULL;
  431. release_delayed_buffers(p);
  432. av_frame_free(&p->frame);
  433. }
  434. for (i = 0; i < thread_count; i++) {
  435. PerThreadContext *p = &fctx->threads[i];
  436. pthread_mutex_destroy(&p->mutex);
  437. pthread_mutex_destroy(&p->progress_mutex);
  438. pthread_cond_destroy(&p->input_cond);
  439. pthread_cond_destroy(&p->progress_cond);
  440. pthread_cond_destroy(&p->output_cond);
  441. av_packet_unref(&p->avpkt);
  442. av_freep(&p->released_buffers);
  443. if (i) {
  444. av_freep(&p->avctx->priv_data);
  445. av_freep(&p->avctx->slice_offset);
  446. }
  447. av_freep(&p->avctx->internal);
  448. av_freep(&p->avctx);
  449. }
  450. av_freep(&fctx->threads);
  451. pthread_mutex_destroy(&fctx->buffer_mutex);
  452. av_freep(&avctx->internal->thread_ctx);
  453. }
  454. int ff_frame_thread_init(AVCodecContext *avctx)
  455. {
  456. int thread_count = avctx->thread_count;
  457. const AVCodec *codec = avctx->codec;
  458. AVCodecContext *src = avctx;
  459. FrameThreadContext *fctx;
  460. int i, err = 0;
  461. #if HAVE_W32THREADS
  462. w32thread_init();
  463. #endif
  464. if (!thread_count) {
  465. int nb_cpus = av_cpu_count();
  466. av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
  467. // use number of cores + 1 as thread count if there is more than one
  468. if (nb_cpus > 1)
  469. thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
  470. else
  471. thread_count = avctx->thread_count = 1;
  472. }
  473. if (thread_count <= 1) {
  474. avctx->active_thread_type = 0;
  475. return 0;
  476. }
  477. avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
  478. if (!fctx)
  479. return AVERROR(ENOMEM);
  480. fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
  481. if (!fctx->threads) {
  482. av_freep(&avctx->internal->thread_ctx);
  483. return AVERROR(ENOMEM);
  484. }
  485. pthread_mutex_init(&fctx->buffer_mutex, NULL);
  486. fctx->delaying = 1;
  487. for (i = 0; i < thread_count; i++) {
  488. AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
  489. PerThreadContext *p = &fctx->threads[i];
  490. pthread_mutex_init(&p->mutex, NULL);
  491. pthread_mutex_init(&p->progress_mutex, NULL);
  492. pthread_cond_init(&p->input_cond, NULL);
  493. pthread_cond_init(&p->progress_cond, NULL);
  494. pthread_cond_init(&p->output_cond, NULL);
  495. p->frame = av_frame_alloc();
  496. if (!p->frame) {
  497. av_freep(&copy);
  498. err = AVERROR(ENOMEM);
  499. goto error;
  500. }
  501. p->parent = fctx;
  502. p->avctx = copy;
  503. if (!copy) {
  504. err = AVERROR(ENOMEM);
  505. goto error;
  506. }
  507. *copy = *src;
  508. copy->internal = av_malloc(sizeof(AVCodecInternal));
  509. if (!copy->internal) {
  510. err = AVERROR(ENOMEM);
  511. goto error;
  512. }
  513. *copy->internal = *src->internal;
  514. copy->internal->thread_ctx = p;
  515. copy->internal->pkt = &p->avpkt;
  516. if (!i) {
  517. src = copy;
  518. if (codec->init)
  519. err = codec->init(copy);
  520. update_context_from_thread(avctx, copy, 1);
  521. } else {
  522. copy->priv_data = av_malloc(codec->priv_data_size);
  523. if (!copy->priv_data) {
  524. err = AVERROR(ENOMEM);
  525. goto error;
  526. }
  527. memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
  528. copy->internal->is_copy = 1;
  529. if (codec->init_thread_copy)
  530. err = codec->init_thread_copy(copy);
  531. }
  532. if (err) goto error;
  533. if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
  534. p->thread_init = 1;
  535. }
  536. return 0;
  537. error:
  538. ff_frame_thread_free(avctx, i+1);
  539. return err;
  540. }
  541. void ff_thread_flush(AVCodecContext *avctx)
  542. {
  543. int i;
  544. FrameThreadContext *fctx = avctx->internal->thread_ctx;
  545. if (!fctx) return;
  546. park_frame_worker_threads(fctx, avctx->thread_count);
  547. if (fctx->prev_thread) {
  548. if (fctx->prev_thread != &fctx->threads[0])
  549. update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
  550. }
  551. fctx->next_decoding = fctx->next_finished = 0;
  552. fctx->delaying = 1;
  553. fctx->prev_thread = NULL;
  554. for (i = 0; i < avctx->thread_count; i++) {
  555. PerThreadContext *p = &fctx->threads[i];
  556. // Make sure decode flush calls with size=0 won't return old frames
  557. p->got_frame = 0;
  558. av_frame_unref(p->frame);
  559. release_delayed_buffers(p);
  560. if (avctx->codec->flush)
  561. avctx->codec->flush(p->avctx);
  562. }
  563. }
  564. int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
  565. {
  566. PerThreadContext *p = avctx->internal->thread_ctx;
  567. int err;
  568. f->owner = avctx;
  569. if (!(avctx->active_thread_type & FF_THREAD_FRAME))
  570. return ff_get_buffer(avctx, f->f, flags);
  571. if (atomic_load(&p->state) != STATE_SETTING_UP &&
  572. (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
  573. av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
  574. return -1;
  575. }
  576. if (avctx->internal->allocate_progress) {
  577. atomic_int *progress;
  578. f->progress = av_buffer_alloc(2 * sizeof(*progress));
  579. if (!f->progress) {
  580. return AVERROR(ENOMEM);
  581. }
  582. progress = (atomic_int*)f->progress->data;
  583. atomic_store(&progress[0], -1);
  584. atomic_store(&progress[1], -1);
  585. }
  586. pthread_mutex_lock(&p->parent->buffer_mutex);
  587. if (avctx->thread_safe_callbacks ||
  588. avctx->get_buffer2 == avcodec_default_get_buffer2) {
  589. err = ff_get_buffer(avctx, f->f, flags);
  590. } else {
  591. p->requested_frame = f->f;
  592. p->requested_flags = flags;
  593. atomic_store_explicit(&p->state, STATE_GET_BUFFER, memory_order_release);
  594. pthread_mutex_lock(&p->progress_mutex);
  595. pthread_cond_signal(&p->progress_cond);
  596. while (atomic_load(&p->state) != STATE_SETTING_UP)
  597. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  598. err = p->result;
  599. pthread_mutex_unlock(&p->progress_mutex);
  600. }
  601. if (!avctx->thread_safe_callbacks && !avctx->codec->update_thread_context)
  602. ff_thread_finish_setup(avctx);
  603. if (err)
  604. av_buffer_unref(&f->progress);
  605. pthread_mutex_unlock(&p->parent->buffer_mutex);
  606. return err;
  607. }
  608. void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
  609. {
  610. PerThreadContext *p = avctx->internal->thread_ctx;
  611. FrameThreadContext *fctx;
  612. AVFrame *dst, *tmp;
  613. int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
  614. avctx->thread_safe_callbacks ||
  615. avctx->get_buffer2 == avcodec_default_get_buffer2;
  616. if (!f->f || !f->f->buf[0])
  617. return;
  618. if (avctx->debug & FF_DEBUG_BUFFERS)
  619. av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
  620. av_buffer_unref(&f->progress);
  621. f->owner = NULL;
  622. if (can_direct_free) {
  623. av_frame_unref(f->f);
  624. return;
  625. }
  626. fctx = p->parent;
  627. pthread_mutex_lock(&fctx->buffer_mutex);
  628. if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
  629. goto fail;
  630. tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
  631. (p->num_released_buffers + 1) *
  632. sizeof(*p->released_buffers));
  633. if (!tmp)
  634. goto fail;
  635. p->released_buffers = tmp;
  636. dst = &p->released_buffers[p->num_released_buffers];
  637. av_frame_move_ref(dst, f->f);
  638. p->num_released_buffers++;
  639. fail:
  640. pthread_mutex_unlock(&fctx->buffer_mutex);
  641. }