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.

890 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. avcodec_get_frame_defaults(&p->frame);
  125. p->got_frame = 0;
  126. p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
  127. /* many decoders assign whole AVFrames, thus overwriting extended_data;
  128. * make sure it's set correctly */
  129. p->frame.extended_data = p->frame.data;
  130. if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
  131. pthread_mutex_lock(&p->progress_mutex);
  132. #if 0 //BUFREF-FIXME
  133. for (i = 0; i < MAX_BUFFERS; i++)
  134. if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != AV_CODEC_ID_H264)) {
  135. p->progress[i][0] = INT_MAX;
  136. p->progress[i][1] = INT_MAX;
  137. }
  138. #endif
  139. p->state = STATE_INPUT_READY;
  140. pthread_cond_broadcast(&p->progress_cond);
  141. pthread_cond_signal(&p->output_cond);
  142. pthread_mutex_unlock(&p->progress_mutex);
  143. }
  144. pthread_mutex_unlock(&p->mutex);
  145. return NULL;
  146. }
  147. /**
  148. * Update the next thread's AVCodecContext with values from the reference thread's context.
  149. *
  150. * @param dst The destination context.
  151. * @param src The source context.
  152. * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
  153. */
  154. static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
  155. {
  156. int err = 0;
  157. if (dst != src) {
  158. dst->time_base = src->time_base;
  159. dst->width = src->width;
  160. dst->height = src->height;
  161. dst->pix_fmt = src->pix_fmt;
  162. dst->coded_width = src->coded_width;
  163. dst->coded_height = src->coded_height;
  164. dst->has_b_frames = src->has_b_frames;
  165. dst->idct_algo = src->idct_algo;
  166. dst->bits_per_coded_sample = src->bits_per_coded_sample;
  167. dst->sample_aspect_ratio = src->sample_aspect_ratio;
  168. dst->dtg_active_format = src->dtg_active_format;
  169. dst->profile = src->profile;
  170. dst->level = src->level;
  171. dst->bits_per_raw_sample = src->bits_per_raw_sample;
  172. dst->ticks_per_frame = src->ticks_per_frame;
  173. dst->color_primaries = src->color_primaries;
  174. dst->color_trc = src->color_trc;
  175. dst->colorspace = src->colorspace;
  176. dst->color_range = src->color_range;
  177. dst->chroma_sample_location = src->chroma_sample_location;
  178. dst->hwaccel = src->hwaccel;
  179. dst->hwaccel_context = src->hwaccel_context;
  180. dst->channels = src->channels;
  181. dst->sample_rate = src->sample_rate;
  182. dst->sample_fmt = src->sample_fmt;
  183. dst->channel_layout = src->channel_layout;
  184. }
  185. if (for_user) {
  186. dst->delay = src->thread_count - 1;
  187. dst->coded_frame = src->coded_frame;
  188. } else {
  189. if (dst->codec->update_thread_context)
  190. err = dst->codec->update_thread_context(dst, src);
  191. }
  192. return err;
  193. }
  194. /**
  195. * Update the next thread's AVCodecContext with values set by the user.
  196. *
  197. * @param dst The destination context.
  198. * @param src The source context.
  199. * @return 0 on success, negative error code on failure
  200. */
  201. static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
  202. {
  203. #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
  204. dst->flags = src->flags;
  205. dst->draw_horiz_band= src->draw_horiz_band;
  206. dst->get_buffer2 = src->get_buffer2;
  207. #if FF_API_GET_BUFFER
  208. FF_DISABLE_DEPRECATION_WARNINGS
  209. dst->get_buffer = src->get_buffer;
  210. dst->release_buffer = src->release_buffer;
  211. FF_ENABLE_DEPRECATION_WARNINGS
  212. #endif
  213. dst->opaque = src->opaque;
  214. dst->debug = src->debug;
  215. dst->debug_mv = src->debug_mv;
  216. dst->slice_flags = src->slice_flags;
  217. dst->flags2 = src->flags2;
  218. copy_fields(skip_loop_filter, subtitle_header);
  219. dst->frame_number = src->frame_number;
  220. dst->reordered_opaque = src->reordered_opaque;
  221. dst->thread_safe_callbacks = src->thread_safe_callbacks;
  222. if (src->slice_count && src->slice_offset) {
  223. if (dst->slice_count < src->slice_count) {
  224. int *tmp = av_realloc(dst->slice_offset, src->slice_count *
  225. sizeof(*dst->slice_offset));
  226. if (!tmp) {
  227. av_free(dst->slice_offset);
  228. return AVERROR(ENOMEM);
  229. }
  230. dst->slice_offset = tmp;
  231. }
  232. memcpy(dst->slice_offset, src->slice_offset,
  233. src->slice_count * sizeof(*dst->slice_offset));
  234. }
  235. dst->slice_count = src->slice_count;
  236. return 0;
  237. #undef copy_fields
  238. }
  239. /// Releases the buffers that this decoding thread was the last user of.
  240. static void release_delayed_buffers(PerThreadContext *p)
  241. {
  242. FrameThreadContext *fctx = p->parent;
  243. while (p->num_released_buffers > 0) {
  244. AVFrame *f;
  245. pthread_mutex_lock(&fctx->buffer_mutex);
  246. // fix extended data in case the caller screwed it up
  247. av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
  248. p->avctx->codec_type == AVMEDIA_TYPE_AUDIO);
  249. f = &p->released_buffers[--p->num_released_buffers];
  250. f->extended_data = f->data;
  251. av_frame_unref(f);
  252. pthread_mutex_unlock(&fctx->buffer_mutex);
  253. }
  254. }
  255. static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
  256. {
  257. FrameThreadContext *fctx = p->parent;
  258. PerThreadContext *prev_thread = fctx->prev_thread;
  259. const AVCodec *codec = p->avctx->codec;
  260. if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) 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_buffer_unref(&p->avpkt.buf);
  278. p->avpkt = *avpkt;
  279. if (avpkt->buf)
  280. p->avpkt.buf = av_buffer_ref(avpkt->buf);
  281. else {
  282. av_fast_malloc(&p->buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
  283. p->avpkt.data = p->buf;
  284. memcpy(p->buf, avpkt->data, avpkt->size);
  285. memset(p->buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  286. }
  287. p->state = STATE_SETTING_UP;
  288. pthread_cond_signal(&p->input_cond);
  289. pthread_mutex_unlock(&p->mutex);
  290. /*
  291. * If the client doesn't have a thread-safe get_buffer(),
  292. * then decoding threads call back to the main thread,
  293. * and it calls back to the client here.
  294. */
  295. FF_DISABLE_DEPRECATION_WARNINGS
  296. if (!p->avctx->thread_safe_callbacks && (
  297. p->avctx->get_format != avcodec_default_get_format ||
  298. #if FF_API_GET_BUFFER
  299. p->avctx->get_buffer ||
  300. #endif
  301. p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
  302. FF_ENABLE_DEPRECATION_WARNINGS
  303. while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
  304. int call_done = 1;
  305. pthread_mutex_lock(&p->progress_mutex);
  306. while (p->state == STATE_SETTING_UP)
  307. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  308. switch (p->state) {
  309. case STATE_GET_BUFFER:
  310. p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
  311. break;
  312. case STATE_GET_FORMAT:
  313. p->result_format = p->avctx->get_format(p->avctx, p->available_formats);
  314. break;
  315. default:
  316. call_done = 0;
  317. break;
  318. }
  319. if (call_done) {
  320. p->state = STATE_SETTING_UP;
  321. pthread_cond_signal(&p->progress_cond);
  322. }
  323. pthread_mutex_unlock(&p->progress_mutex);
  324. }
  325. }
  326. fctx->prev_thread = p;
  327. fctx->next_decoding++;
  328. return 0;
  329. }
  330. int ff_thread_decode_frame(AVCodecContext *avctx,
  331. AVFrame *picture, int *got_picture_ptr,
  332. AVPacket *avpkt)
  333. {
  334. FrameThreadContext *fctx = avctx->internal->thread_ctx;
  335. int finished = fctx->next_finished;
  336. PerThreadContext *p;
  337. int err;
  338. /*
  339. * Submit a packet to the next decoding thread.
  340. */
  341. p = &fctx->threads[fctx->next_decoding];
  342. err = update_context_from_user(p->avctx, avctx);
  343. if (err) return err;
  344. err = submit_packet(p, avpkt);
  345. if (err) return err;
  346. /*
  347. * If we're still receiving the initial packets, don't return a frame.
  348. */
  349. if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
  350. fctx->delaying = 0;
  351. if (fctx->delaying) {
  352. *got_picture_ptr=0;
  353. if (avpkt->size)
  354. return avpkt->size;
  355. }
  356. /*
  357. * Return the next available frame from the oldest thread.
  358. * If we're at the end of the stream, then we have to skip threads that
  359. * didn't output a frame, because we don't want to accidentally signal
  360. * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
  361. */
  362. do {
  363. p = &fctx->threads[finished++];
  364. if (p->state != STATE_INPUT_READY) {
  365. pthread_mutex_lock(&p->progress_mutex);
  366. while (p->state != STATE_INPUT_READY)
  367. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  368. pthread_mutex_unlock(&p->progress_mutex);
  369. }
  370. av_frame_move_ref(picture, &p->frame);
  371. *got_picture_ptr = p->got_frame;
  372. picture->pkt_dts = p->avpkt.dts;
  373. /*
  374. * A later call with avkpt->size == 0 may loop over all threads,
  375. * including this one, searching for a frame to return before being
  376. * stopped by the "finished != fctx->next_finished" condition.
  377. * Make sure we don't mistakenly return the same frame again.
  378. */
  379. p->got_frame = 0;
  380. if (finished >= avctx->thread_count) finished = 0;
  381. } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
  382. update_context_from_thread(avctx, p->avctx, 1);
  383. if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
  384. fctx->next_finished = finished;
  385. /* return the size of the consumed packet if no error occurred */
  386. return (p->result >= 0) ? avpkt->size : p->result;
  387. }
  388. void ff_thread_report_progress(ThreadFrame *f, int n, int field)
  389. {
  390. PerThreadContext *p;
  391. volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
  392. if (!progress || progress[field] >= n) return;
  393. p = f->owner->internal->thread_ctx;
  394. if (f->owner->debug&FF_DEBUG_THREADS)
  395. av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
  396. pthread_mutex_lock(&p->progress_mutex);
  397. progress[field] = n;
  398. pthread_cond_broadcast(&p->progress_cond);
  399. pthread_mutex_unlock(&p->progress_mutex);
  400. }
  401. void ff_thread_await_progress(ThreadFrame *f, int n, int field)
  402. {
  403. PerThreadContext *p;
  404. volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
  405. if (!progress || progress[field] >= n) return;
  406. p = f->owner->internal->thread_ctx;
  407. if (f->owner->debug&FF_DEBUG_THREADS)
  408. av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
  409. pthread_mutex_lock(&p->progress_mutex);
  410. while (progress[field] < n)
  411. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  412. pthread_mutex_unlock(&p->progress_mutex);
  413. }
  414. void ff_thread_finish_setup(AVCodecContext *avctx) {
  415. PerThreadContext *p = avctx->internal->thread_ctx;
  416. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
  417. if(p->state == STATE_SETUP_FINISHED){
  418. av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
  419. }
  420. pthread_mutex_lock(&p->progress_mutex);
  421. p->state = STATE_SETUP_FINISHED;
  422. pthread_cond_broadcast(&p->progress_cond);
  423. pthread_mutex_unlock(&p->progress_mutex);
  424. }
  425. /// Waits for all threads to finish.
  426. static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
  427. {
  428. int i;
  429. for (i = 0; i < thread_count; i++) {
  430. PerThreadContext *p = &fctx->threads[i];
  431. if (p->state != STATE_INPUT_READY) {
  432. pthread_mutex_lock(&p->progress_mutex);
  433. while (p->state != STATE_INPUT_READY)
  434. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  435. pthread_mutex_unlock(&p->progress_mutex);
  436. }
  437. p->got_frame = 0;
  438. }
  439. }
  440. void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
  441. {
  442. FrameThreadContext *fctx = avctx->internal->thread_ctx;
  443. const AVCodec *codec = avctx->codec;
  444. int i;
  445. park_frame_worker_threads(fctx, thread_count);
  446. if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
  447. if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
  448. av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
  449. fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
  450. fctx->threads->avctx->internal->is_copy = 1;
  451. }
  452. fctx->die = 1;
  453. for (i = 0; i < thread_count; i++) {
  454. PerThreadContext *p = &fctx->threads[i];
  455. pthread_mutex_lock(&p->mutex);
  456. pthread_cond_signal(&p->input_cond);
  457. pthread_mutex_unlock(&p->mutex);
  458. if (p->thread_init)
  459. pthread_join(p->thread, NULL);
  460. p->thread_init=0;
  461. if (codec->close)
  462. codec->close(p->avctx);
  463. avctx->codec = NULL;
  464. release_delayed_buffers(p);
  465. av_frame_unref(&p->frame);
  466. }
  467. for (i = 0; i < thread_count; i++) {
  468. PerThreadContext *p = &fctx->threads[i];
  469. pthread_mutex_destroy(&p->mutex);
  470. pthread_mutex_destroy(&p->progress_mutex);
  471. pthread_cond_destroy(&p->input_cond);
  472. pthread_cond_destroy(&p->progress_cond);
  473. pthread_cond_destroy(&p->output_cond);
  474. av_buffer_unref(&p->avpkt.buf);
  475. av_freep(&p->buf);
  476. av_freep(&p->released_buffers);
  477. if (i) {
  478. av_freep(&p->avctx->priv_data);
  479. av_freep(&p->avctx->slice_offset);
  480. }
  481. av_freep(&p->avctx->internal);
  482. av_freep(&p->avctx);
  483. }
  484. av_freep(&fctx->threads);
  485. pthread_mutex_destroy(&fctx->buffer_mutex);
  486. av_freep(&avctx->internal->thread_ctx);
  487. }
  488. int ff_frame_thread_init(AVCodecContext *avctx)
  489. {
  490. int thread_count = avctx->thread_count;
  491. const AVCodec *codec = avctx->codec;
  492. AVCodecContext *src = avctx;
  493. FrameThreadContext *fctx;
  494. int i, err = 0;
  495. #if HAVE_W32THREADS
  496. w32thread_init();
  497. #endif
  498. if (!thread_count) {
  499. int nb_cpus = av_cpu_count();
  500. if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
  501. nb_cpus = 1;
  502. // use number of cores + 1 as thread count if there is more than one
  503. if (nb_cpus > 1)
  504. thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
  505. else
  506. thread_count = avctx->thread_count = 1;
  507. }
  508. if (thread_count <= 1) {
  509. avctx->active_thread_type = 0;
  510. return 0;
  511. }
  512. avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
  513. fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
  514. pthread_mutex_init(&fctx->buffer_mutex, NULL);
  515. fctx->delaying = 1;
  516. for (i = 0; i < thread_count; i++) {
  517. AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
  518. PerThreadContext *p = &fctx->threads[i];
  519. pthread_mutex_init(&p->mutex, NULL);
  520. pthread_mutex_init(&p->progress_mutex, NULL);
  521. pthread_cond_init(&p->input_cond, NULL);
  522. pthread_cond_init(&p->progress_cond, NULL);
  523. pthread_cond_init(&p->output_cond, NULL);
  524. p->parent = fctx;
  525. p->avctx = copy;
  526. if (!copy) {
  527. err = AVERROR(ENOMEM);
  528. goto error;
  529. }
  530. *copy = *src;
  531. copy->pkt = &p->avpkt;
  532. copy->internal = av_malloc(sizeof(AVCodecInternal));
  533. if (!copy->internal) {
  534. err = AVERROR(ENOMEM);
  535. goto error;
  536. }
  537. *copy->internal = *src->internal;
  538. copy->internal->thread_ctx = p;
  539. if (!i) {
  540. src = copy;
  541. if (codec->init)
  542. err = codec->init(copy);
  543. update_context_from_thread(avctx, copy, 1);
  544. } else {
  545. copy->priv_data = av_malloc(codec->priv_data_size);
  546. if (!copy->priv_data) {
  547. err = AVERROR(ENOMEM);
  548. goto error;
  549. }
  550. memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
  551. copy->internal->is_copy = 1;
  552. if (codec->init_thread_copy)
  553. err = codec->init_thread_copy(copy);
  554. }
  555. if (err) goto error;
  556. err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
  557. p->thread_init= !err;
  558. if(!p->thread_init)
  559. goto error;
  560. }
  561. return 0;
  562. error:
  563. ff_frame_thread_free(avctx, i+1);
  564. return err;
  565. }
  566. void ff_thread_flush(AVCodecContext *avctx)
  567. {
  568. int i;
  569. FrameThreadContext *fctx = avctx->internal->thread_ctx;
  570. if (!fctx) return;
  571. park_frame_worker_threads(fctx, avctx->thread_count);
  572. if (fctx->prev_thread) {
  573. if (fctx->prev_thread != &fctx->threads[0])
  574. update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
  575. if (avctx->codec->flush)
  576. avctx->codec->flush(fctx->threads[0].avctx);
  577. }
  578. fctx->next_decoding = fctx->next_finished = 0;
  579. fctx->delaying = 1;
  580. fctx->prev_thread = NULL;
  581. for (i = 0; i < avctx->thread_count; i++) {
  582. PerThreadContext *p = &fctx->threads[i];
  583. // Make sure decode flush calls with size=0 won't return old frames
  584. p->got_frame = 0;
  585. av_frame_unref(&p->frame);
  586. release_delayed_buffers(p);
  587. }
  588. }
  589. int ff_thread_can_start_frame(AVCodecContext *avctx)
  590. {
  591. PerThreadContext *p = avctx->internal->thread_ctx;
  592. if ((avctx->active_thread_type&FF_THREAD_FRAME) && p->state != STATE_SETTING_UP &&
  593. (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
  594. return 0;
  595. }
  596. return 1;
  597. }
  598. static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
  599. {
  600. PerThreadContext *p = avctx->internal->thread_ctx;
  601. int err;
  602. f->owner = avctx;
  603. ff_init_buffer_info(avctx, f->f);
  604. if (!(avctx->active_thread_type & FF_THREAD_FRAME))
  605. return ff_get_buffer(avctx, f->f, flags);
  606. if (p->state != STATE_SETTING_UP &&
  607. (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
  608. av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
  609. return -1;
  610. }
  611. if (avctx->internal->allocate_progress) {
  612. int *progress;
  613. f->progress = av_buffer_alloc(2 * sizeof(int));
  614. if (!f->progress) {
  615. return AVERROR(ENOMEM);
  616. }
  617. progress = (int*)f->progress->data;
  618. progress[0] = progress[1] = -1;
  619. }
  620. pthread_mutex_lock(&p->parent->buffer_mutex);
  621. FF_DISABLE_DEPRECATION_WARNINGS
  622. if (avctx->thread_safe_callbacks || (
  623. #if FF_API_GET_BUFFER
  624. !avctx->get_buffer &&
  625. #endif
  626. avctx->get_buffer2 == avcodec_default_get_buffer2)) {
  627. FF_ENABLE_DEPRECATION_WARNINGS
  628. err = ff_get_buffer(avctx, f->f, flags);
  629. } else {
  630. pthread_mutex_lock(&p->progress_mutex);
  631. p->requested_frame = f->f;
  632. p->requested_flags = flags;
  633. p->state = STATE_GET_BUFFER;
  634. pthread_cond_broadcast(&p->progress_cond);
  635. while (p->state != STATE_SETTING_UP)
  636. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  637. err = p->result;
  638. pthread_mutex_unlock(&p->progress_mutex);
  639. }
  640. if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
  641. ff_thread_finish_setup(avctx);
  642. if (err)
  643. av_buffer_unref(&f->progress);
  644. pthread_mutex_unlock(&p->parent->buffer_mutex);
  645. return err;
  646. }
  647. enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
  648. {
  649. enum AVPixelFormat res;
  650. PerThreadContext *p = avctx->internal->thread_ctx;
  651. if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
  652. avctx->get_format == avcodec_default_get_format)
  653. return avctx->get_format(avctx, fmt);
  654. if (p->state != STATE_SETTING_UP) {
  655. av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
  656. return -1;
  657. }
  658. pthread_mutex_lock(&p->progress_mutex);
  659. p->available_formats = fmt;
  660. p->state = STATE_GET_FORMAT;
  661. pthread_cond_broadcast(&p->progress_cond);
  662. while (p->state != STATE_SETTING_UP)
  663. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  664. res = p->result_format;
  665. pthread_mutex_unlock(&p->progress_mutex);
  666. return res;
  667. }
  668. int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
  669. {
  670. int ret = thread_get_buffer_internal(avctx, f, flags);
  671. if (ret < 0)
  672. av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
  673. return ret;
  674. }
  675. void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
  676. {
  677. PerThreadContext *p = avctx->internal->thread_ctx;
  678. FrameThreadContext *fctx;
  679. AVFrame *dst, *tmp;
  680. FF_DISABLE_DEPRECATION_WARNINGS
  681. int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
  682. avctx->thread_safe_callbacks ||
  683. (
  684. #if FF_API_GET_BUFFER
  685. !avctx->get_buffer &&
  686. #endif
  687. avctx->get_buffer2 == avcodec_default_get_buffer2);
  688. FF_ENABLE_DEPRECATION_WARNINGS
  689. if (!f->f->data[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. }