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.

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