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.

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