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.

1003 lines
32KB

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