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.

1120 lines
35KB

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