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.

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