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.

1020 lines
32KB

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