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.

900 lines
28KB

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