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.

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