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.

896 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 "libavutil/avassert.h"
  37. #include "libavutil/buffer.h"
  38. #include "libavutil/common.h"
  39. #include "libavutil/cpu.h"
  40. #include "libavutil/frame.h"
  41. #include "libavutil/log.h"
  42. #include "libavutil/mem.h"
  43. /**
  44. * Context used by codec threads and stored in their AVCodecInternal thread_ctx.
  45. */
  46. typedef struct PerThreadContext {
  47. struct FrameThreadContext *parent;
  48. pthread_t thread;
  49. int thread_init;
  50. pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
  51. pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
  52. pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
  53. pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
  54. pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
  55. AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
  56. AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
  57. uint8_t *buf; ///< backup storage for packet data when the input packet is not refcounted
  58. int allocated_buf_size; ///< Size allocated for buf
  59. AVFrame *frame; ///< Output frame (for decoding) or input (for encoding).
  60. int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
  61. int result; ///< The result of the last codec decode/encode() call.
  62. enum {
  63. STATE_INPUT_READY, ///< Set when the thread is awaiting a packet.
  64. STATE_SETTING_UP, ///< Set before the codec has called ff_thread_finish_setup().
  65. STATE_GET_BUFFER, /**<
  66. * Set when the codec calls get_buffer().
  67. * State is returned to STATE_SETTING_UP afterwards.
  68. */
  69. STATE_GET_FORMAT, /**<
  70. * Set when the codec calls get_format().
  71. * State is returned to STATE_SETTING_UP afterwards.
  72. */
  73. STATE_SETUP_FINISHED ///< Set after the codec has called ff_thread_finish_setup().
  74. } state;
  75. /**
  76. * Array of frames passed to ff_thread_release_buffer().
  77. * Frames are released after all threads referencing them are finished.
  78. */
  79. AVFrame *released_buffers;
  80. int num_released_buffers;
  81. int released_buffers_allocated;
  82. AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
  83. int requested_flags; ///< flags passed to get_buffer() for requested_frame
  84. const enum AVPixelFormat *available_formats; ///< Format array for get_format()
  85. enum AVPixelFormat result_format; ///< get_format() result
  86. } PerThreadContext;
  87. /**
  88. * Context stored in the client AVCodecInternal thread_ctx.
  89. */
  90. typedef struct FrameThreadContext {
  91. PerThreadContext *threads; ///< The contexts for each thread.
  92. PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
  93. pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
  94. int next_decoding; ///< The next context to submit a packet to.
  95. int next_finished; ///< The next context to return output from.
  96. int delaying; /**<
  97. * Set for the first N packets, where N is the number of threads.
  98. * While it is set, ff_thread_en/decode_frame won't return any results.
  99. */
  100. int die; ///< Set when threads should exit.
  101. } FrameThreadContext;
  102. #define THREAD_SAFE_CALLBACKS(avctx) \
  103. ((avctx)->thread_safe_callbacks || (!(avctx)->get_buffer && (avctx)->get_buffer2 == avcodec_default_get_buffer2))
  104. /**
  105. * Codec worker thread.
  106. *
  107. * Automatically calls ff_thread_finish_setup() if the codec does
  108. * not provide an update_thread_context method, or if the codec returns
  109. * before calling it.
  110. */
  111. static attribute_align_arg void *frame_worker_thread(void *arg)
  112. {
  113. PerThreadContext *p = arg;
  114. FrameThreadContext *fctx = p->parent;
  115. AVCodecContext *avctx = p->avctx;
  116. const AVCodec *codec = avctx->codec;
  117. pthread_mutex_lock(&p->mutex);
  118. while (1) {
  119. while (p->state == STATE_INPUT_READY && !fctx->die)
  120. pthread_cond_wait(&p->input_cond, &p->mutex);
  121. if (fctx->die) break;
  122. if (!codec->update_thread_context && THREAD_SAFE_CALLBACKS(avctx))
  123. ff_thread_finish_setup(avctx);
  124. av_frame_unref(p->frame);
  125. p->got_frame = 0;
  126. p->result = codec->decode(avctx, p->frame, &p->got_frame, &p->avpkt);
  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. */
  151. static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
  152. {
  153. int err = 0;
  154. if (dst != src) {
  155. dst->time_base = src->time_base;
  156. dst->width = src->width;
  157. dst->height = src->height;
  158. dst->pix_fmt = src->pix_fmt;
  159. dst->coded_width = src->coded_width;
  160. dst->coded_height = src->coded_height;
  161. dst->has_b_frames = src->has_b_frames;
  162. dst->idct_algo = src->idct_algo;
  163. dst->bits_per_coded_sample = src->bits_per_coded_sample;
  164. dst->sample_aspect_ratio = src->sample_aspect_ratio;
  165. dst->dtg_active_format = src->dtg_active_format;
  166. dst->profile = src->profile;
  167. dst->level = src->level;
  168. dst->bits_per_raw_sample = src->bits_per_raw_sample;
  169. dst->ticks_per_frame = src->ticks_per_frame;
  170. dst->color_primaries = src->color_primaries;
  171. dst->color_trc = src->color_trc;
  172. dst->colorspace = src->colorspace;
  173. dst->color_range = src->color_range;
  174. dst->chroma_sample_location = src->chroma_sample_location;
  175. dst->hwaccel = src->hwaccel;
  176. dst->hwaccel_context = src->hwaccel_context;
  177. dst->channels = src->channels;
  178. dst->sample_rate = src->sample_rate;
  179. dst->sample_fmt = src->sample_fmt;
  180. dst->channel_layout = src->channel_layout;
  181. }
  182. if (for_user) {
  183. dst->delay = src->thread_count - 1;
  184. dst->coded_frame = src->coded_frame;
  185. } else {
  186. if (dst->codec->update_thread_context)
  187. err = dst->codec->update_thread_context(dst, src);
  188. }
  189. return err;
  190. }
  191. /**
  192. * Update the next thread's AVCodecContext with values set by the user.
  193. *
  194. * @param dst The destination context.
  195. * @param src The source context.
  196. * @return 0 on success, negative error code on failure
  197. */
  198. static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
  199. {
  200. #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
  201. dst->flags = src->flags;
  202. dst->draw_horiz_band= src->draw_horiz_band;
  203. dst->get_buffer2 = src->get_buffer2;
  204. #if FF_API_GET_BUFFER
  205. FF_DISABLE_DEPRECATION_WARNINGS
  206. dst->get_buffer = src->get_buffer;
  207. dst->release_buffer = src->release_buffer;
  208. FF_ENABLE_DEPRECATION_WARNINGS
  209. #endif
  210. dst->opaque = src->opaque;
  211. dst->debug = src->debug;
  212. dst->debug_mv = src->debug_mv;
  213. dst->slice_flags = src->slice_flags;
  214. dst->flags2 = src->flags2;
  215. copy_fields(skip_loop_filter, subtitle_header);
  216. dst->frame_number = src->frame_number;
  217. dst->reordered_opaque = src->reordered_opaque;
  218. dst->thread_safe_callbacks = src->thread_safe_callbacks;
  219. if (src->slice_count && src->slice_offset) {
  220. if (dst->slice_count < src->slice_count) {
  221. int *tmp = av_realloc(dst->slice_offset, src->slice_count *
  222. sizeof(*dst->slice_offset));
  223. if (!tmp) {
  224. av_free(dst->slice_offset);
  225. return AVERROR(ENOMEM);
  226. }
  227. dst->slice_offset = tmp;
  228. }
  229. memcpy(dst->slice_offset, src->slice_offset,
  230. src->slice_count * sizeof(*dst->slice_offset));
  231. }
  232. dst->slice_count = src->slice_count;
  233. return 0;
  234. #undef copy_fields
  235. }
  236. /// Releases the buffers that this decoding thread was the last user of.
  237. static void release_delayed_buffers(PerThreadContext *p)
  238. {
  239. FrameThreadContext *fctx = p->parent;
  240. while (p->num_released_buffers > 0) {
  241. AVFrame *f;
  242. pthread_mutex_lock(&fctx->buffer_mutex);
  243. // fix extended data in case the caller screwed it up
  244. av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
  245. p->avctx->codec_type == AVMEDIA_TYPE_AUDIO);
  246. f = &p->released_buffers[--p->num_released_buffers];
  247. f->extended_data = f->data;
  248. av_frame_unref(f);
  249. pthread_mutex_unlock(&fctx->buffer_mutex);
  250. }
  251. }
  252. static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
  253. {
  254. FrameThreadContext *fctx = p->parent;
  255. PerThreadContext *prev_thread = fctx->prev_thread;
  256. const AVCodec *codec = p->avctx->codec;
  257. if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
  258. pthread_mutex_lock(&p->mutex);
  259. release_delayed_buffers(p);
  260. if (prev_thread) {
  261. int err;
  262. if (prev_thread->state == STATE_SETTING_UP) {
  263. pthread_mutex_lock(&prev_thread->progress_mutex);
  264. while (prev_thread->state == STATE_SETTING_UP)
  265. pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
  266. pthread_mutex_unlock(&prev_thread->progress_mutex);
  267. }
  268. err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
  269. if (err) {
  270. pthread_mutex_unlock(&p->mutex);
  271. return err;
  272. }
  273. }
  274. av_buffer_unref(&p->avpkt.buf);
  275. p->avpkt = *avpkt;
  276. if (avpkt->buf)
  277. p->avpkt.buf = av_buffer_ref(avpkt->buf);
  278. else {
  279. av_fast_malloc(&p->buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
  280. if (!p->buf) {
  281. pthread_mutex_unlock(&p->mutex);
  282. return AVERROR(ENOMEM);
  283. }
  284. p->avpkt.data = p->buf;
  285. memcpy(p->buf, avpkt->data, avpkt->size);
  286. memset(p->buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  287. }
  288. p->state = STATE_SETTING_UP;
  289. pthread_cond_signal(&p->input_cond);
  290. pthread_mutex_unlock(&p->mutex);
  291. /*
  292. * If the client doesn't have a thread-safe get_buffer(),
  293. * then decoding threads call back to the main thread,
  294. * and it calls back to the client here.
  295. */
  296. FF_DISABLE_DEPRECATION_WARNINGS
  297. if (!p->avctx->thread_safe_callbacks && (
  298. p->avctx->get_format != avcodec_default_get_format ||
  299. #if FF_API_GET_BUFFER
  300. p->avctx->get_buffer ||
  301. #endif
  302. p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
  303. FF_ENABLE_DEPRECATION_WARNINGS
  304. while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
  305. int call_done = 1;
  306. pthread_mutex_lock(&p->progress_mutex);
  307. while (p->state == STATE_SETTING_UP)
  308. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  309. switch (p->state) {
  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 = p->avctx->get_format(p->avctx, p->available_formats);
  315. break;
  316. default:
  317. call_done = 0;
  318. break;
  319. }
  320. if (call_done) {
  321. 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 (p->state != STATE_INPUT_READY) {
  366. pthread_mutex_lock(&p->progress_mutex);
  367. while (p->state != 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. /*
  375. * A later call with avkpt->size == 0 may loop over all threads,
  376. * including this one, searching for a frame to return before being
  377. * stopped by the "finished != fctx->next_finished" condition.
  378. * Make sure we don't mistakenly return the same frame again.
  379. */
  380. p->got_frame = 0;
  381. if (finished >= avctx->thread_count) finished = 0;
  382. } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
  383. update_context_from_thread(avctx, p->avctx, 1);
  384. if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
  385. fctx->next_finished = finished;
  386. /* return the size of the consumed packet if no error occurred */
  387. return (p->result >= 0) ? avpkt->size : p->result;
  388. }
  389. void ff_thread_report_progress(ThreadFrame *f, int n, int field)
  390. {
  391. PerThreadContext *p;
  392. volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
  393. if (!progress || progress[field] >= n) return;
  394. p = f->owner->internal->thread_ctx;
  395. if (f->owner->debug&FF_DEBUG_THREADS)
  396. av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
  397. pthread_mutex_lock(&p->progress_mutex);
  398. progress[field] = n;
  399. pthread_cond_broadcast(&p->progress_cond);
  400. pthread_mutex_unlock(&p->progress_mutex);
  401. }
  402. void ff_thread_await_progress(ThreadFrame *f, int n, int field)
  403. {
  404. PerThreadContext *p;
  405. volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
  406. if (!progress || progress[field] >= n) return;
  407. p = f->owner->internal->thread_ctx;
  408. if (f->owner->debug&FF_DEBUG_THREADS)
  409. av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
  410. pthread_mutex_lock(&p->progress_mutex);
  411. while (progress[field] < n)
  412. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  413. pthread_mutex_unlock(&p->progress_mutex);
  414. }
  415. void ff_thread_finish_setup(AVCodecContext *avctx) {
  416. PerThreadContext *p = avctx->internal->thread_ctx;
  417. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
  418. if(p->state == STATE_SETUP_FINISHED){
  419. av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
  420. }
  421. pthread_mutex_lock(&p->progress_mutex);
  422. p->state = STATE_SETUP_FINISHED;
  423. pthread_cond_broadcast(&p->progress_cond);
  424. pthread_mutex_unlock(&p->progress_mutex);
  425. }
  426. /// Waits for all threads to finish.
  427. static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
  428. {
  429. int i;
  430. for (i = 0; i < thread_count; i++) {
  431. PerThreadContext *p = &fctx->threads[i];
  432. if (p->state != STATE_INPUT_READY) {
  433. pthread_mutex_lock(&p->progress_mutex);
  434. while (p->state != STATE_INPUT_READY)
  435. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  436. pthread_mutex_unlock(&p->progress_mutex);
  437. }
  438. p->got_frame = 0;
  439. }
  440. }
  441. void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
  442. {
  443. FrameThreadContext *fctx = avctx->internal->thread_ctx;
  444. const AVCodec *codec = avctx->codec;
  445. int i;
  446. park_frame_worker_threads(fctx, thread_count);
  447. if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
  448. if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
  449. av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
  450. fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
  451. fctx->threads->avctx->internal->is_copy = 1;
  452. }
  453. fctx->die = 1;
  454. for (i = 0; i < thread_count; i++) {
  455. PerThreadContext *p = &fctx->threads[i];
  456. pthread_mutex_lock(&p->mutex);
  457. pthread_cond_signal(&p->input_cond);
  458. pthread_mutex_unlock(&p->mutex);
  459. if (p->thread_init)
  460. pthread_join(p->thread, NULL);
  461. p->thread_init=0;
  462. if (codec->close)
  463. codec->close(p->avctx);
  464. avctx->codec = NULL;
  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_buffer_unref(&p->avpkt.buf);
  476. av_freep(&p->buf);
  477. av_freep(&p->released_buffers);
  478. if (i) {
  479. av_freep(&p->avctx->priv_data);
  480. av_freep(&p->avctx->slice_offset);
  481. }
  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. }
  489. int ff_frame_thread_init(AVCodecContext *avctx)
  490. {
  491. int thread_count = avctx->thread_count;
  492. const AVCodec *codec = avctx->codec;
  493. AVCodecContext *src = avctx;
  494. FrameThreadContext *fctx;
  495. int i, err = 0;
  496. #if HAVE_W32THREADS
  497. w32thread_init();
  498. #endif
  499. if (!thread_count) {
  500. int nb_cpus = av_cpu_count();
  501. if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
  502. nb_cpus = 1;
  503. // use number of cores + 1 as thread count if there is more than one
  504. if (nb_cpus > 1)
  505. thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
  506. else
  507. thread_count = avctx->thread_count = 1;
  508. }
  509. if (thread_count <= 1) {
  510. avctx->active_thread_type = 0;
  511. return 0;
  512. }
  513. avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
  514. fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
  515. pthread_mutex_init(&fctx->buffer_mutex, NULL);
  516. fctx->delaying = 1;
  517. for (i = 0; i < thread_count; i++) {
  518. AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
  519. PerThreadContext *p = &fctx->threads[i];
  520. pthread_mutex_init(&p->mutex, NULL);
  521. pthread_mutex_init(&p->progress_mutex, NULL);
  522. pthread_cond_init(&p->input_cond, NULL);
  523. pthread_cond_init(&p->progress_cond, NULL);
  524. pthread_cond_init(&p->output_cond, NULL);
  525. p->frame = av_frame_alloc();
  526. if (!p->frame) {
  527. err = AVERROR(ENOMEM);
  528. goto error;
  529. }
  530. p->parent = fctx;
  531. p->avctx = copy;
  532. if (!copy) {
  533. err = AVERROR(ENOMEM);
  534. goto error;
  535. }
  536. *copy = *src;
  537. copy->internal = av_malloc(sizeof(AVCodecInternal));
  538. if (!copy->internal) {
  539. err = AVERROR(ENOMEM);
  540. goto error;
  541. }
  542. *copy->internal = *src->internal;
  543. copy->internal->thread_ctx = p;
  544. copy->internal->pkt = &p->avpkt;
  545. if (!i) {
  546. src = copy;
  547. if (codec->init)
  548. err = codec->init(copy);
  549. update_context_from_thread(avctx, copy, 1);
  550. } else {
  551. copy->priv_data = av_malloc(codec->priv_data_size);
  552. if (!copy->priv_data) {
  553. err = AVERROR(ENOMEM);
  554. goto error;
  555. }
  556. memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
  557. copy->internal->is_copy = 1;
  558. if (codec->init_thread_copy)
  559. err = codec->init_thread_copy(copy);
  560. }
  561. if (err) goto error;
  562. err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
  563. p->thread_init= !err;
  564. if(!p->thread_init)
  565. goto error;
  566. }
  567. return 0;
  568. error:
  569. ff_frame_thread_free(avctx, i+1);
  570. return err;
  571. }
  572. void ff_thread_flush(AVCodecContext *avctx)
  573. {
  574. int i;
  575. FrameThreadContext *fctx = avctx->internal->thread_ctx;
  576. if (!fctx) return;
  577. park_frame_worker_threads(fctx, avctx->thread_count);
  578. if (fctx->prev_thread) {
  579. if (fctx->prev_thread != &fctx->threads[0])
  580. update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
  581. if (avctx->codec->flush)
  582. avctx->codec->flush(fctx->threads[0].avctx);
  583. }
  584. fctx->next_decoding = fctx->next_finished = 0;
  585. fctx->delaying = 1;
  586. fctx->prev_thread = NULL;
  587. for (i = 0; i < avctx->thread_count; i++) {
  588. PerThreadContext *p = &fctx->threads[i];
  589. // Make sure decode flush calls with size=0 won't return old frames
  590. p->got_frame = 0;
  591. av_frame_unref(p->frame);
  592. release_delayed_buffers(p);
  593. }
  594. }
  595. int ff_thread_can_start_frame(AVCodecContext *avctx)
  596. {
  597. PerThreadContext *p = avctx->internal->thread_ctx;
  598. if ((avctx->active_thread_type&FF_THREAD_FRAME) && p->state != STATE_SETTING_UP &&
  599. (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
  600. return 0;
  601. }
  602. return 1;
  603. }
  604. static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
  605. {
  606. PerThreadContext *p = avctx->internal->thread_ctx;
  607. int err;
  608. f->owner = avctx;
  609. ff_init_buffer_info(avctx, f->f);
  610. if (!(avctx->active_thread_type & FF_THREAD_FRAME))
  611. return ff_get_buffer(avctx, f->f, flags);
  612. if (p->state != STATE_SETTING_UP &&
  613. (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
  614. av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
  615. return -1;
  616. }
  617. if (avctx->internal->allocate_progress) {
  618. int *progress;
  619. f->progress = av_buffer_alloc(2 * sizeof(int));
  620. if (!f->progress) {
  621. return AVERROR(ENOMEM);
  622. }
  623. progress = (int*)f->progress->data;
  624. progress[0] = progress[1] = -1;
  625. }
  626. pthread_mutex_lock(&p->parent->buffer_mutex);
  627. FF_DISABLE_DEPRECATION_WARNINGS
  628. if (avctx->thread_safe_callbacks || (
  629. #if FF_API_GET_BUFFER
  630. !avctx->get_buffer &&
  631. #endif
  632. avctx->get_buffer2 == avcodec_default_get_buffer2)) {
  633. FF_ENABLE_DEPRECATION_WARNINGS
  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 avctx->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. FF_DISABLE_DEPRECATION_WARNINGS
  687. int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
  688. avctx->thread_safe_callbacks ||
  689. (
  690. #if FF_API_GET_BUFFER
  691. !avctx->get_buffer &&
  692. #endif
  693. avctx->get_buffer2 == avcodec_default_get_buffer2);
  694. FF_ENABLE_DEPRECATION_WARNINGS
  695. if (!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. }