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.

1124 lines
36KB

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