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.

1172 lines
37KB

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