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.

1174 lines
38KB

  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. if (dst->codec->update_thread_context_for_user)
  272. err = dst->codec->update_thread_context_for_user(dst, src);
  273. } else {
  274. if (dst->codec->update_thread_context)
  275. err = dst->codec->update_thread_context(dst, src);
  276. }
  277. return err;
  278. }
  279. /**
  280. * Update the next thread's AVCodecContext with values set by the user.
  281. *
  282. * @param dst The destination context.
  283. * @param src The source context.
  284. * @return 0 on success, negative error code on failure
  285. */
  286. static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
  287. {
  288. dst->flags = src->flags;
  289. dst->draw_horiz_band= src->draw_horiz_band;
  290. dst->get_buffer2 = src->get_buffer2;
  291. dst->opaque = src->opaque;
  292. dst->debug = src->debug;
  293. dst->slice_flags = src->slice_flags;
  294. dst->flags2 = src->flags2;
  295. dst->export_side_data = src->export_side_data;
  296. dst->skip_loop_filter = src->skip_loop_filter;
  297. dst->skip_idct = src->skip_idct;
  298. dst->skip_frame = src->skip_frame;
  299. dst->frame_number = src->frame_number;
  300. dst->reordered_opaque = src->reordered_opaque;
  301. #if FF_API_THREAD_SAFE_CALLBACKS
  302. FF_DISABLE_DEPRECATION_WARNINGS
  303. dst->thread_safe_callbacks = src->thread_safe_callbacks;
  304. FF_ENABLE_DEPRECATION_WARNINGS
  305. #endif
  306. if (src->slice_count && src->slice_offset) {
  307. if (dst->slice_count < src->slice_count) {
  308. int err = av_reallocp_array(&dst->slice_offset, src->slice_count,
  309. sizeof(*dst->slice_offset));
  310. if (err < 0)
  311. return err;
  312. }
  313. memcpy(dst->slice_offset, src->slice_offset,
  314. src->slice_count * sizeof(*dst->slice_offset));
  315. }
  316. dst->slice_count = src->slice_count;
  317. return 0;
  318. }
  319. #if FF_API_THREAD_SAFE_CALLBACKS
  320. /// Releases the buffers that this decoding thread was the last user of.
  321. static void release_delayed_buffers(PerThreadContext *p)
  322. {
  323. FrameThreadContext *fctx = p->parent;
  324. while (p->num_released_buffers > 0) {
  325. AVFrame *f;
  326. pthread_mutex_lock(&fctx->buffer_mutex);
  327. // fix extended data in case the caller screwed it up
  328. av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
  329. p->avctx->codec_type == AVMEDIA_TYPE_AUDIO);
  330. f = p->released_buffers[--p->num_released_buffers];
  331. f->extended_data = f->data;
  332. av_frame_unref(f);
  333. pthread_mutex_unlock(&fctx->buffer_mutex);
  334. }
  335. }
  336. #endif
  337. static int submit_packet(PerThreadContext *p, AVCodecContext *user_avctx,
  338. AVPacket *avpkt)
  339. {
  340. FrameThreadContext *fctx = p->parent;
  341. PerThreadContext *prev_thread = fctx->prev_thread;
  342. const AVCodec *codec = p->avctx->codec;
  343. int ret;
  344. if (!avpkt->size && !(codec->capabilities & AV_CODEC_CAP_DELAY))
  345. return 0;
  346. pthread_mutex_lock(&p->mutex);
  347. ret = update_context_from_user(p->avctx, user_avctx);
  348. if (ret) {
  349. pthread_mutex_unlock(&p->mutex);
  350. return ret;
  351. }
  352. atomic_store_explicit(&p->debug_threads,
  353. (p->avctx->debug & FF_DEBUG_THREADS) != 0,
  354. memory_order_relaxed);
  355. #if FF_API_THREAD_SAFE_CALLBACKS
  356. release_delayed_buffers(p);
  357. #endif
  358. if (prev_thread) {
  359. int err;
  360. if (atomic_load(&prev_thread->state) == STATE_SETTING_UP) {
  361. pthread_mutex_lock(&prev_thread->progress_mutex);
  362. while (atomic_load(&prev_thread->state) == STATE_SETTING_UP)
  363. pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
  364. pthread_mutex_unlock(&prev_thread->progress_mutex);
  365. }
  366. err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
  367. if (err) {
  368. pthread_mutex_unlock(&p->mutex);
  369. return err;
  370. }
  371. }
  372. av_packet_unref(p->avpkt);
  373. ret = av_packet_ref(p->avpkt, avpkt);
  374. if (ret < 0) {
  375. pthread_mutex_unlock(&p->mutex);
  376. av_log(p->avctx, AV_LOG_ERROR, "av_packet_ref() failed in submit_packet()\n");
  377. return ret;
  378. }
  379. atomic_store(&p->state, STATE_SETTING_UP);
  380. pthread_cond_signal(&p->input_cond);
  381. pthread_mutex_unlock(&p->mutex);
  382. #if FF_API_THREAD_SAFE_CALLBACKS
  383. FF_DISABLE_DEPRECATION_WARNINGS
  384. /*
  385. * If the client doesn't have a thread-safe get_buffer(),
  386. * then decoding threads call back to the main thread,
  387. * and it calls back to the client here.
  388. */
  389. if (!p->avctx->thread_safe_callbacks && (
  390. p->avctx->get_format != avcodec_default_get_format ||
  391. p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
  392. while (atomic_load(&p->state) != STATE_SETUP_FINISHED && atomic_load(&p->state) != STATE_INPUT_READY) {
  393. int call_done = 1;
  394. pthread_mutex_lock(&p->progress_mutex);
  395. while (atomic_load(&p->state) == STATE_SETTING_UP)
  396. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  397. switch (atomic_load_explicit(&p->state, memory_order_acquire)) {
  398. case STATE_GET_BUFFER:
  399. p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
  400. break;
  401. case STATE_GET_FORMAT:
  402. p->result_format = ff_get_format(p->avctx, p->available_formats);
  403. break;
  404. default:
  405. call_done = 0;
  406. break;
  407. }
  408. if (call_done) {
  409. atomic_store(&p->state, STATE_SETTING_UP);
  410. pthread_cond_signal(&p->progress_cond);
  411. }
  412. pthread_mutex_unlock(&p->progress_mutex);
  413. }
  414. }
  415. FF_ENABLE_DEPRECATION_WARNINGS
  416. #endif
  417. fctx->prev_thread = p;
  418. fctx->next_decoding++;
  419. return 0;
  420. }
  421. int ff_thread_decode_frame(AVCodecContext *avctx,
  422. AVFrame *picture, int *got_picture_ptr,
  423. AVPacket *avpkt)
  424. {
  425. FrameThreadContext *fctx = avctx->internal->thread_ctx;
  426. int finished = fctx->next_finished;
  427. PerThreadContext *p;
  428. int err;
  429. /* release the async lock, permitting blocked hwaccel threads to
  430. * go forward while we are in this function */
  431. async_unlock(fctx);
  432. /*
  433. * Submit a packet to the next decoding thread.
  434. */
  435. p = &fctx->threads[fctx->next_decoding];
  436. err = submit_packet(p, avctx, avpkt);
  437. if (err)
  438. goto finish;
  439. /*
  440. * If we're still receiving the initial packets, don't return a frame.
  441. */
  442. if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
  443. fctx->delaying = 0;
  444. if (fctx->delaying) {
  445. *got_picture_ptr=0;
  446. if (avpkt->size) {
  447. err = avpkt->size;
  448. goto finish;
  449. }
  450. }
  451. /*
  452. * Return the next available frame from the oldest thread.
  453. * If we're at the end of the stream, then we have to skip threads that
  454. * didn't output a frame/error, because we don't want to accidentally signal
  455. * EOF (avpkt->size == 0 && *got_picture_ptr == 0 && err >= 0).
  456. */
  457. do {
  458. p = &fctx->threads[finished++];
  459. if (atomic_load(&p->state) != STATE_INPUT_READY) {
  460. pthread_mutex_lock(&p->progress_mutex);
  461. while (atomic_load_explicit(&p->state, memory_order_relaxed) != STATE_INPUT_READY)
  462. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  463. pthread_mutex_unlock(&p->progress_mutex);
  464. }
  465. av_frame_move_ref(picture, p->frame);
  466. *got_picture_ptr = p->got_frame;
  467. picture->pkt_dts = p->avpkt->dts;
  468. err = p->result;
  469. /*
  470. * A later call with avkpt->size == 0 may loop over all threads,
  471. * including this one, searching for a frame/error to return before being
  472. * stopped by the "finished != fctx->next_finished" condition.
  473. * Make sure we don't mistakenly return the same frame/error again.
  474. */
  475. p->got_frame = 0;
  476. p->result = 0;
  477. if (finished >= avctx->thread_count) finished = 0;
  478. } while (!avpkt->size && !*got_picture_ptr && err >= 0 && finished != fctx->next_finished);
  479. update_context_from_thread(avctx, p->avctx, 1);
  480. if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
  481. fctx->next_finished = finished;
  482. /* return the size of the consumed packet if no error occurred */
  483. if (err >= 0)
  484. err = avpkt->size;
  485. finish:
  486. async_lock(fctx);
  487. return err;
  488. }
  489. void ff_thread_report_progress(ThreadFrame *f, int n, int field)
  490. {
  491. PerThreadContext *p;
  492. atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
  493. if (!progress ||
  494. atomic_load_explicit(&progress[field], memory_order_relaxed) >= n)
  495. return;
  496. p = f->owner[field]->internal->thread_ctx;
  497. if (atomic_load_explicit(&p->debug_threads, memory_order_relaxed))
  498. av_log(f->owner[field], AV_LOG_DEBUG,
  499. "%p finished %d field %d\n", progress, n, field);
  500. pthread_mutex_lock(&p->progress_mutex);
  501. atomic_store_explicit(&progress[field], n, memory_order_release);
  502. pthread_cond_broadcast(&p->progress_cond);
  503. pthread_mutex_unlock(&p->progress_mutex);
  504. }
  505. void ff_thread_await_progress(ThreadFrame *f, int n, int field)
  506. {
  507. PerThreadContext *p;
  508. atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
  509. if (!progress ||
  510. atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
  511. return;
  512. p = f->owner[field]->internal->thread_ctx;
  513. if (atomic_load_explicit(&p->debug_threads, memory_order_relaxed))
  514. av_log(f->owner[field], AV_LOG_DEBUG,
  515. "thread awaiting %d field %d from %p\n", n, field, progress);
  516. pthread_mutex_lock(&p->progress_mutex);
  517. while (atomic_load_explicit(&progress[field], memory_order_relaxed) < n)
  518. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  519. pthread_mutex_unlock(&p->progress_mutex);
  520. }
  521. void ff_thread_finish_setup(AVCodecContext *avctx) {
  522. PerThreadContext *p = avctx->internal->thread_ctx;
  523. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
  524. if (avctx->hwaccel && !p->hwaccel_serializing) {
  525. pthread_mutex_lock(&p->parent->hwaccel_mutex);
  526. p->hwaccel_serializing = 1;
  527. }
  528. /* this assumes that no hwaccel calls happen before ff_thread_finish_setup() */
  529. if (avctx->hwaccel &&
  530. !(avctx->hwaccel->caps_internal & HWACCEL_CAP_ASYNC_SAFE)) {
  531. p->async_serializing = 1;
  532. async_lock(p->parent);
  533. }
  534. pthread_mutex_lock(&p->progress_mutex);
  535. if(atomic_load(&p->state) == STATE_SETUP_FINISHED){
  536. av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
  537. }
  538. atomic_store(&p->state, STATE_SETUP_FINISHED);
  539. pthread_cond_broadcast(&p->progress_cond);
  540. pthread_mutex_unlock(&p->progress_mutex);
  541. }
  542. /// Waits for all threads to finish.
  543. static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
  544. {
  545. int i;
  546. async_unlock(fctx);
  547. for (i = 0; i < thread_count; i++) {
  548. PerThreadContext *p = &fctx->threads[i];
  549. if (atomic_load(&p->state) != STATE_INPUT_READY) {
  550. pthread_mutex_lock(&p->progress_mutex);
  551. while (atomic_load(&p->state) != STATE_INPUT_READY)
  552. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  553. pthread_mutex_unlock(&p->progress_mutex);
  554. }
  555. p->got_frame = 0;
  556. }
  557. async_lock(fctx);
  558. }
  559. #define SENTINEL 0 // This forbids putting a mutex/condition variable at the front.
  560. #define OFFSET_ARRAY(...) __VA_ARGS__, SENTINEL
  561. #define DEFINE_OFFSET_ARRAY(type, name, mutexes, conds) \
  562. static const unsigned name ## _offsets[] = { offsetof(type, pthread_init_cnt),\
  563. OFFSET_ARRAY mutexes, \
  564. OFFSET_ARRAY conds }
  565. #define OFF(member) offsetof(FrameThreadContext, member)
  566. DEFINE_OFFSET_ARRAY(FrameThreadContext, thread_ctx,
  567. (OFF(buffer_mutex), OFF(hwaccel_mutex), OFF(async_mutex)),
  568. (OFF(async_cond)));
  569. #undef OFF
  570. #define OFF(member) offsetof(PerThreadContext, member)
  571. DEFINE_OFFSET_ARRAY(PerThreadContext, per_thread,
  572. (OFF(progress_mutex), OFF(mutex)),
  573. (OFF(input_cond), OFF(progress_cond), OFF(output_cond)));
  574. #undef OFF
  575. static av_cold void free_pthread(void *obj, const unsigned offsets[])
  576. {
  577. unsigned cnt = *(unsigned*)((char*)obj + offsets[0]);
  578. const unsigned *cur_offset = offsets;
  579. for (; *(++cur_offset) != SENTINEL && cnt; cnt--)
  580. pthread_mutex_destroy((pthread_mutex_t*)((char*)obj + *cur_offset));
  581. for (; *(++cur_offset) != SENTINEL && cnt; cnt--)
  582. pthread_cond_destroy ((pthread_cond_t *)((char*)obj + *cur_offset));
  583. }
  584. static av_cold int init_pthread(void *obj, const unsigned offsets[])
  585. {
  586. const unsigned *cur_offset = offsets;
  587. unsigned cnt = 0;
  588. int err;
  589. #define PTHREAD_INIT_LOOP(type) \
  590. for (; *(++cur_offset) != SENTINEL; cnt++) { \
  591. pthread_ ## type ## _t *dst = (void*)((char*)obj + *cur_offset); \
  592. err = pthread_ ## type ## _init(dst, NULL); \
  593. if (err) { \
  594. err = AVERROR(err); \
  595. goto fail; \
  596. } \
  597. }
  598. PTHREAD_INIT_LOOP(mutex)
  599. PTHREAD_INIT_LOOP(cond)
  600. fail:
  601. *(unsigned*)((char*)obj + offsets[0]) = cnt;
  602. return err;
  603. }
  604. void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
  605. {
  606. FrameThreadContext *fctx = avctx->internal->thread_ctx;
  607. const AVCodec *codec = avctx->codec;
  608. int i;
  609. park_frame_worker_threads(fctx, thread_count);
  610. if (fctx->prev_thread && avctx->internal->hwaccel_priv_data !=
  611. fctx->prev_thread->avctx->internal->hwaccel_priv_data) {
  612. if (update_context_from_thread(avctx, fctx->prev_thread->avctx, 1) < 0) {
  613. av_log(avctx, AV_LOG_ERROR, "Failed to update user thread.\n");
  614. }
  615. }
  616. if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
  617. if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
  618. av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
  619. fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
  620. fctx->threads->avctx->internal->is_copy = 1;
  621. }
  622. for (i = 0; i < thread_count; i++) {
  623. PerThreadContext *p = &fctx->threads[i];
  624. AVCodecContext *ctx = p->avctx;
  625. if (ctx->internal) {
  626. if (p->thread_init == INITIALIZED) {
  627. pthread_mutex_lock(&p->mutex);
  628. p->die = 1;
  629. pthread_cond_signal(&p->input_cond);
  630. pthread_mutex_unlock(&p->mutex);
  631. pthread_join(p->thread, NULL);
  632. }
  633. if (codec->close && p->thread_init != UNINITIALIZED)
  634. codec->close(ctx);
  635. #if FF_API_THREAD_SAFE_CALLBACKS
  636. release_delayed_buffers(p);
  637. for (int j = 0; j < p->released_buffers_allocated; j++)
  638. av_frame_free(&p->released_buffers[j]);
  639. av_freep(&p->released_buffers);
  640. #endif
  641. if (ctx->priv_data) {
  642. if (codec->priv_class)
  643. av_opt_free(ctx->priv_data);
  644. av_freep(&ctx->priv_data);
  645. }
  646. av_freep(&ctx->slice_offset);
  647. av_buffer_unref(&ctx->internal->pool);
  648. av_freep(&ctx->internal);
  649. av_buffer_unref(&ctx->hw_frames_ctx);
  650. }
  651. av_frame_free(&p->frame);
  652. free_pthread(p, per_thread_offsets);
  653. av_packet_free(&p->avpkt);
  654. av_freep(&p->avctx);
  655. }
  656. av_freep(&fctx->threads);
  657. free_pthread(fctx, thread_ctx_offsets);
  658. av_freep(&avctx->internal->thread_ctx);
  659. if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
  660. av_opt_free(avctx->priv_data);
  661. avctx->codec = NULL;
  662. }
  663. static av_cold int init_thread(PerThreadContext *p, int *threads_to_free,
  664. FrameThreadContext *fctx, AVCodecContext *avctx,
  665. AVCodecContext *src, const AVCodec *codec, int first)
  666. {
  667. AVCodecContext *copy;
  668. int err;
  669. atomic_init(&p->state, STATE_INPUT_READY);
  670. copy = av_memdup(src, sizeof(*src));
  671. if (!copy)
  672. return AVERROR(ENOMEM);
  673. copy->priv_data = NULL;
  674. /* From now on, this PerThreadContext will be cleaned up by
  675. * ff_frame_thread_free in case of errors. */
  676. (*threads_to_free)++;
  677. p->parent = fctx;
  678. p->avctx = copy;
  679. copy->internal = av_memdup(src->internal, sizeof(*src->internal));
  680. if (!copy->internal)
  681. return AVERROR(ENOMEM);
  682. copy->internal->thread_ctx = p;
  683. copy->delay = avctx->delay;
  684. if (codec->priv_data_size) {
  685. copy->priv_data = av_mallocz(codec->priv_data_size);
  686. if (!copy->priv_data)
  687. return AVERROR(ENOMEM);
  688. if (codec->priv_class) {
  689. *(const AVClass **)copy->priv_data = codec->priv_class;
  690. err = av_opt_copy(copy->priv_data, src->priv_data);
  691. if (err < 0)
  692. return err;
  693. }
  694. }
  695. err = init_pthread(p, per_thread_offsets);
  696. if (err < 0)
  697. return err;
  698. if (!(p->frame = av_frame_alloc()) ||
  699. !(p->avpkt = av_packet_alloc()))
  700. return AVERROR(ENOMEM);
  701. copy->internal->last_pkt_props = p->avpkt;
  702. if (!first)
  703. copy->internal->is_copy = 1;
  704. if (codec->init) {
  705. err = codec->init(copy);
  706. if (err < 0) {
  707. if (codec->caps_internal & FF_CODEC_CAP_INIT_CLEANUP)
  708. p->thread_init = NEEDS_CLOSE;
  709. return err;
  710. }
  711. }
  712. p->thread_init = NEEDS_CLOSE;
  713. if (first)
  714. update_context_from_thread(avctx, copy, 1);
  715. atomic_init(&p->debug_threads, (copy->debug & FF_DEBUG_THREADS) != 0);
  716. err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
  717. if (err < 0)
  718. return err;
  719. p->thread_init = INITIALIZED;
  720. return 0;
  721. }
  722. int ff_frame_thread_init(AVCodecContext *avctx)
  723. {
  724. int thread_count = avctx->thread_count;
  725. const AVCodec *codec = avctx->codec;
  726. AVCodecContext *src = avctx;
  727. FrameThreadContext *fctx;
  728. int err, i = 0;
  729. if (!thread_count) {
  730. int nb_cpus = av_cpu_count();
  731. // use number of cores + 1 as thread count if there is more than one
  732. if (nb_cpus > 1)
  733. thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
  734. else
  735. thread_count = avctx->thread_count = 1;
  736. }
  737. if (thread_count <= 1) {
  738. avctx->active_thread_type = 0;
  739. return 0;
  740. }
  741. avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
  742. if (!fctx)
  743. return AVERROR(ENOMEM);
  744. err = init_pthread(fctx, thread_ctx_offsets);
  745. if (err < 0) {
  746. free_pthread(fctx, thread_ctx_offsets);
  747. av_freep(&avctx->internal->thread_ctx);
  748. return err;
  749. }
  750. fctx->async_lock = 1;
  751. fctx->delaying = 1;
  752. if (codec->type == AVMEDIA_TYPE_VIDEO)
  753. avctx->delay = src->thread_count - 1;
  754. fctx->threads = av_mallocz_array(thread_count, sizeof(PerThreadContext));
  755. if (!fctx->threads) {
  756. err = AVERROR(ENOMEM);
  757. goto error;
  758. }
  759. for (; i < thread_count; ) {
  760. PerThreadContext *p = &fctx->threads[i];
  761. int first = !i;
  762. err = init_thread(p, &i, fctx, avctx, src, codec, first);
  763. if (err < 0)
  764. goto error;
  765. }
  766. return 0;
  767. error:
  768. ff_frame_thread_free(avctx, i);
  769. return err;
  770. }
  771. void ff_thread_flush(AVCodecContext *avctx)
  772. {
  773. int i;
  774. FrameThreadContext *fctx = avctx->internal->thread_ctx;
  775. if (!fctx) return;
  776. park_frame_worker_threads(fctx, avctx->thread_count);
  777. if (fctx->prev_thread) {
  778. if (fctx->prev_thread != &fctx->threads[0])
  779. update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
  780. }
  781. fctx->next_decoding = fctx->next_finished = 0;
  782. fctx->delaying = 1;
  783. fctx->prev_thread = NULL;
  784. for (i = 0; i < avctx->thread_count; i++) {
  785. PerThreadContext *p = &fctx->threads[i];
  786. // Make sure decode flush calls with size=0 won't return old frames
  787. p->got_frame = 0;
  788. av_frame_unref(p->frame);
  789. p->result = 0;
  790. #if FF_API_THREAD_SAFE_CALLBACKS
  791. release_delayed_buffers(p);
  792. #endif
  793. if (avctx->codec->flush)
  794. avctx->codec->flush(p->avctx);
  795. }
  796. }
  797. int ff_thread_can_start_frame(AVCodecContext *avctx)
  798. {
  799. PerThreadContext *p = avctx->internal->thread_ctx;
  800. FF_DISABLE_DEPRECATION_WARNINGS
  801. if ((avctx->active_thread_type&FF_THREAD_FRAME) && atomic_load(&p->state) != STATE_SETTING_UP &&
  802. (avctx->codec->update_thread_context
  803. #if FF_API_THREAD_SAFE_CALLBACKS
  804. || !THREAD_SAFE_CALLBACKS(avctx)
  805. #endif
  806. )) {
  807. return 0;
  808. }
  809. FF_ENABLE_DEPRECATION_WARNINGS
  810. return 1;
  811. }
  812. static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
  813. {
  814. PerThreadContext *p = avctx->internal->thread_ctx;
  815. int err;
  816. f->owner[0] = f->owner[1] = avctx;
  817. if (!(avctx->active_thread_type & FF_THREAD_FRAME))
  818. return ff_get_buffer(avctx, f->f, flags);
  819. FF_DISABLE_DEPRECATION_WARNINGS
  820. if (atomic_load(&p->state) != STATE_SETTING_UP &&
  821. (avctx->codec->update_thread_context
  822. #if FF_API_THREAD_SAFE_CALLBACKS
  823. || !THREAD_SAFE_CALLBACKS(avctx)
  824. #endif
  825. )) {
  826. FF_ENABLE_DEPRECATION_WARNINGS
  827. av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
  828. return -1;
  829. }
  830. if (avctx->codec->caps_internal & FF_CODEC_CAP_ALLOCATE_PROGRESS) {
  831. atomic_int *progress;
  832. f->progress = av_buffer_alloc(2 * sizeof(*progress));
  833. if (!f->progress) {
  834. return AVERROR(ENOMEM);
  835. }
  836. progress = (atomic_int*)f->progress->data;
  837. atomic_init(&progress[0], -1);
  838. atomic_init(&progress[1], -1);
  839. }
  840. pthread_mutex_lock(&p->parent->buffer_mutex);
  841. #if !FF_API_THREAD_SAFE_CALLBACKS
  842. err = ff_get_buffer(avctx, f->f, flags);
  843. #else
  844. FF_DISABLE_DEPRECATION_WARNINGS
  845. if (THREAD_SAFE_CALLBACKS(avctx)) {
  846. err = ff_get_buffer(avctx, f->f, flags);
  847. } else {
  848. pthread_mutex_lock(&p->progress_mutex);
  849. p->requested_frame = f->f;
  850. p->requested_flags = flags;
  851. atomic_store_explicit(&p->state, STATE_GET_BUFFER, memory_order_release);
  852. pthread_cond_broadcast(&p->progress_cond);
  853. while (atomic_load(&p->state) != STATE_SETTING_UP)
  854. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  855. err = p->result;
  856. pthread_mutex_unlock(&p->progress_mutex);
  857. }
  858. if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
  859. ff_thread_finish_setup(avctx);
  860. FF_ENABLE_DEPRECATION_WARNINGS
  861. #endif
  862. if (err)
  863. av_buffer_unref(&f->progress);
  864. pthread_mutex_unlock(&p->parent->buffer_mutex);
  865. return err;
  866. }
  867. #if FF_API_THREAD_SAFE_CALLBACKS
  868. FF_DISABLE_DEPRECATION_WARNINGS
  869. enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
  870. {
  871. enum AVPixelFormat res;
  872. PerThreadContext *p = avctx->internal->thread_ctx;
  873. if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
  874. avctx->get_format == avcodec_default_get_format)
  875. return ff_get_format(avctx, fmt);
  876. if (atomic_load(&p->state) != STATE_SETTING_UP) {
  877. av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
  878. return -1;
  879. }
  880. pthread_mutex_lock(&p->progress_mutex);
  881. p->available_formats = fmt;
  882. atomic_store(&p->state, STATE_GET_FORMAT);
  883. pthread_cond_broadcast(&p->progress_cond);
  884. while (atomic_load(&p->state) != STATE_SETTING_UP)
  885. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  886. res = p->result_format;
  887. pthread_mutex_unlock(&p->progress_mutex);
  888. return res;
  889. }
  890. FF_ENABLE_DEPRECATION_WARNINGS
  891. #endif
  892. int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
  893. {
  894. int ret = thread_get_buffer_internal(avctx, f, flags);
  895. if (ret < 0)
  896. av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
  897. return ret;
  898. }
  899. void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
  900. {
  901. #if FF_API_THREAD_SAFE_CALLBACKS
  902. FF_DISABLE_DEPRECATION_WARNINGS
  903. PerThreadContext *p = avctx->internal->thread_ctx;
  904. FrameThreadContext *fctx;
  905. AVFrame *dst;
  906. int ret = 0;
  907. int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
  908. THREAD_SAFE_CALLBACKS(avctx);
  909. FF_ENABLE_DEPRECATION_WARNINGS
  910. #endif
  911. if (!f->f)
  912. return;
  913. if (avctx->debug & FF_DEBUG_BUFFERS)
  914. av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
  915. av_buffer_unref(&f->progress);
  916. f->owner[0] = f->owner[1] = NULL;
  917. #if !FF_API_THREAD_SAFE_CALLBACKS
  918. av_frame_unref(f->f);
  919. #else
  920. // when the frame buffers are not allocated, just reset it to clean state
  921. if (can_direct_free || !f->f->buf[0]) {
  922. av_frame_unref(f->f);
  923. return;
  924. }
  925. fctx = p->parent;
  926. pthread_mutex_lock(&fctx->buffer_mutex);
  927. if (p->num_released_buffers == p->released_buffers_allocated) {
  928. AVFrame **tmp = av_realloc_array(p->released_buffers, p->released_buffers_allocated + 1,
  929. sizeof(*p->released_buffers));
  930. if (tmp) {
  931. tmp[p->released_buffers_allocated] = av_frame_alloc();
  932. p->released_buffers = tmp;
  933. }
  934. if (!tmp || !tmp[p->released_buffers_allocated]) {
  935. ret = AVERROR(ENOMEM);
  936. goto fail;
  937. }
  938. p->released_buffers_allocated++;
  939. }
  940. dst = p->released_buffers[p->num_released_buffers];
  941. av_frame_move_ref(dst, f->f);
  942. p->num_released_buffers++;
  943. fail:
  944. pthread_mutex_unlock(&fctx->buffer_mutex);
  945. // make sure the frame is clean even if we fail to free it
  946. // this leaks, but it is better than crashing
  947. if (ret < 0) {
  948. av_log(avctx, AV_LOG_ERROR, "Could not queue a frame for freeing, this will leak\n");
  949. memset(f->f->buf, 0, sizeof(f->f->buf));
  950. if (f->f->extended_buf)
  951. memset(f->f->extended_buf, 0, f->f->nb_extended_buf * sizeof(*f->f->extended_buf));
  952. av_frame_unref(f->f);
  953. }
  954. #endif
  955. }