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.

1127 lines
35KB

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