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.

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