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.

915 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. }
  197. if (for_user) {
  198. dst->delay = src->thread_count - 1;
  199. #if FF_API_CODED_FRAME
  200. FF_DISABLE_DEPRECATION_WARNINGS
  201. dst->coded_frame = src->coded_frame;
  202. FF_ENABLE_DEPRECATION_WARNINGS
  203. #endif
  204. } else {
  205. if (dst->codec->update_thread_context)
  206. err = dst->codec->update_thread_context(dst, src);
  207. }
  208. return err;
  209. }
  210. /**
  211. * Update the next thread's AVCodecContext with values set by the user.
  212. *
  213. * @param dst The destination context.
  214. * @param src The source context.
  215. * @return 0 on success, negative error code on failure
  216. */
  217. static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
  218. {
  219. #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
  220. dst->flags = src->flags;
  221. dst->draw_horiz_band= src->draw_horiz_band;
  222. dst->get_buffer2 = src->get_buffer2;
  223. dst->opaque = src->opaque;
  224. dst->debug = src->debug;
  225. dst->debug_mv = src->debug_mv;
  226. dst->slice_flags = src->slice_flags;
  227. dst->flags2 = src->flags2;
  228. copy_fields(skip_loop_filter, subtitle_header);
  229. dst->frame_number = src->frame_number;
  230. dst->reordered_opaque = src->reordered_opaque;
  231. dst->thread_safe_callbacks = src->thread_safe_callbacks;
  232. if (src->slice_count && src->slice_offset) {
  233. if (dst->slice_count < src->slice_count) {
  234. int err = av_reallocp_array(&dst->slice_offset, src->slice_count,
  235. sizeof(*dst->slice_offset));
  236. if (err < 0)
  237. return err;
  238. }
  239. memcpy(dst->slice_offset, src->slice_offset,
  240. src->slice_count * sizeof(*dst->slice_offset));
  241. }
  242. dst->slice_count = src->slice_count;
  243. return 0;
  244. #undef copy_fields
  245. }
  246. /// Releases the buffers that this decoding thread was the last user of.
  247. static void release_delayed_buffers(PerThreadContext *p)
  248. {
  249. FrameThreadContext *fctx = p->parent;
  250. while (p->num_released_buffers > 0) {
  251. AVFrame *f;
  252. pthread_mutex_lock(&fctx->buffer_mutex);
  253. // fix extended data in case the caller screwed it up
  254. av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
  255. p->avctx->codec_type == AVMEDIA_TYPE_AUDIO);
  256. f = &p->released_buffers[--p->num_released_buffers];
  257. f->extended_data = f->data;
  258. av_frame_unref(f);
  259. pthread_mutex_unlock(&fctx->buffer_mutex);
  260. }
  261. }
  262. static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
  263. {
  264. FrameThreadContext *fctx = p->parent;
  265. PerThreadContext *prev_thread = fctx->prev_thread;
  266. const AVCodec *codec = p->avctx->codec;
  267. int ret;
  268. if (!avpkt->size && !(codec->capabilities & AV_CODEC_CAP_DELAY))
  269. return 0;
  270. pthread_mutex_lock(&p->mutex);
  271. release_delayed_buffers(p);
  272. if (prev_thread) {
  273. int err;
  274. if (atomic_load(&prev_thread->state) == STATE_SETTING_UP) {
  275. pthread_mutex_lock(&prev_thread->progress_mutex);
  276. while (atomic_load(&prev_thread->state) == STATE_SETTING_UP)
  277. pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
  278. pthread_mutex_unlock(&prev_thread->progress_mutex);
  279. }
  280. err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
  281. if (err) {
  282. pthread_mutex_unlock(&p->mutex);
  283. return err;
  284. }
  285. }
  286. av_packet_unref(&p->avpkt);
  287. ret = av_packet_ref(&p->avpkt, avpkt);
  288. if (ret < 0) {
  289. pthread_mutex_unlock(&p->mutex);
  290. av_log(p->avctx, AV_LOG_ERROR, "av_packet_ref() failed in submit_packet()\n");
  291. return ret;
  292. }
  293. atomic_store(&p->state, STATE_SETTING_UP);
  294. pthread_cond_signal(&p->input_cond);
  295. pthread_mutex_unlock(&p->mutex);
  296. /*
  297. * If the client doesn't have a thread-safe get_buffer(),
  298. * then decoding threads call back to the main thread,
  299. * and it calls back to the client here.
  300. */
  301. if (!p->avctx->thread_safe_callbacks && (
  302. p->avctx->get_format != avcodec_default_get_format ||
  303. p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
  304. while (atomic_load(&p->state) != STATE_SETUP_FINISHED && atomic_load(&p->state) != STATE_INPUT_READY) {
  305. int call_done = 1;
  306. pthread_mutex_lock(&p->progress_mutex);
  307. while (atomic_load(&p->state) == STATE_SETTING_UP)
  308. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  309. switch (atomic_load_explicit(&p->state, memory_order_acquire)) {
  310. case STATE_GET_BUFFER:
  311. p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
  312. break;
  313. case STATE_GET_FORMAT:
  314. p->result_format = ff_get_format(p->avctx, p->available_formats);
  315. break;
  316. default:
  317. call_done = 0;
  318. break;
  319. }
  320. if (call_done) {
  321. atomic_store(&p->state, STATE_SETTING_UP);
  322. pthread_cond_signal(&p->progress_cond);
  323. }
  324. pthread_mutex_unlock(&p->progress_mutex);
  325. }
  326. }
  327. fctx->prev_thread = p;
  328. fctx->next_decoding++;
  329. return 0;
  330. }
  331. int ff_thread_decode_frame(AVCodecContext *avctx,
  332. AVFrame *picture, int *got_picture_ptr,
  333. AVPacket *avpkt)
  334. {
  335. FrameThreadContext *fctx = avctx->internal->thread_ctx;
  336. int finished = fctx->next_finished;
  337. PerThreadContext *p;
  338. int err;
  339. /*
  340. * Submit a packet to the next decoding thread.
  341. */
  342. p = &fctx->threads[fctx->next_decoding];
  343. err = update_context_from_user(p->avctx, avctx);
  344. if (err) return err;
  345. err = submit_packet(p, avpkt);
  346. if (err) return err;
  347. /*
  348. * If we're still receiving the initial packets, don't return a frame.
  349. */
  350. if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
  351. fctx->delaying = 0;
  352. if (fctx->delaying) {
  353. *got_picture_ptr=0;
  354. if (avpkt->size)
  355. return avpkt->size;
  356. }
  357. /*
  358. * Return the next available frame from the oldest thread.
  359. * If we're at the end of the stream, then we have to skip threads that
  360. * didn't output a frame, because we don't want to accidentally signal
  361. * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
  362. */
  363. do {
  364. p = &fctx->threads[finished++];
  365. if (atomic_load(&p->state) != STATE_INPUT_READY) {
  366. pthread_mutex_lock(&p->progress_mutex);
  367. while (atomic_load_explicit(&p->state, memory_order_relaxed) != STATE_INPUT_READY)
  368. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  369. pthread_mutex_unlock(&p->progress_mutex);
  370. }
  371. av_frame_move_ref(picture, p->frame);
  372. *got_picture_ptr = p->got_frame;
  373. picture->pkt_dts = p->avpkt.dts;
  374. if (p->result < 0)
  375. err = p->result;
  376. /*
  377. * A later call with avkpt->size == 0 may loop over all threads,
  378. * including this one, searching for a frame to return before being
  379. * stopped by the "finished != fctx->next_finished" condition.
  380. * Make sure we don't mistakenly return the same frame again.
  381. */
  382. p->got_frame = 0;
  383. if (finished >= avctx->thread_count) finished = 0;
  384. } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
  385. update_context_from_thread(avctx, p->avctx, 1);
  386. if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
  387. fctx->next_finished = finished;
  388. /*
  389. * When no frame was found while flushing, but an error occurred in
  390. * any thread, return it instead of 0.
  391. * Otherwise the error can get lost.
  392. */
  393. if (!avpkt->size && !*got_picture_ptr)
  394. return err;
  395. /* return the size of the consumed packet if no error occurred */
  396. return (p->result >= 0) ? avpkt->size : p->result;
  397. }
  398. void ff_thread_report_progress(ThreadFrame *f, int n, int field)
  399. {
  400. PerThreadContext *p;
  401. atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
  402. if (!progress ||
  403. atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
  404. return;
  405. p = f->owner->internal->thread_ctx;
  406. if (f->owner->debug&FF_DEBUG_THREADS)
  407. av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
  408. pthread_mutex_lock(&p->progress_mutex);
  409. atomic_store(&progress[field], n);
  410. pthread_cond_broadcast(&p->progress_cond);
  411. pthread_mutex_unlock(&p->progress_mutex);
  412. }
  413. void ff_thread_await_progress(ThreadFrame *f, int n, int field)
  414. {
  415. PerThreadContext *p;
  416. atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
  417. if (!progress ||
  418. atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
  419. return;
  420. p = f->owner->internal->thread_ctx;
  421. if (f->owner->debug&FF_DEBUG_THREADS)
  422. av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
  423. pthread_mutex_lock(&p->progress_mutex);
  424. while (atomic_load_explicit(&progress[field], memory_order_relaxed) < n)
  425. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  426. pthread_mutex_unlock(&p->progress_mutex);
  427. }
  428. void ff_thread_finish_setup(AVCodecContext *avctx) {
  429. PerThreadContext *p = avctx->internal->thread_ctx;
  430. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
  431. pthread_mutex_lock(&p->progress_mutex);
  432. if(atomic_load(&p->state) == STATE_SETUP_FINISHED){
  433. av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
  434. }
  435. atomic_store(&p->state, STATE_SETUP_FINISHED);
  436. pthread_cond_broadcast(&p->progress_cond);
  437. pthread_mutex_unlock(&p->progress_mutex);
  438. }
  439. /// Waits for all threads to finish.
  440. static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
  441. {
  442. int i;
  443. for (i = 0; i < thread_count; i++) {
  444. PerThreadContext *p = &fctx->threads[i];
  445. if (atomic_load(&p->state) != STATE_INPUT_READY) {
  446. pthread_mutex_lock(&p->progress_mutex);
  447. while (atomic_load(&p->state) != STATE_INPUT_READY)
  448. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  449. pthread_mutex_unlock(&p->progress_mutex);
  450. }
  451. p->got_frame = 0;
  452. }
  453. }
  454. void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
  455. {
  456. FrameThreadContext *fctx = avctx->internal->thread_ctx;
  457. const AVCodec *codec = avctx->codec;
  458. int i;
  459. park_frame_worker_threads(fctx, thread_count);
  460. if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
  461. if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
  462. av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
  463. fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
  464. fctx->threads->avctx->internal->is_copy = 1;
  465. }
  466. for (i = 0; i < thread_count; i++) {
  467. PerThreadContext *p = &fctx->threads[i];
  468. pthread_mutex_lock(&p->mutex);
  469. p->die = 1;
  470. pthread_cond_signal(&p->input_cond);
  471. pthread_mutex_unlock(&p->mutex);
  472. if (p->thread_init)
  473. pthread_join(p->thread, NULL);
  474. p->thread_init=0;
  475. if (codec->close && p->avctx)
  476. codec->close(p->avctx);
  477. release_delayed_buffers(p);
  478. av_frame_free(&p->frame);
  479. }
  480. for (i = 0; i < thread_count; i++) {
  481. PerThreadContext *p = &fctx->threads[i];
  482. pthread_mutex_destroy(&p->mutex);
  483. pthread_mutex_destroy(&p->progress_mutex);
  484. pthread_cond_destroy(&p->input_cond);
  485. pthread_cond_destroy(&p->progress_cond);
  486. pthread_cond_destroy(&p->output_cond);
  487. av_packet_unref(&p->avpkt);
  488. av_freep(&p->released_buffers);
  489. if (i && p->avctx) {
  490. av_freep(&p->avctx->priv_data);
  491. av_freep(&p->avctx->slice_offset);
  492. }
  493. if (p->avctx)
  494. av_freep(&p->avctx->internal);
  495. av_freep(&p->avctx);
  496. }
  497. av_freep(&fctx->threads);
  498. pthread_mutex_destroy(&fctx->buffer_mutex);
  499. av_freep(&avctx->internal->thread_ctx);
  500. if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
  501. av_opt_free(avctx->priv_data);
  502. avctx->codec = NULL;
  503. }
  504. int ff_frame_thread_init(AVCodecContext *avctx)
  505. {
  506. int thread_count = avctx->thread_count;
  507. const AVCodec *codec = avctx->codec;
  508. AVCodecContext *src = avctx;
  509. FrameThreadContext *fctx;
  510. int i, err = 0;
  511. #if HAVE_W32THREADS
  512. w32thread_init();
  513. #endif
  514. if (!thread_count) {
  515. int nb_cpus = av_cpu_count();
  516. if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
  517. nb_cpus = 1;
  518. // use number of cores + 1 as thread count if there is more than one
  519. if (nb_cpus > 1)
  520. thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
  521. else
  522. thread_count = avctx->thread_count = 1;
  523. }
  524. if (thread_count <= 1) {
  525. avctx->active_thread_type = 0;
  526. return 0;
  527. }
  528. avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
  529. if (!fctx)
  530. return AVERROR(ENOMEM);
  531. fctx->threads = av_mallocz_array(thread_count, sizeof(PerThreadContext));
  532. if (!fctx->threads) {
  533. av_freep(&avctx->internal->thread_ctx);
  534. return AVERROR(ENOMEM);
  535. }
  536. pthread_mutex_init(&fctx->buffer_mutex, NULL);
  537. fctx->delaying = 1;
  538. for (i = 0; i < thread_count; i++) {
  539. AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
  540. PerThreadContext *p = &fctx->threads[i];
  541. pthread_mutex_init(&p->mutex, NULL);
  542. pthread_mutex_init(&p->progress_mutex, NULL);
  543. pthread_cond_init(&p->input_cond, NULL);
  544. pthread_cond_init(&p->progress_cond, NULL);
  545. pthread_cond_init(&p->output_cond, NULL);
  546. p->frame = av_frame_alloc();
  547. if (!p->frame) {
  548. av_freep(&copy);
  549. err = AVERROR(ENOMEM);
  550. goto error;
  551. }
  552. p->parent = fctx;
  553. p->avctx = copy;
  554. if (!copy) {
  555. err = AVERROR(ENOMEM);
  556. goto error;
  557. }
  558. *copy = *src;
  559. copy->internal = av_malloc(sizeof(AVCodecInternal));
  560. if (!copy->internal) {
  561. copy->priv_data = NULL;
  562. err = AVERROR(ENOMEM);
  563. goto error;
  564. }
  565. *copy->internal = *src->internal;
  566. copy->internal->thread_ctx = p;
  567. copy->internal->pkt = &p->avpkt;
  568. if (!i) {
  569. src = copy;
  570. if (codec->init)
  571. err = codec->init(copy);
  572. update_context_from_thread(avctx, copy, 1);
  573. } else {
  574. copy->priv_data = av_malloc(codec->priv_data_size);
  575. if (!copy->priv_data) {
  576. err = AVERROR(ENOMEM);
  577. goto error;
  578. }
  579. memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
  580. copy->internal->is_copy = 1;
  581. if (codec->init_thread_copy)
  582. err = codec->init_thread_copy(copy);
  583. }
  584. if (err) goto error;
  585. err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
  586. p->thread_init= !err;
  587. if(!p->thread_init)
  588. goto error;
  589. }
  590. return 0;
  591. error:
  592. ff_frame_thread_free(avctx, i+1);
  593. return err;
  594. }
  595. void ff_thread_flush(AVCodecContext *avctx)
  596. {
  597. int i;
  598. FrameThreadContext *fctx = avctx->internal->thread_ctx;
  599. if (!fctx) return;
  600. park_frame_worker_threads(fctx, avctx->thread_count);
  601. if (fctx->prev_thread) {
  602. if (fctx->prev_thread != &fctx->threads[0])
  603. update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
  604. }
  605. fctx->next_decoding = fctx->next_finished = 0;
  606. fctx->delaying = 1;
  607. fctx->prev_thread = NULL;
  608. for (i = 0; i < avctx->thread_count; i++) {
  609. PerThreadContext *p = &fctx->threads[i];
  610. // Make sure decode flush calls with size=0 won't return old frames
  611. p->got_frame = 0;
  612. av_frame_unref(p->frame);
  613. release_delayed_buffers(p);
  614. if (avctx->codec->flush)
  615. avctx->codec->flush(p->avctx);
  616. }
  617. }
  618. int ff_thread_can_start_frame(AVCodecContext *avctx)
  619. {
  620. PerThreadContext *p = avctx->internal->thread_ctx;
  621. if ((avctx->active_thread_type&FF_THREAD_FRAME) && atomic_load(&p->state) != STATE_SETTING_UP &&
  622. (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
  623. return 0;
  624. }
  625. return 1;
  626. }
  627. static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
  628. {
  629. PerThreadContext *p = avctx->internal->thread_ctx;
  630. int err;
  631. f->owner = avctx;
  632. ff_init_buffer_info(avctx, f->f);
  633. if (!(avctx->active_thread_type & FF_THREAD_FRAME))
  634. return ff_get_buffer(avctx, f->f, flags);
  635. if (atomic_load(&p->state) != STATE_SETTING_UP &&
  636. (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
  637. av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
  638. return -1;
  639. }
  640. if (avctx->internal->allocate_progress) {
  641. atomic_int *progress;
  642. f->progress = av_buffer_alloc(2 * sizeof(*progress));
  643. if (!f->progress) {
  644. return AVERROR(ENOMEM);
  645. }
  646. progress = (atomic_int*)f->progress->data;
  647. atomic_store(&progress[0], -1);
  648. atomic_store(&progress[1], -1);
  649. }
  650. pthread_mutex_lock(&p->parent->buffer_mutex);
  651. if (avctx->thread_safe_callbacks ||
  652. avctx->get_buffer2 == avcodec_default_get_buffer2) {
  653. err = ff_get_buffer(avctx, f->f, flags);
  654. } else {
  655. pthread_mutex_lock(&p->progress_mutex);
  656. p->requested_frame = f->f;
  657. p->requested_flags = flags;
  658. atomic_store_explicit(&p->state, STATE_GET_BUFFER, memory_order_release);
  659. pthread_cond_broadcast(&p->progress_cond);
  660. while (atomic_load(&p->state) != STATE_SETTING_UP)
  661. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  662. err = p->result;
  663. pthread_mutex_unlock(&p->progress_mutex);
  664. }
  665. if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
  666. ff_thread_finish_setup(avctx);
  667. if (err)
  668. av_buffer_unref(&f->progress);
  669. pthread_mutex_unlock(&p->parent->buffer_mutex);
  670. return err;
  671. }
  672. enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
  673. {
  674. enum AVPixelFormat res;
  675. PerThreadContext *p = avctx->internal->thread_ctx;
  676. if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
  677. avctx->get_format == avcodec_default_get_format)
  678. return ff_get_format(avctx, fmt);
  679. if (atomic_load(&p->state) != STATE_SETTING_UP) {
  680. av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
  681. return -1;
  682. }
  683. pthread_mutex_lock(&p->progress_mutex);
  684. p->available_formats = fmt;
  685. atomic_store(&p->state, STATE_GET_FORMAT);
  686. pthread_cond_broadcast(&p->progress_cond);
  687. while (atomic_load(&p->state) != STATE_SETTING_UP)
  688. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  689. res = p->result_format;
  690. pthread_mutex_unlock(&p->progress_mutex);
  691. return res;
  692. }
  693. int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
  694. {
  695. int ret = thread_get_buffer_internal(avctx, f, flags);
  696. if (ret < 0)
  697. av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
  698. return ret;
  699. }
  700. void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
  701. {
  702. PerThreadContext *p = avctx->internal->thread_ctx;
  703. FrameThreadContext *fctx;
  704. AVFrame *dst, *tmp;
  705. int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
  706. avctx->thread_safe_callbacks ||
  707. avctx->get_buffer2 == avcodec_default_get_buffer2;
  708. if (!f->f || !f->f->buf[0])
  709. return;
  710. if (avctx->debug & FF_DEBUG_BUFFERS)
  711. av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
  712. av_buffer_unref(&f->progress);
  713. f->owner = NULL;
  714. if (can_direct_free) {
  715. av_frame_unref(f->f);
  716. return;
  717. }
  718. fctx = p->parent;
  719. pthread_mutex_lock(&fctx->buffer_mutex);
  720. if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
  721. goto fail;
  722. tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
  723. (p->num_released_buffers + 1) *
  724. sizeof(*p->released_buffers));
  725. if (!tmp)
  726. goto fail;
  727. p->released_buffers = tmp;
  728. dst = &p->released_buffers[p->num_released_buffers];
  729. av_frame_move_ref(dst, f->f);
  730. p->num_released_buffers++;
  731. fail:
  732. pthread_mutex_unlock(&fctx->buffer_mutex);
  733. }