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.

1129 lines
36KB

  1. /*
  2. * Copyright (c) 2004 Roman Shaposhnik
  3. * Copyright (c) 2008 Alexander Strange (astrange@ithinksw.com)
  4. *
  5. * Many thanks to Steven M. Schultz for providing clever ideas and
  6. * to Michael Niedermayer <michaelni@gmx.at> for writing initial
  7. * implementation.
  8. *
  9. * This file is part of FFmpeg.
  10. *
  11. * FFmpeg is free software; you can redistribute it and/or
  12. * modify it under the terms of the GNU Lesser General Public
  13. * License as published by the Free Software Foundation; either
  14. * version 2.1 of the License, or (at your option) any later version.
  15. *
  16. * FFmpeg is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  19. * Lesser General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Lesser General Public
  22. * License along with FFmpeg; if not, write to the Free Software
  23. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  24. */
  25. /**
  26. * @file
  27. * Multithreading support functions
  28. * @see doc/multithreading.txt
  29. */
  30. #include "config.h"
  31. #include "avcodec.h"
  32. #include "internal.h"
  33. #include "thread.h"
  34. #include "libavutil/avassert.h"
  35. #include "libavutil/common.h"
  36. #include "libavutil/cpu.h"
  37. #include "libavutil/internal.h"
  38. #if HAVE_PTHREADS
  39. #include <pthread.h>
  40. #elif HAVE_W32THREADS
  41. #include "compat/w32pthreads.h"
  42. #elif HAVE_OS2THREADS
  43. #include "compat/os2threads.h"
  44. #endif
  45. typedef int (action_func)(AVCodecContext *c, void *arg);
  46. typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
  47. typedef struct ThreadContext {
  48. pthread_t *workers;
  49. action_func *func;
  50. action_func2 *func2;
  51. void *args;
  52. int *rets;
  53. int rets_count;
  54. int job_count;
  55. int job_size;
  56. pthread_cond_t last_job_cond;
  57. pthread_cond_t current_job_cond;
  58. pthread_mutex_t current_job_lock;
  59. int current_job;
  60. unsigned int current_execute;
  61. int done;
  62. } ThreadContext;
  63. /**
  64. * Context used by codec threads and stored in their AVCodecContext thread_opaque.
  65. */
  66. typedef struct PerThreadContext {
  67. struct FrameThreadContext *parent;
  68. pthread_t thread;
  69. int thread_init;
  70. pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
  71. pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
  72. pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
  73. pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
  74. pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
  75. AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
  76. AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
  77. uint8_t *buf; ///< backup storage for packet data when the input packet is not refcounted
  78. int allocated_buf_size; ///< Size allocated for buf
  79. AVFrame frame; ///< Output frame (for decoding) or input (for encoding).
  80. int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
  81. int result; ///< The result of the last codec decode/encode() call.
  82. enum {
  83. STATE_INPUT_READY, ///< Set when the thread is awaiting a packet.
  84. STATE_SETTING_UP, ///< Set before the codec has called ff_thread_finish_setup().
  85. STATE_GET_BUFFER, /**<
  86. * Set when the codec calls get_buffer().
  87. * State is returned to STATE_SETTING_UP afterwards.
  88. */
  89. STATE_GET_FORMAT, /**<
  90. * Set when the codec calls get_format().
  91. * State is returned to STATE_SETTING_UP afterwards.
  92. */
  93. STATE_SETUP_FINISHED ///< Set after the codec has called ff_thread_finish_setup().
  94. } state;
  95. /**
  96. * Array of frames passed to ff_thread_release_buffer().
  97. * Frames are released after all threads referencing them are finished.
  98. */
  99. AVFrame *released_buffers;
  100. int num_released_buffers;
  101. int released_buffers_allocated;
  102. AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
  103. int requested_flags; ///< flags passed to get_buffer() for requested_frame
  104. const enum AVPixelFormat *available_formats; ///< Format array for get_format()
  105. enum AVPixelFormat result_format; ///< get_format() result
  106. } PerThreadContext;
  107. /**
  108. * Context stored in the client AVCodecContext thread_opaque.
  109. */
  110. typedef struct FrameThreadContext {
  111. PerThreadContext *threads; ///< The contexts for each thread.
  112. PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
  113. pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
  114. int next_decoding; ///< The next context to submit a packet to.
  115. int next_finished; ///< The next context to return output from.
  116. int delaying; /**<
  117. * Set for the first N packets, where N is the number of threads.
  118. * While it is set, ff_thread_en/decode_frame won't return any results.
  119. */
  120. int die; ///< Set when threads should exit.
  121. } FrameThreadContext;
  122. /* H264 slice threading seems to be buggy with more than 16 threads,
  123. * limit the number of threads to 16 for automatic detection */
  124. #define MAX_AUTO_THREADS 16
  125. static void* attribute_align_arg worker(void *v)
  126. {
  127. AVCodecContext *avctx = v;
  128. ThreadContext *c = avctx->thread_opaque;
  129. int our_job = c->job_count;
  130. int last_execute = 0;
  131. int thread_count = avctx->thread_count;
  132. int self_id;
  133. pthread_mutex_lock(&c->current_job_lock);
  134. self_id = c->current_job++;
  135. for (;;){
  136. while (our_job >= c->job_count) {
  137. if (c->current_job == thread_count + c->job_count)
  138. pthread_cond_signal(&c->last_job_cond);
  139. while (last_execute == c->current_execute && !c->done)
  140. pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
  141. last_execute = c->current_execute;
  142. our_job = self_id;
  143. if (c->done) {
  144. pthread_mutex_unlock(&c->current_job_lock);
  145. return NULL;
  146. }
  147. }
  148. pthread_mutex_unlock(&c->current_job_lock);
  149. c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
  150. c->func2(avctx, c->args, our_job, self_id);
  151. pthread_mutex_lock(&c->current_job_lock);
  152. our_job = c->current_job++;
  153. }
  154. }
  155. static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
  156. {
  157. while (c->current_job != thread_count + c->job_count)
  158. pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
  159. pthread_mutex_unlock(&c->current_job_lock);
  160. }
  161. static void thread_free(AVCodecContext *avctx)
  162. {
  163. ThreadContext *c = avctx->thread_opaque;
  164. int i;
  165. pthread_mutex_lock(&c->current_job_lock);
  166. c->done = 1;
  167. pthread_cond_broadcast(&c->current_job_cond);
  168. pthread_mutex_unlock(&c->current_job_lock);
  169. for (i=0; i<avctx->thread_count; i++)
  170. pthread_join(c->workers[i], NULL);
  171. pthread_mutex_destroy(&c->current_job_lock);
  172. pthread_cond_destroy(&c->current_job_cond);
  173. pthread_cond_destroy(&c->last_job_cond);
  174. av_free(c->workers);
  175. av_freep(&avctx->thread_opaque);
  176. }
  177. static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
  178. {
  179. ThreadContext *c= avctx->thread_opaque;
  180. int dummy_ret;
  181. if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
  182. return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
  183. if (job_count <= 0)
  184. return 0;
  185. pthread_mutex_lock(&c->current_job_lock);
  186. c->current_job = avctx->thread_count;
  187. c->job_count = job_count;
  188. c->job_size = job_size;
  189. c->args = arg;
  190. c->func = func;
  191. if (ret) {
  192. c->rets = ret;
  193. c->rets_count = job_count;
  194. } else {
  195. c->rets = &dummy_ret;
  196. c->rets_count = 1;
  197. }
  198. c->current_execute++;
  199. pthread_cond_broadcast(&c->current_job_cond);
  200. avcodec_thread_park_workers(c, avctx->thread_count);
  201. return 0;
  202. }
  203. static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
  204. {
  205. ThreadContext *c= avctx->thread_opaque;
  206. c->func2 = func2;
  207. return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
  208. }
  209. static int thread_init_internal(AVCodecContext *avctx)
  210. {
  211. int i;
  212. ThreadContext *c;
  213. int thread_count = avctx->thread_count;
  214. if (!thread_count) {
  215. int nb_cpus = av_cpu_count();
  216. if (avctx->height)
  217. nb_cpus = FFMIN(nb_cpus, (avctx->height+15)/16);
  218. // use number of cores + 1 as thread count if there is more than one
  219. if (nb_cpus > 1)
  220. thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
  221. else
  222. thread_count = avctx->thread_count = 1;
  223. }
  224. if (thread_count <= 1) {
  225. avctx->active_thread_type = 0;
  226. return 0;
  227. }
  228. c = av_mallocz(sizeof(ThreadContext));
  229. if (!c)
  230. return -1;
  231. c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
  232. if (!c->workers) {
  233. av_free(c);
  234. return -1;
  235. }
  236. avctx->thread_opaque = c;
  237. c->current_job = 0;
  238. c->job_count = 0;
  239. c->job_size = 0;
  240. c->done = 0;
  241. pthread_cond_init(&c->current_job_cond, NULL);
  242. pthread_cond_init(&c->last_job_cond, NULL);
  243. pthread_mutex_init(&c->current_job_lock, NULL);
  244. pthread_mutex_lock(&c->current_job_lock);
  245. for (i=0; i<thread_count; i++) {
  246. if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
  247. avctx->thread_count = i;
  248. pthread_mutex_unlock(&c->current_job_lock);
  249. ff_thread_free(avctx);
  250. return -1;
  251. }
  252. }
  253. avcodec_thread_park_workers(c, thread_count);
  254. avctx->execute = avcodec_thread_execute;
  255. avctx->execute2 = avcodec_thread_execute2;
  256. return 0;
  257. }
  258. #define THREAD_SAFE_CALLBACKS(avctx) \
  259. ((avctx)->thread_safe_callbacks || (!(avctx)->get_buffer && (avctx)->get_buffer2 == avcodec_default_get_buffer2))
  260. /**
  261. * Codec worker thread.
  262. *
  263. * Automatically calls ff_thread_finish_setup() if the codec does
  264. * not provide an update_thread_context method, or if the codec returns
  265. * before calling it.
  266. */
  267. static attribute_align_arg void *frame_worker_thread(void *arg)
  268. {
  269. PerThreadContext *p = arg;
  270. FrameThreadContext *fctx = p->parent;
  271. AVCodecContext *avctx = p->avctx;
  272. const AVCodec *codec = avctx->codec;
  273. pthread_mutex_lock(&p->mutex);
  274. while (1) {
  275. while (p->state == STATE_INPUT_READY && !fctx->die)
  276. pthread_cond_wait(&p->input_cond, &p->mutex);
  277. if (fctx->die) break;
  278. if (!codec->update_thread_context && THREAD_SAFE_CALLBACKS(avctx))
  279. ff_thread_finish_setup(avctx);
  280. avcodec_get_frame_defaults(&p->frame);
  281. p->got_frame = 0;
  282. p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
  283. /* many decoders assign whole AVFrames, thus overwriting extended_data;
  284. * make sure it's set correctly */
  285. p->frame.extended_data = p->frame.data;
  286. if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
  287. pthread_mutex_lock(&p->progress_mutex);
  288. #if 0 //BUFREF-FIXME
  289. for (i = 0; i < MAX_BUFFERS; i++)
  290. if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != AV_CODEC_ID_H264)) {
  291. p->progress[i][0] = INT_MAX;
  292. p->progress[i][1] = INT_MAX;
  293. }
  294. #endif
  295. p->state = STATE_INPUT_READY;
  296. pthread_cond_broadcast(&p->progress_cond);
  297. pthread_cond_signal(&p->output_cond);
  298. pthread_mutex_unlock(&p->progress_mutex);
  299. }
  300. pthread_mutex_unlock(&p->mutex);
  301. return NULL;
  302. }
  303. /**
  304. * Update the next thread's AVCodecContext with values from the reference thread's context.
  305. *
  306. * @param dst The destination context.
  307. * @param src The source context.
  308. * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
  309. */
  310. static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
  311. {
  312. int err = 0;
  313. if (dst != src) {
  314. dst->time_base = src->time_base;
  315. dst->width = src->width;
  316. dst->height = src->height;
  317. dst->pix_fmt = src->pix_fmt;
  318. dst->coded_width = src->coded_width;
  319. dst->coded_height = src->coded_height;
  320. dst->has_b_frames = src->has_b_frames;
  321. dst->idct_algo = src->idct_algo;
  322. dst->bits_per_coded_sample = src->bits_per_coded_sample;
  323. dst->sample_aspect_ratio = src->sample_aspect_ratio;
  324. dst->dtg_active_format = src->dtg_active_format;
  325. dst->profile = src->profile;
  326. dst->level = src->level;
  327. dst->bits_per_raw_sample = src->bits_per_raw_sample;
  328. dst->ticks_per_frame = src->ticks_per_frame;
  329. dst->color_primaries = src->color_primaries;
  330. dst->color_trc = src->color_trc;
  331. dst->colorspace = src->colorspace;
  332. dst->color_range = src->color_range;
  333. dst->chroma_sample_location = src->chroma_sample_location;
  334. dst->hwaccel = src->hwaccel;
  335. dst->hwaccel_context = src->hwaccel_context;
  336. dst->channels = src->channels;
  337. dst->sample_rate = src->sample_rate;
  338. dst->sample_fmt = src->sample_fmt;
  339. dst->channel_layout = src->channel_layout;
  340. }
  341. if (for_user) {
  342. dst->delay = src->thread_count - 1;
  343. dst->coded_frame = src->coded_frame;
  344. } else {
  345. if (dst->codec->update_thread_context)
  346. err = dst->codec->update_thread_context(dst, src);
  347. }
  348. return err;
  349. }
  350. /**
  351. * Update the next thread's AVCodecContext with values set by the user.
  352. *
  353. * @param dst The destination context.
  354. * @param src The source context.
  355. * @return 0 on success, negative error code on failure
  356. */
  357. static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
  358. {
  359. #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
  360. dst->flags = src->flags;
  361. dst->draw_horiz_band= src->draw_horiz_band;
  362. dst->get_buffer2 = src->get_buffer2;
  363. #if FF_API_GET_BUFFER
  364. FF_DISABLE_DEPRECATION_WARNINGS
  365. dst->get_buffer = src->get_buffer;
  366. dst->release_buffer = src->release_buffer;
  367. FF_ENABLE_DEPRECATION_WARNINGS
  368. #endif
  369. dst->opaque = src->opaque;
  370. dst->debug = src->debug;
  371. dst->debug_mv = src->debug_mv;
  372. dst->slice_flags = src->slice_flags;
  373. dst->flags2 = src->flags2;
  374. copy_fields(skip_loop_filter, subtitle_header);
  375. dst->frame_number = src->frame_number;
  376. dst->reordered_opaque = src->reordered_opaque;
  377. dst->thread_safe_callbacks = src->thread_safe_callbacks;
  378. if (src->slice_count && src->slice_offset) {
  379. if (dst->slice_count < src->slice_count) {
  380. int *tmp = av_realloc(dst->slice_offset, src->slice_count *
  381. sizeof(*dst->slice_offset));
  382. if (!tmp) {
  383. av_free(dst->slice_offset);
  384. return AVERROR(ENOMEM);
  385. }
  386. dst->slice_offset = tmp;
  387. }
  388. memcpy(dst->slice_offset, src->slice_offset,
  389. src->slice_count * sizeof(*dst->slice_offset));
  390. }
  391. dst->slice_count = src->slice_count;
  392. return 0;
  393. #undef copy_fields
  394. }
  395. /// Releases the buffers that this decoding thread was the last user of.
  396. static void release_delayed_buffers(PerThreadContext *p)
  397. {
  398. FrameThreadContext *fctx = p->parent;
  399. while (p->num_released_buffers > 0) {
  400. AVFrame *f;
  401. pthread_mutex_lock(&fctx->buffer_mutex);
  402. // fix extended data in case the caller screwed it up
  403. av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
  404. p->avctx->codec_type == AVMEDIA_TYPE_AUDIO);
  405. f = &p->released_buffers[--p->num_released_buffers];
  406. f->extended_data = f->data;
  407. av_frame_unref(f);
  408. pthread_mutex_unlock(&fctx->buffer_mutex);
  409. }
  410. }
  411. static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
  412. {
  413. FrameThreadContext *fctx = p->parent;
  414. PerThreadContext *prev_thread = fctx->prev_thread;
  415. const AVCodec *codec = p->avctx->codec;
  416. if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
  417. pthread_mutex_lock(&p->mutex);
  418. release_delayed_buffers(p);
  419. if (prev_thread) {
  420. int err;
  421. if (prev_thread->state == STATE_SETTING_UP) {
  422. pthread_mutex_lock(&prev_thread->progress_mutex);
  423. while (prev_thread->state == STATE_SETTING_UP)
  424. pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
  425. pthread_mutex_unlock(&prev_thread->progress_mutex);
  426. }
  427. err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
  428. if (err) {
  429. pthread_mutex_unlock(&p->mutex);
  430. return err;
  431. }
  432. }
  433. av_buffer_unref(&p->avpkt.buf);
  434. p->avpkt = *avpkt;
  435. if (avpkt->buf)
  436. p->avpkt.buf = av_buffer_ref(avpkt->buf);
  437. else {
  438. av_fast_malloc(&p->buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
  439. p->avpkt.data = p->buf;
  440. memcpy(p->buf, avpkt->data, avpkt->size);
  441. memset(p->buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  442. }
  443. p->state = STATE_SETTING_UP;
  444. pthread_cond_signal(&p->input_cond);
  445. pthread_mutex_unlock(&p->mutex);
  446. /*
  447. * If the client doesn't have a thread-safe get_buffer(),
  448. * then decoding threads call back to the main thread,
  449. * and it calls back to the client here.
  450. */
  451. FF_DISABLE_DEPRECATION_WARNINGS
  452. if (!p->avctx->thread_safe_callbacks && (
  453. p->avctx->get_format != avcodec_default_get_format ||
  454. #if FF_API_GET_BUFFER
  455. p->avctx->get_buffer ||
  456. #endif
  457. p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
  458. FF_ENABLE_DEPRECATION_WARNINGS
  459. while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
  460. int call_done = 1;
  461. pthread_mutex_lock(&p->progress_mutex);
  462. while (p->state == STATE_SETTING_UP)
  463. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  464. switch (p->state) {
  465. case STATE_GET_BUFFER:
  466. p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
  467. break;
  468. case STATE_GET_FORMAT:
  469. p->result_format = p->avctx->get_format(p->avctx, p->available_formats);
  470. break;
  471. default:
  472. call_done = 0;
  473. break;
  474. }
  475. if (call_done) {
  476. p->state = STATE_SETTING_UP;
  477. pthread_cond_signal(&p->progress_cond);
  478. }
  479. pthread_mutex_unlock(&p->progress_mutex);
  480. }
  481. }
  482. fctx->prev_thread = p;
  483. fctx->next_decoding++;
  484. return 0;
  485. }
  486. int ff_thread_decode_frame(AVCodecContext *avctx,
  487. AVFrame *picture, int *got_picture_ptr,
  488. AVPacket *avpkt)
  489. {
  490. FrameThreadContext *fctx = avctx->thread_opaque;
  491. int finished = fctx->next_finished;
  492. PerThreadContext *p;
  493. int err;
  494. /*
  495. * Submit a packet to the next decoding thread.
  496. */
  497. p = &fctx->threads[fctx->next_decoding];
  498. err = update_context_from_user(p->avctx, avctx);
  499. if (err) return err;
  500. err = submit_packet(p, avpkt);
  501. if (err) return err;
  502. /*
  503. * If we're still receiving the initial packets, don't return a frame.
  504. */
  505. if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
  506. fctx->delaying = 0;
  507. if (fctx->delaying) {
  508. *got_picture_ptr=0;
  509. if (avpkt->size)
  510. return avpkt->size;
  511. }
  512. /*
  513. * Return the next available frame from the oldest thread.
  514. * If we're at the end of the stream, then we have to skip threads that
  515. * didn't output a frame, because we don't want to accidentally signal
  516. * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
  517. */
  518. do {
  519. p = &fctx->threads[finished++];
  520. if (p->state != STATE_INPUT_READY) {
  521. pthread_mutex_lock(&p->progress_mutex);
  522. while (p->state != STATE_INPUT_READY)
  523. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  524. pthread_mutex_unlock(&p->progress_mutex);
  525. }
  526. av_frame_move_ref(picture, &p->frame);
  527. *got_picture_ptr = p->got_frame;
  528. picture->pkt_dts = p->avpkt.dts;
  529. /*
  530. * A later call with avkpt->size == 0 may loop over all threads,
  531. * including this one, searching for a frame to return before being
  532. * stopped by the "finished != fctx->next_finished" condition.
  533. * Make sure we don't mistakenly return the same frame again.
  534. */
  535. p->got_frame = 0;
  536. if (finished >= avctx->thread_count) finished = 0;
  537. } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
  538. update_context_from_thread(avctx, p->avctx, 1);
  539. if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
  540. fctx->next_finished = finished;
  541. /* return the size of the consumed packet if no error occurred */
  542. return (p->result >= 0) ? avpkt->size : p->result;
  543. }
  544. void ff_thread_report_progress(ThreadFrame *f, int n, int field)
  545. {
  546. PerThreadContext *p;
  547. volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
  548. if (!progress || progress[field] >= n) return;
  549. p = f->owner->thread_opaque;
  550. if (f->owner->debug&FF_DEBUG_THREADS)
  551. av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
  552. pthread_mutex_lock(&p->progress_mutex);
  553. progress[field] = n;
  554. pthread_cond_broadcast(&p->progress_cond);
  555. pthread_mutex_unlock(&p->progress_mutex);
  556. }
  557. void ff_thread_await_progress(ThreadFrame *f, int n, int field)
  558. {
  559. PerThreadContext *p;
  560. volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
  561. if (!progress || progress[field] >= n) return;
  562. p = f->owner->thread_opaque;
  563. if (f->owner->debug&FF_DEBUG_THREADS)
  564. av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
  565. pthread_mutex_lock(&p->progress_mutex);
  566. while (progress[field] < n)
  567. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  568. pthread_mutex_unlock(&p->progress_mutex);
  569. }
  570. void ff_thread_finish_setup(AVCodecContext *avctx) {
  571. PerThreadContext *p = avctx->thread_opaque;
  572. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
  573. if(p->state == STATE_SETUP_FINISHED){
  574. av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
  575. }
  576. pthread_mutex_lock(&p->progress_mutex);
  577. p->state = STATE_SETUP_FINISHED;
  578. pthread_cond_broadcast(&p->progress_cond);
  579. pthread_mutex_unlock(&p->progress_mutex);
  580. }
  581. /// Waits for all threads to finish.
  582. static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
  583. {
  584. int i;
  585. for (i = 0; i < thread_count; i++) {
  586. PerThreadContext *p = &fctx->threads[i];
  587. if (p->state != STATE_INPUT_READY) {
  588. pthread_mutex_lock(&p->progress_mutex);
  589. while (p->state != STATE_INPUT_READY)
  590. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  591. pthread_mutex_unlock(&p->progress_mutex);
  592. }
  593. p->got_frame = 0;
  594. }
  595. }
  596. static void frame_thread_free(AVCodecContext *avctx, int thread_count)
  597. {
  598. FrameThreadContext *fctx = avctx->thread_opaque;
  599. const AVCodec *codec = avctx->codec;
  600. int i;
  601. park_frame_worker_threads(fctx, thread_count);
  602. if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
  603. if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
  604. av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
  605. fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
  606. fctx->threads->avctx->internal->is_copy = 1;
  607. }
  608. fctx->die = 1;
  609. for (i = 0; i < thread_count; i++) {
  610. PerThreadContext *p = &fctx->threads[i];
  611. pthread_mutex_lock(&p->mutex);
  612. pthread_cond_signal(&p->input_cond);
  613. pthread_mutex_unlock(&p->mutex);
  614. if (p->thread_init)
  615. pthread_join(p->thread, NULL);
  616. p->thread_init=0;
  617. if (codec->close)
  618. codec->close(p->avctx);
  619. avctx->codec = NULL;
  620. release_delayed_buffers(p);
  621. av_frame_unref(&p->frame);
  622. }
  623. for (i = 0; i < thread_count; i++) {
  624. PerThreadContext *p = &fctx->threads[i];
  625. pthread_mutex_destroy(&p->mutex);
  626. pthread_mutex_destroy(&p->progress_mutex);
  627. pthread_cond_destroy(&p->input_cond);
  628. pthread_cond_destroy(&p->progress_cond);
  629. pthread_cond_destroy(&p->output_cond);
  630. av_buffer_unref(&p->avpkt.buf);
  631. av_freep(&p->buf);
  632. av_freep(&p->released_buffers);
  633. if (i) {
  634. av_freep(&p->avctx->priv_data);
  635. av_freep(&p->avctx->internal);
  636. av_freep(&p->avctx->slice_offset);
  637. }
  638. av_freep(&p->avctx);
  639. }
  640. av_freep(&fctx->threads);
  641. pthread_mutex_destroy(&fctx->buffer_mutex);
  642. av_freep(&avctx->thread_opaque);
  643. }
  644. static int frame_thread_init(AVCodecContext *avctx)
  645. {
  646. int thread_count = avctx->thread_count;
  647. const AVCodec *codec = avctx->codec;
  648. AVCodecContext *src = avctx;
  649. FrameThreadContext *fctx;
  650. int i, err = 0;
  651. if (!thread_count) {
  652. int nb_cpus = av_cpu_count();
  653. if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
  654. nb_cpus = 1;
  655. // use number of cores + 1 as thread count if there is more than one
  656. if (nb_cpus > 1)
  657. thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
  658. else
  659. thread_count = avctx->thread_count = 1;
  660. }
  661. if (thread_count <= 1) {
  662. avctx->active_thread_type = 0;
  663. return 0;
  664. }
  665. avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
  666. fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
  667. pthread_mutex_init(&fctx->buffer_mutex, NULL);
  668. fctx->delaying = 1;
  669. for (i = 0; i < thread_count; i++) {
  670. AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
  671. PerThreadContext *p = &fctx->threads[i];
  672. pthread_mutex_init(&p->mutex, NULL);
  673. pthread_mutex_init(&p->progress_mutex, NULL);
  674. pthread_cond_init(&p->input_cond, NULL);
  675. pthread_cond_init(&p->progress_cond, NULL);
  676. pthread_cond_init(&p->output_cond, NULL);
  677. p->parent = fctx;
  678. p->avctx = copy;
  679. if (!copy) {
  680. err = AVERROR(ENOMEM);
  681. goto error;
  682. }
  683. *copy = *src;
  684. copy->thread_opaque = p;
  685. copy->pkt = &p->avpkt;
  686. if (!i) {
  687. src = copy;
  688. if (codec->init)
  689. err = codec->init(copy);
  690. update_context_from_thread(avctx, copy, 1);
  691. } else {
  692. copy->priv_data = av_malloc(codec->priv_data_size);
  693. if (!copy->priv_data) {
  694. err = AVERROR(ENOMEM);
  695. goto error;
  696. }
  697. memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
  698. copy->internal = av_malloc(sizeof(AVCodecInternal));
  699. if (!copy->internal) {
  700. err = AVERROR(ENOMEM);
  701. goto error;
  702. }
  703. *copy->internal = *src->internal;
  704. copy->internal->is_copy = 1;
  705. if (codec->init_thread_copy)
  706. err = codec->init_thread_copy(copy);
  707. }
  708. if (err) goto error;
  709. err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
  710. p->thread_init= !err;
  711. if(!p->thread_init)
  712. goto error;
  713. }
  714. return 0;
  715. error:
  716. frame_thread_free(avctx, i+1);
  717. return err;
  718. }
  719. void ff_thread_flush(AVCodecContext *avctx)
  720. {
  721. int i;
  722. FrameThreadContext *fctx = avctx->thread_opaque;
  723. if (!avctx->thread_opaque) return;
  724. park_frame_worker_threads(fctx, avctx->thread_count);
  725. if (fctx->prev_thread) {
  726. if (fctx->prev_thread != &fctx->threads[0])
  727. update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
  728. if (avctx->codec->flush)
  729. avctx->codec->flush(fctx->threads[0].avctx);
  730. }
  731. fctx->next_decoding = fctx->next_finished = 0;
  732. fctx->delaying = 1;
  733. fctx->prev_thread = NULL;
  734. for (i = 0; i < avctx->thread_count; i++) {
  735. PerThreadContext *p = &fctx->threads[i];
  736. // Make sure decode flush calls with size=0 won't return old frames
  737. p->got_frame = 0;
  738. av_frame_unref(&p->frame);
  739. release_delayed_buffers(p);
  740. }
  741. }
  742. int ff_thread_can_start_frame(AVCodecContext *avctx)
  743. {
  744. PerThreadContext *p = avctx->thread_opaque;
  745. if ((avctx->active_thread_type&FF_THREAD_FRAME) && p->state != STATE_SETTING_UP &&
  746. (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
  747. return 0;
  748. }
  749. return 1;
  750. }
  751. static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
  752. {
  753. PerThreadContext *p = avctx->thread_opaque;
  754. int err;
  755. f->owner = avctx;
  756. ff_init_buffer_info(avctx, f->f);
  757. if (!(avctx->active_thread_type & FF_THREAD_FRAME))
  758. return ff_get_buffer(avctx, f->f, flags);
  759. if (p->state != STATE_SETTING_UP &&
  760. (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
  761. av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
  762. return -1;
  763. }
  764. if (avctx->internal->allocate_progress) {
  765. int *progress;
  766. f->progress = av_buffer_alloc(2 * sizeof(int));
  767. if (!f->progress) {
  768. return AVERROR(ENOMEM);
  769. }
  770. progress = (int*)f->progress->data;
  771. progress[0] = progress[1] = -1;
  772. }
  773. pthread_mutex_lock(&p->parent->buffer_mutex);
  774. FF_DISABLE_DEPRECATION_WARNINGS
  775. if (avctx->thread_safe_callbacks || (
  776. #if FF_API_GET_BUFFER
  777. !avctx->get_buffer &&
  778. #endif
  779. avctx->get_buffer2 == avcodec_default_get_buffer2)) {
  780. FF_ENABLE_DEPRECATION_WARNINGS
  781. err = ff_get_buffer(avctx, f->f, flags);
  782. } else {
  783. pthread_mutex_lock(&p->progress_mutex);
  784. p->requested_frame = f->f;
  785. p->requested_flags = flags;
  786. p->state = STATE_GET_BUFFER;
  787. pthread_cond_broadcast(&p->progress_cond);
  788. while (p->state != STATE_SETTING_UP)
  789. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  790. err = p->result;
  791. pthread_mutex_unlock(&p->progress_mutex);
  792. }
  793. if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
  794. ff_thread_finish_setup(avctx);
  795. if (err)
  796. av_buffer_unref(&f->progress);
  797. pthread_mutex_unlock(&p->parent->buffer_mutex);
  798. return err;
  799. }
  800. enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
  801. {
  802. enum AVPixelFormat res;
  803. PerThreadContext *p = avctx->thread_opaque;
  804. if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
  805. avctx->get_format == avcodec_default_get_format)
  806. return avctx->get_format(avctx, fmt);
  807. if (p->state != STATE_SETTING_UP) {
  808. av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
  809. return -1;
  810. }
  811. pthread_mutex_lock(&p->progress_mutex);
  812. p->available_formats = fmt;
  813. p->state = STATE_GET_FORMAT;
  814. pthread_cond_broadcast(&p->progress_cond);
  815. while (p->state != STATE_SETTING_UP)
  816. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  817. res = p->result_format;
  818. pthread_mutex_unlock(&p->progress_mutex);
  819. return res;
  820. }
  821. int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
  822. {
  823. int ret = thread_get_buffer_internal(avctx, f, flags);
  824. if (ret < 0)
  825. av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
  826. return ret;
  827. }
  828. void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
  829. {
  830. PerThreadContext *p = avctx->thread_opaque;
  831. FrameThreadContext *fctx;
  832. AVFrame *dst, *tmp;
  833. FF_DISABLE_DEPRECATION_WARNINGS
  834. int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
  835. avctx->thread_safe_callbacks ||
  836. (
  837. #if FF_API_GET_BUFFER
  838. !avctx->get_buffer &&
  839. #endif
  840. avctx->get_buffer2 == avcodec_default_get_buffer2);
  841. FF_ENABLE_DEPRECATION_WARNINGS
  842. if (!f->f->data[0])
  843. return;
  844. if (avctx->debug & FF_DEBUG_BUFFERS)
  845. av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
  846. av_buffer_unref(&f->progress);
  847. f->owner = NULL;
  848. if (can_direct_free) {
  849. av_frame_unref(f->f);
  850. return;
  851. }
  852. fctx = p->parent;
  853. pthread_mutex_lock(&fctx->buffer_mutex);
  854. if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
  855. goto fail;
  856. tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
  857. (p->num_released_buffers + 1) *
  858. sizeof(*p->released_buffers));
  859. if (!tmp)
  860. goto fail;
  861. p->released_buffers = tmp;
  862. dst = &p->released_buffers[p->num_released_buffers];
  863. av_frame_move_ref(dst, f->f);
  864. p->num_released_buffers++;
  865. fail:
  866. pthread_mutex_unlock(&fctx->buffer_mutex);
  867. }
  868. /**
  869. * Set the threading algorithms used.
  870. *
  871. * Threading requires more than one thread.
  872. * Frame threading requires entire frames to be passed to the codec,
  873. * and introduces extra decoding delay, so is incompatible with low_delay.
  874. *
  875. * @param avctx The context.
  876. */
  877. static void validate_thread_parameters(AVCodecContext *avctx)
  878. {
  879. int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
  880. && !(avctx->flags & CODEC_FLAG_TRUNCATED)
  881. && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
  882. && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
  883. if (avctx->thread_count == 1) {
  884. avctx->active_thread_type = 0;
  885. } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
  886. avctx->active_thread_type = FF_THREAD_FRAME;
  887. } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
  888. avctx->thread_type & FF_THREAD_SLICE) {
  889. avctx->active_thread_type = FF_THREAD_SLICE;
  890. } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
  891. avctx->thread_count = 1;
  892. avctx->active_thread_type = 0;
  893. }
  894. if (avctx->thread_count > MAX_AUTO_THREADS)
  895. av_log(avctx, AV_LOG_WARNING,
  896. "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
  897. avctx->thread_count, MAX_AUTO_THREADS);
  898. }
  899. int ff_thread_init(AVCodecContext *avctx)
  900. {
  901. #if HAVE_W32THREADS
  902. w32thread_init();
  903. #endif
  904. validate_thread_parameters(avctx);
  905. if (avctx->active_thread_type&FF_THREAD_SLICE)
  906. return thread_init_internal(avctx);
  907. else if (avctx->active_thread_type&FF_THREAD_FRAME)
  908. return frame_thread_init(avctx);
  909. return 0;
  910. }
  911. void ff_thread_free(AVCodecContext *avctx)
  912. {
  913. if (avctx->active_thread_type&FF_THREAD_FRAME)
  914. frame_thread_free(avctx, avctx->thread_count);
  915. else
  916. thread_free(avctx);
  917. }