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.

892 lines
28KB

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