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.

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