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.

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