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