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.

903 lines
29KB

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