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.

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