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.

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