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.

929 lines
29KB

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