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.

1194 lines
38KB

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