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.

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