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.

825 lines
26KB

  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. if (!!dst->hw_frames_ctx != !!src->hw_frames_ctx ||
  187. (dst->hw_frames_ctx && dst->hw_frames_ctx->data != src->hw_frames_ctx->data)) {
  188. av_buffer_unref(&dst->hw_frames_ctx);
  189. if (src->hw_frames_ctx) {
  190. dst->hw_frames_ctx = av_buffer_ref(src->hw_frames_ctx);
  191. if (!dst->hw_frames_ctx)
  192. return AVERROR(ENOMEM);
  193. }
  194. }
  195. }
  196. if (for_user) {
  197. #if FF_API_CODED_FRAME
  198. FF_DISABLE_DEPRECATION_WARNINGS
  199. dst->coded_frame = src->coded_frame;
  200. FF_ENABLE_DEPRECATION_WARNINGS
  201. #endif
  202. } else {
  203. if (dst->codec->update_thread_context)
  204. err = dst->codec->update_thread_context(dst, src);
  205. }
  206. return err;
  207. }
  208. /**
  209. * Update the next thread's AVCodecContext with values set by the user.
  210. *
  211. * @param dst The destination context.
  212. * @param src The source context.
  213. * @return 0 on success, negative error code on failure
  214. */
  215. static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
  216. {
  217. #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
  218. dst->flags = src->flags;
  219. dst->draw_horiz_band= src->draw_horiz_band;
  220. dst->get_buffer2 = src->get_buffer2;
  221. dst->opaque = src->opaque;
  222. dst->debug = src->debug;
  223. dst->slice_flags = src->slice_flags;
  224. dst->flags2 = src->flags2;
  225. copy_fields(skip_loop_filter, subtitle_header);
  226. dst->frame_number = src->frame_number;
  227. dst->reordered_opaque = src->reordered_opaque;
  228. if (src->slice_count && src->slice_offset) {
  229. if (dst->slice_count < src->slice_count) {
  230. int *tmp = av_realloc(dst->slice_offset, src->slice_count *
  231. sizeof(*dst->slice_offset));
  232. if (!tmp) {
  233. av_free(dst->slice_offset);
  234. return AVERROR(ENOMEM);
  235. }
  236. dst->slice_offset = tmp;
  237. }
  238. memcpy(dst->slice_offset, src->slice_offset,
  239. src->slice_count * sizeof(*dst->slice_offset));
  240. }
  241. dst->slice_count = src->slice_count;
  242. return 0;
  243. #undef copy_fields
  244. }
  245. /// Releases the buffers that this decoding thread was the last user of.
  246. static void release_delayed_buffers(PerThreadContext *p)
  247. {
  248. FrameThreadContext *fctx = p->parent;
  249. while (p->num_released_buffers > 0) {
  250. AVFrame *f;
  251. pthread_mutex_lock(&fctx->buffer_mutex);
  252. // fix extended data in case the caller screwed it up
  253. av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO);
  254. f = &p->released_buffers[--p->num_released_buffers];
  255. f->extended_data = f->data;
  256. av_frame_unref(f);
  257. pthread_mutex_unlock(&fctx->buffer_mutex);
  258. }
  259. }
  260. static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
  261. {
  262. FrameThreadContext *fctx = p->parent;
  263. PerThreadContext *prev_thread = fctx->prev_thread;
  264. const AVCodec *codec = p->avctx->codec;
  265. if (!avpkt->size && !(codec->capabilities & AV_CODEC_CAP_DELAY))
  266. return 0;
  267. pthread_mutex_lock(&p->mutex);
  268. release_delayed_buffers(p);
  269. if (prev_thread) {
  270. int err;
  271. if (atomic_load(&prev_thread->state) == STATE_SETTING_UP) {
  272. pthread_mutex_lock(&prev_thread->progress_mutex);
  273. while (atomic_load(&prev_thread->state) == STATE_SETTING_UP)
  274. pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
  275. pthread_mutex_unlock(&prev_thread->progress_mutex);
  276. }
  277. err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
  278. if (err) {
  279. pthread_mutex_unlock(&p->mutex);
  280. return err;
  281. }
  282. }
  283. av_packet_unref(&p->avpkt);
  284. av_packet_ref(&p->avpkt, avpkt);
  285. atomic_store(&p->state, STATE_SETTING_UP);
  286. pthread_cond_signal(&p->input_cond);
  287. pthread_mutex_unlock(&p->mutex);
  288. /*
  289. * If the client doesn't have a thread-safe get_buffer(),
  290. * then decoding threads call back to the main thread,
  291. * and it calls back to the client here.
  292. */
  293. if (!p->avctx->thread_safe_callbacks &&
  294. p->avctx->get_buffer2 != avcodec_default_get_buffer2) {
  295. while (atomic_load(&p->state) != STATE_SETUP_FINISHED &&
  296. atomic_load(&p->state) != STATE_INPUT_READY) {
  297. pthread_mutex_lock(&p->progress_mutex);
  298. while (atomic_load(&p->state) == STATE_SETTING_UP)
  299. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  300. if (atomic_load_explicit(&p->state, memory_order_acquire) == STATE_GET_BUFFER) {
  301. p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
  302. atomic_store(&p->state, STATE_SETTING_UP);
  303. pthread_cond_signal(&p->progress_cond);
  304. }
  305. pthread_mutex_unlock(&p->progress_mutex);
  306. }
  307. }
  308. fctx->prev_thread = p;
  309. fctx->next_decoding++;
  310. return 0;
  311. }
  312. int ff_thread_decode_frame(AVCodecContext *avctx,
  313. AVFrame *picture, int *got_picture_ptr,
  314. AVPacket *avpkt)
  315. {
  316. FrameThreadContext *fctx = avctx->internal->thread_ctx;
  317. int finished = fctx->next_finished;
  318. PerThreadContext *p;
  319. int err;
  320. /*
  321. * Submit a packet to the next decoding thread.
  322. */
  323. p = &fctx->threads[fctx->next_decoding];
  324. err = update_context_from_user(p->avctx, avctx);
  325. if (err) return err;
  326. err = submit_packet(p, avpkt);
  327. if (err) return err;
  328. /*
  329. * If we're still receiving the initial packets, don't return a frame.
  330. */
  331. if (fctx->delaying) {
  332. if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
  333. *got_picture_ptr=0;
  334. if (avpkt->size)
  335. return avpkt->size;
  336. }
  337. /*
  338. * Return the next available frame from the oldest thread.
  339. * If we're at the end of the stream, then we have to skip threads that
  340. * didn't output a frame, because we don't want to accidentally signal
  341. * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
  342. */
  343. do {
  344. p = &fctx->threads[finished++];
  345. if (atomic_load(&p->state) != STATE_INPUT_READY) {
  346. pthread_mutex_lock(&p->progress_mutex);
  347. while (atomic_load_explicit(&p->state, memory_order_relaxed) != STATE_INPUT_READY)
  348. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  349. pthread_mutex_unlock(&p->progress_mutex);
  350. }
  351. av_frame_move_ref(picture, p->frame);
  352. *got_picture_ptr = p->got_frame;
  353. picture->pkt_dts = p->avpkt.dts;
  354. /*
  355. * A later call with avkpt->size == 0 may loop over all threads,
  356. * including this one, searching for a frame to return before being
  357. * stopped by the "finished != fctx->next_finished" condition.
  358. * Make sure we don't mistakenly return the same frame again.
  359. */
  360. p->got_frame = 0;
  361. if (finished >= avctx->thread_count) finished = 0;
  362. } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
  363. update_context_from_thread(avctx, p->avctx, 1);
  364. if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
  365. fctx->next_finished = finished;
  366. /* return the size of the consumed packet if no error occurred */
  367. return (p->result >= 0) ? avpkt->size : p->result;
  368. }
  369. void ff_thread_report_progress(ThreadFrame *f, int n, int field)
  370. {
  371. PerThreadContext *p;
  372. atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
  373. if (!progress ||
  374. atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
  375. return;
  376. p = f->owner->internal->thread_ctx;
  377. if (f->owner->debug&FF_DEBUG_THREADS)
  378. av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
  379. pthread_mutex_lock(&p->progress_mutex);
  380. atomic_store(&progress[field], n);
  381. pthread_cond_broadcast(&p->progress_cond);
  382. pthread_mutex_unlock(&p->progress_mutex);
  383. }
  384. void ff_thread_await_progress(ThreadFrame *f, int n, int field)
  385. {
  386. PerThreadContext *p;
  387. atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
  388. if (!progress ||
  389. atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
  390. return;
  391. p = f->owner->internal->thread_ctx;
  392. if (f->owner->debug&FF_DEBUG_THREADS)
  393. av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
  394. pthread_mutex_lock(&p->progress_mutex);
  395. while (atomic_load_explicit(&progress[field], memory_order_relaxed) < n)
  396. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  397. pthread_mutex_unlock(&p->progress_mutex);
  398. }
  399. void ff_thread_finish_setup(AVCodecContext *avctx) {
  400. PerThreadContext *p = avctx->internal->thread_ctx;
  401. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
  402. pthread_mutex_lock(&p->progress_mutex);
  403. atomic_store(&p->state, STATE_SETUP_FINISHED);
  404. pthread_cond_broadcast(&p->progress_cond);
  405. pthread_mutex_unlock(&p->progress_mutex);
  406. }
  407. /// Waits for all threads to finish.
  408. static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
  409. {
  410. int i;
  411. for (i = 0; i < thread_count; i++) {
  412. PerThreadContext *p = &fctx->threads[i];
  413. if (atomic_load(&p->state) != STATE_INPUT_READY) {
  414. pthread_mutex_lock(&p->progress_mutex);
  415. while (atomic_load(&p->state) != STATE_INPUT_READY)
  416. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  417. pthread_mutex_unlock(&p->progress_mutex);
  418. }
  419. }
  420. }
  421. void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
  422. {
  423. FrameThreadContext *fctx = avctx->internal->thread_ctx;
  424. const AVCodec *codec = avctx->codec;
  425. int i;
  426. park_frame_worker_threads(fctx, thread_count);
  427. if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
  428. update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
  429. for (i = 0; i < thread_count; i++) {
  430. PerThreadContext *p = &fctx->threads[i];
  431. pthread_mutex_lock(&p->mutex);
  432. p->die = 1;
  433. pthread_cond_signal(&p->input_cond);
  434. pthread_mutex_unlock(&p->mutex);
  435. if (p->thread_init)
  436. pthread_join(p->thread, NULL);
  437. if (codec->close)
  438. codec->close(p->avctx);
  439. avctx->codec = NULL;
  440. release_delayed_buffers(p);
  441. av_frame_free(&p->frame);
  442. }
  443. for (i = 0; i < thread_count; i++) {
  444. PerThreadContext *p = &fctx->threads[i];
  445. pthread_mutex_destroy(&p->mutex);
  446. pthread_mutex_destroy(&p->progress_mutex);
  447. pthread_cond_destroy(&p->input_cond);
  448. pthread_cond_destroy(&p->progress_cond);
  449. pthread_cond_destroy(&p->output_cond);
  450. av_packet_unref(&p->avpkt);
  451. av_freep(&p->released_buffers);
  452. if (i) {
  453. av_freep(&p->avctx->priv_data);
  454. av_freep(&p->avctx->slice_offset);
  455. }
  456. av_buffer_unref(&p->avctx->hw_frames_ctx);
  457. av_freep(&p->avctx->internal);
  458. av_freep(&p->avctx);
  459. }
  460. av_freep(&fctx->threads);
  461. pthread_mutex_destroy(&fctx->buffer_mutex);
  462. av_freep(&avctx->internal->thread_ctx);
  463. }
  464. int ff_frame_thread_init(AVCodecContext *avctx)
  465. {
  466. int thread_count = avctx->thread_count;
  467. const AVCodec *codec = avctx->codec;
  468. AVCodecContext *src = avctx;
  469. FrameThreadContext *fctx;
  470. int i, err = 0;
  471. #if HAVE_W32THREADS
  472. w32thread_init();
  473. #endif
  474. if (!thread_count) {
  475. int nb_cpus = av_cpu_count();
  476. av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
  477. // use number of cores + 1 as thread count if there is more than one
  478. if (nb_cpus > 1)
  479. thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
  480. else
  481. thread_count = avctx->thread_count = 1;
  482. }
  483. if (thread_count <= 1) {
  484. avctx->active_thread_type = 0;
  485. return 0;
  486. }
  487. avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
  488. if (!fctx)
  489. return AVERROR(ENOMEM);
  490. fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
  491. if (!fctx->threads) {
  492. av_freep(&avctx->internal->thread_ctx);
  493. return AVERROR(ENOMEM);
  494. }
  495. pthread_mutex_init(&fctx->buffer_mutex, NULL);
  496. fctx->delaying = 1;
  497. for (i = 0; i < thread_count; i++) {
  498. AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
  499. PerThreadContext *p = &fctx->threads[i];
  500. pthread_mutex_init(&p->mutex, NULL);
  501. pthread_mutex_init(&p->progress_mutex, NULL);
  502. pthread_cond_init(&p->input_cond, NULL);
  503. pthread_cond_init(&p->progress_cond, NULL);
  504. pthread_cond_init(&p->output_cond, NULL);
  505. p->frame = av_frame_alloc();
  506. if (!p->frame) {
  507. av_freep(&copy);
  508. err = AVERROR(ENOMEM);
  509. goto error;
  510. }
  511. p->parent = fctx;
  512. p->avctx = copy;
  513. if (!copy) {
  514. err = AVERROR(ENOMEM);
  515. goto error;
  516. }
  517. *copy = *src;
  518. copy->internal = av_malloc(sizeof(AVCodecInternal));
  519. if (!copy->internal) {
  520. err = AVERROR(ENOMEM);
  521. goto error;
  522. }
  523. *copy->internal = *src->internal;
  524. copy->internal->thread_ctx = p;
  525. copy->internal->pkt = &p->avpkt;
  526. if (!i) {
  527. src = copy;
  528. if (codec->init)
  529. err = codec->init(copy);
  530. update_context_from_thread(avctx, copy, 1);
  531. } else {
  532. copy->priv_data = av_malloc(codec->priv_data_size);
  533. if (!copy->priv_data) {
  534. err = AVERROR(ENOMEM);
  535. goto error;
  536. }
  537. memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
  538. copy->internal->is_copy = 1;
  539. if (codec->init_thread_copy)
  540. err = codec->init_thread_copy(copy);
  541. }
  542. if (err) goto error;
  543. if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
  544. p->thread_init = 1;
  545. }
  546. return 0;
  547. error:
  548. ff_frame_thread_free(avctx, i+1);
  549. return err;
  550. }
  551. void ff_thread_flush(AVCodecContext *avctx)
  552. {
  553. int i;
  554. FrameThreadContext *fctx = avctx->internal->thread_ctx;
  555. if (!fctx) return;
  556. park_frame_worker_threads(fctx, avctx->thread_count);
  557. if (fctx->prev_thread) {
  558. if (fctx->prev_thread != &fctx->threads[0])
  559. update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
  560. }
  561. fctx->next_decoding = fctx->next_finished = 0;
  562. fctx->delaying = 1;
  563. fctx->prev_thread = NULL;
  564. for (i = 0; i < avctx->thread_count; i++) {
  565. PerThreadContext *p = &fctx->threads[i];
  566. // Make sure decode flush calls with size=0 won't return old frames
  567. p->got_frame = 0;
  568. av_frame_unref(p->frame);
  569. release_delayed_buffers(p);
  570. if (avctx->codec->flush)
  571. avctx->codec->flush(p->avctx);
  572. }
  573. }
  574. int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
  575. {
  576. PerThreadContext *p = avctx->internal->thread_ctx;
  577. int err;
  578. f->owner = avctx;
  579. if (!(avctx->active_thread_type & FF_THREAD_FRAME))
  580. return ff_get_buffer(avctx, f->f, flags);
  581. if (atomic_load(&p->state) != STATE_SETTING_UP &&
  582. (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
  583. av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
  584. return -1;
  585. }
  586. if (avctx->internal->allocate_progress) {
  587. atomic_int *progress;
  588. f->progress = av_buffer_alloc(2 * sizeof(*progress));
  589. if (!f->progress) {
  590. return AVERROR(ENOMEM);
  591. }
  592. progress = (atomic_int*)f->progress->data;
  593. atomic_store(&progress[0], -1);
  594. atomic_store(&progress[1], -1);
  595. }
  596. pthread_mutex_lock(&p->parent->buffer_mutex);
  597. if (avctx->thread_safe_callbacks ||
  598. avctx->get_buffer2 == avcodec_default_get_buffer2) {
  599. err = ff_get_buffer(avctx, f->f, flags);
  600. } else {
  601. p->requested_frame = f->f;
  602. p->requested_flags = flags;
  603. atomic_store_explicit(&p->state, STATE_GET_BUFFER, memory_order_release);
  604. pthread_mutex_lock(&p->progress_mutex);
  605. pthread_cond_signal(&p->progress_cond);
  606. while (atomic_load(&p->state) != STATE_SETTING_UP)
  607. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  608. err = p->result;
  609. pthread_mutex_unlock(&p->progress_mutex);
  610. }
  611. if (!avctx->thread_safe_callbacks && !avctx->codec->update_thread_context)
  612. ff_thread_finish_setup(avctx);
  613. if (err)
  614. av_buffer_unref(&f->progress);
  615. pthread_mutex_unlock(&p->parent->buffer_mutex);
  616. return err;
  617. }
  618. void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
  619. {
  620. PerThreadContext *p = avctx->internal->thread_ctx;
  621. FrameThreadContext *fctx;
  622. AVFrame *dst, *tmp;
  623. int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
  624. avctx->thread_safe_callbacks ||
  625. avctx->get_buffer2 == avcodec_default_get_buffer2;
  626. if (!f->f || !f->f->buf[0])
  627. return;
  628. if (avctx->debug & FF_DEBUG_BUFFERS)
  629. av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
  630. av_buffer_unref(&f->progress);
  631. f->owner = NULL;
  632. if (can_direct_free) {
  633. av_frame_unref(f->f);
  634. return;
  635. }
  636. fctx = p->parent;
  637. pthread_mutex_lock(&fctx->buffer_mutex);
  638. if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
  639. goto fail;
  640. tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
  641. (p->num_released_buffers + 1) *
  642. sizeof(*p->released_buffers));
  643. if (!tmp)
  644. goto fail;
  645. p->released_buffers = tmp;
  646. dst = &p->released_buffers[p->num_released_buffers];
  647. av_frame_move_ref(dst, f->f);
  648. p->num_released_buffers++;
  649. fail:
  650. pthread_mutex_unlock(&fctx->buffer_mutex);
  651. }