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.

1122 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 "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. int ff_get_logical_cpus(AVCodecContext *avctx)
  125. {
  126. int nb_cpus = av_cpu_count();
  127. if (avctx->height)
  128. nb_cpus = FFMIN(nb_cpus, (avctx->height+15)/16);
  129. return nb_cpus;
  130. }
  131. static void* attribute_align_arg worker(void *v)
  132. {
  133. AVCodecContext *avctx = v;
  134. ThreadContext *c = avctx->thread_opaque;
  135. int our_job = c->job_count;
  136. int last_execute = 0;
  137. int thread_count = avctx->thread_count;
  138. int self_id;
  139. pthread_mutex_lock(&c->current_job_lock);
  140. self_id = c->current_job++;
  141. for (;;){
  142. while (our_job >= c->job_count) {
  143. if (c->current_job == thread_count + c->job_count)
  144. pthread_cond_signal(&c->last_job_cond);
  145. while (last_execute == c->current_execute && !c->done)
  146. pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
  147. last_execute = c->current_execute;
  148. our_job = self_id;
  149. if (c->done) {
  150. pthread_mutex_unlock(&c->current_job_lock);
  151. return NULL;
  152. }
  153. }
  154. pthread_mutex_unlock(&c->current_job_lock);
  155. c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
  156. c->func2(avctx, c->args, our_job, self_id);
  157. pthread_mutex_lock(&c->current_job_lock);
  158. our_job = c->current_job++;
  159. }
  160. }
  161. static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
  162. {
  163. while (c->current_job != thread_count + c->job_count)
  164. pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
  165. pthread_mutex_unlock(&c->current_job_lock);
  166. }
  167. static void thread_free(AVCodecContext *avctx)
  168. {
  169. ThreadContext *c = avctx->thread_opaque;
  170. int i;
  171. pthread_mutex_lock(&c->current_job_lock);
  172. c->done = 1;
  173. pthread_cond_broadcast(&c->current_job_cond);
  174. pthread_mutex_unlock(&c->current_job_lock);
  175. for (i=0; i<avctx->thread_count; i++)
  176. pthread_join(c->workers[i], NULL);
  177. pthread_mutex_destroy(&c->current_job_lock);
  178. pthread_cond_destroy(&c->current_job_cond);
  179. pthread_cond_destroy(&c->last_job_cond);
  180. av_free(c->workers);
  181. av_freep(&avctx->thread_opaque);
  182. }
  183. static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
  184. {
  185. ThreadContext *c= avctx->thread_opaque;
  186. int dummy_ret;
  187. if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
  188. return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
  189. if (job_count <= 0)
  190. return 0;
  191. pthread_mutex_lock(&c->current_job_lock);
  192. c->current_job = avctx->thread_count;
  193. c->job_count = job_count;
  194. c->job_size = job_size;
  195. c->args = arg;
  196. c->func = func;
  197. if (ret) {
  198. c->rets = ret;
  199. c->rets_count = job_count;
  200. } else {
  201. c->rets = &dummy_ret;
  202. c->rets_count = 1;
  203. }
  204. c->current_execute++;
  205. pthread_cond_broadcast(&c->current_job_cond);
  206. avcodec_thread_park_workers(c, avctx->thread_count);
  207. return 0;
  208. }
  209. static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
  210. {
  211. ThreadContext *c= avctx->thread_opaque;
  212. c->func2 = func2;
  213. return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
  214. }
  215. static int thread_init(AVCodecContext *avctx)
  216. {
  217. int i;
  218. ThreadContext *c;
  219. int thread_count = avctx->thread_count;
  220. if (!thread_count) {
  221. int nb_cpus = ff_get_logical_cpus(avctx);
  222. // use number of cores + 1 as thread count if there is more than one
  223. if (nb_cpus > 1)
  224. thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
  225. else
  226. thread_count = avctx->thread_count = 1;
  227. }
  228. if (thread_count <= 1) {
  229. avctx->active_thread_type = 0;
  230. return 0;
  231. }
  232. c = av_mallocz(sizeof(ThreadContext));
  233. if (!c)
  234. return -1;
  235. c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
  236. if (!c->workers) {
  237. av_free(c);
  238. return -1;
  239. }
  240. avctx->thread_opaque = c;
  241. c->current_job = 0;
  242. c->job_count = 0;
  243. c->job_size = 0;
  244. c->done = 0;
  245. pthread_cond_init(&c->current_job_cond, NULL);
  246. pthread_cond_init(&c->last_job_cond, NULL);
  247. pthread_mutex_init(&c->current_job_lock, NULL);
  248. pthread_mutex_lock(&c->current_job_lock);
  249. for (i=0; i<thread_count; i++) {
  250. if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
  251. avctx->thread_count = i;
  252. pthread_mutex_unlock(&c->current_job_lock);
  253. ff_thread_free(avctx);
  254. return -1;
  255. }
  256. }
  257. avcodec_thread_park_workers(c, thread_count);
  258. avctx->execute = avcodec_thread_execute;
  259. avctx->execute2 = avcodec_thread_execute2;
  260. return 0;
  261. }
  262. #define THREAD_SAFE_CALLBACKS(avctx) \
  263. ((avctx)->thread_safe_callbacks || (!(avctx)->get_buffer && (avctx)->get_buffer2 == avcodec_default_get_buffer2))
  264. /**
  265. * Codec worker thread.
  266. *
  267. * Automatically calls ff_thread_finish_setup() if the codec does
  268. * not provide an update_thread_context method, or if the codec returns
  269. * before calling it.
  270. */
  271. static attribute_align_arg void *frame_worker_thread(void *arg)
  272. {
  273. PerThreadContext *p = arg;
  274. FrameThreadContext *fctx = p->parent;
  275. AVCodecContext *avctx = p->avctx;
  276. const AVCodec *codec = avctx->codec;
  277. pthread_mutex_lock(&p->mutex);
  278. while (1) {
  279. while (p->state == STATE_INPUT_READY && !fctx->die)
  280. pthread_cond_wait(&p->input_cond, &p->mutex);
  281. if (fctx->die) break;
  282. if (!codec->update_thread_context && THREAD_SAFE_CALLBACKS(avctx))
  283. ff_thread_finish_setup(avctx);
  284. avcodec_get_frame_defaults(&p->frame);
  285. p->got_frame = 0;
  286. p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
  287. /* many decoders assign whole AVFrames, thus overwriting extended_data;
  288. * make sure it's set correctly */
  289. p->frame.extended_data = p->frame.data;
  290. if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
  291. pthread_mutex_lock(&p->progress_mutex);
  292. #if 0 //BUFREF-FIXME
  293. for (i = 0; i < MAX_BUFFERS; i++)
  294. if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != AV_CODEC_ID_H264)) {
  295. p->progress[i][0] = INT_MAX;
  296. p->progress[i][1] = INT_MAX;
  297. }
  298. #endif
  299. p->state = STATE_INPUT_READY;
  300. pthread_cond_broadcast(&p->progress_cond);
  301. pthread_cond_signal(&p->output_cond);
  302. pthread_mutex_unlock(&p->progress_mutex);
  303. }
  304. pthread_mutex_unlock(&p->mutex);
  305. return NULL;
  306. }
  307. /**
  308. * Update the next thread's AVCodecContext with values from the reference thread's context.
  309. *
  310. * @param dst The destination context.
  311. * @param src The source context.
  312. * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
  313. */
  314. static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
  315. {
  316. int err = 0;
  317. if (dst != src) {
  318. dst->time_base = src->time_base;
  319. dst->width = src->width;
  320. dst->height = src->height;
  321. dst->pix_fmt = src->pix_fmt;
  322. dst->coded_width = src->coded_width;
  323. dst->coded_height = src->coded_height;
  324. dst->has_b_frames = src->has_b_frames;
  325. dst->idct_algo = src->idct_algo;
  326. dst->bits_per_coded_sample = src->bits_per_coded_sample;
  327. dst->sample_aspect_ratio = src->sample_aspect_ratio;
  328. dst->dtg_active_format = src->dtg_active_format;
  329. dst->profile = src->profile;
  330. dst->level = src->level;
  331. dst->bits_per_raw_sample = src->bits_per_raw_sample;
  332. dst->ticks_per_frame = src->ticks_per_frame;
  333. dst->color_primaries = src->color_primaries;
  334. dst->color_trc = src->color_trc;
  335. dst->colorspace = src->colorspace;
  336. dst->color_range = src->color_range;
  337. dst->chroma_sample_location = src->chroma_sample_location;
  338. dst->hwaccel = src->hwaccel;
  339. dst->hwaccel_context = src->hwaccel_context;
  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. dst->get_buffer = src->get_buffer;
  365. dst->release_buffer = src->release_buffer;
  366. #endif
  367. dst->opaque = src->opaque;
  368. dst->debug = src->debug;
  369. dst->debug_mv = src->debug_mv;
  370. dst->slice_flags = src->slice_flags;
  371. dst->flags2 = src->flags2;
  372. copy_fields(skip_loop_filter, subtitle_header);
  373. dst->frame_number = src->frame_number;
  374. dst->reordered_opaque = src->reordered_opaque;
  375. dst->thread_safe_callbacks = src->thread_safe_callbacks;
  376. if (src->slice_count && src->slice_offset) {
  377. if (dst->slice_count < src->slice_count) {
  378. int *tmp = av_realloc(dst->slice_offset, src->slice_count *
  379. sizeof(*dst->slice_offset));
  380. if (!tmp) {
  381. av_free(dst->slice_offset);
  382. return AVERROR(ENOMEM);
  383. }
  384. dst->slice_offset = tmp;
  385. }
  386. memcpy(dst->slice_offset, src->slice_offset,
  387. src->slice_count * sizeof(*dst->slice_offset));
  388. }
  389. dst->slice_count = src->slice_count;
  390. return 0;
  391. #undef copy_fields
  392. }
  393. /// Releases the buffers that this decoding thread was the last user of.
  394. static void release_delayed_buffers(PerThreadContext *p)
  395. {
  396. FrameThreadContext *fctx = p->parent;
  397. while (p->num_released_buffers > 0) {
  398. AVFrame *f;
  399. pthread_mutex_lock(&fctx->buffer_mutex);
  400. // fix extended data in case the caller screwed it up
  401. av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO);
  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. av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
  651. // use number of cores + 1 as thread count if there is more than one
  652. if (nb_cpus > 1)
  653. thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
  654. else
  655. thread_count = avctx->thread_count = 1;
  656. }
  657. if (thread_count <= 1) {
  658. avctx->active_thread_type = 0;
  659. return 0;
  660. }
  661. avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
  662. fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
  663. pthread_mutex_init(&fctx->buffer_mutex, NULL);
  664. fctx->delaying = 1;
  665. for (i = 0; i < thread_count; i++) {
  666. AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
  667. PerThreadContext *p = &fctx->threads[i];
  668. pthread_mutex_init(&p->mutex, NULL);
  669. pthread_mutex_init(&p->progress_mutex, NULL);
  670. pthread_cond_init(&p->input_cond, NULL);
  671. pthread_cond_init(&p->progress_cond, NULL);
  672. pthread_cond_init(&p->output_cond, NULL);
  673. p->parent = fctx;
  674. p->avctx = copy;
  675. if (!copy) {
  676. err = AVERROR(ENOMEM);
  677. goto error;
  678. }
  679. *copy = *src;
  680. copy->thread_opaque = p;
  681. copy->pkt = &p->avpkt;
  682. if (!i) {
  683. src = copy;
  684. if (codec->init)
  685. err = codec->init(copy);
  686. update_context_from_thread(avctx, copy, 1);
  687. } else {
  688. copy->priv_data = av_malloc(codec->priv_data_size);
  689. if (!copy->priv_data) {
  690. err = AVERROR(ENOMEM);
  691. goto error;
  692. }
  693. memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
  694. copy->internal = av_malloc(sizeof(AVCodecInternal));
  695. if (!copy->internal) {
  696. err = AVERROR(ENOMEM);
  697. goto error;
  698. }
  699. *copy->internal = *src->internal;
  700. copy->internal->is_copy = 1;
  701. if (codec->init_thread_copy)
  702. err = codec->init_thread_copy(copy);
  703. }
  704. if (err) goto error;
  705. err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
  706. p->thread_init= !err;
  707. if(!p->thread_init)
  708. goto error;
  709. }
  710. return 0;
  711. error:
  712. frame_thread_free(avctx, i+1);
  713. return err;
  714. }
  715. void ff_thread_flush(AVCodecContext *avctx)
  716. {
  717. int i;
  718. FrameThreadContext *fctx = avctx->thread_opaque;
  719. if (!avctx->thread_opaque) return;
  720. park_frame_worker_threads(fctx, avctx->thread_count);
  721. if (fctx->prev_thread) {
  722. if (fctx->prev_thread != &fctx->threads[0])
  723. update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
  724. if (avctx->codec->flush)
  725. avctx->codec->flush(fctx->threads[0].avctx);
  726. }
  727. fctx->next_decoding = fctx->next_finished = 0;
  728. fctx->delaying = 1;
  729. fctx->prev_thread = NULL;
  730. for (i = 0; i < avctx->thread_count; i++) {
  731. PerThreadContext *p = &fctx->threads[i];
  732. // Make sure decode flush calls with size=0 won't return old frames
  733. p->got_frame = 0;
  734. av_frame_unref(&p->frame);
  735. release_delayed_buffers(p);
  736. }
  737. }
  738. int ff_thread_can_start_frame(AVCodecContext *avctx)
  739. {
  740. PerThreadContext *p = avctx->thread_opaque;
  741. if ((avctx->active_thread_type&FF_THREAD_FRAME) && p->state != STATE_SETTING_UP &&
  742. (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
  743. return 0;
  744. }
  745. return 1;
  746. }
  747. static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
  748. {
  749. PerThreadContext *p = avctx->thread_opaque;
  750. int err;
  751. f->owner = avctx;
  752. ff_init_buffer_info(avctx, f->f);
  753. if (!(avctx->active_thread_type & FF_THREAD_FRAME))
  754. return ff_get_buffer(avctx, f->f, flags);
  755. if (p->state != STATE_SETTING_UP &&
  756. (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
  757. av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
  758. return -1;
  759. }
  760. if (avctx->internal->allocate_progress) {
  761. int *progress;
  762. f->progress = av_buffer_alloc(2 * sizeof(int));
  763. if (!f->progress) {
  764. return AVERROR(ENOMEM);
  765. }
  766. progress = (int*)f->progress->data;
  767. progress[0] = progress[1] = -1;
  768. }
  769. pthread_mutex_lock(&p->parent->buffer_mutex);
  770. if (avctx->thread_safe_callbacks || (
  771. #if FF_API_GET_BUFFER
  772. !avctx->get_buffer &&
  773. #endif
  774. avctx->get_buffer2 == avcodec_default_get_buffer2)) {
  775. err = ff_get_buffer(avctx, f->f, flags);
  776. } else {
  777. pthread_mutex_lock(&p->progress_mutex);
  778. p->requested_frame = f->f;
  779. p->requested_flags = flags;
  780. p->state = STATE_GET_BUFFER;
  781. pthread_cond_broadcast(&p->progress_cond);
  782. while (p->state != STATE_SETTING_UP)
  783. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  784. err = p->result;
  785. pthread_mutex_unlock(&p->progress_mutex);
  786. }
  787. if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
  788. ff_thread_finish_setup(avctx);
  789. if (err)
  790. av_buffer_unref(&f->progress);
  791. pthread_mutex_unlock(&p->parent->buffer_mutex);
  792. return err;
  793. }
  794. enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
  795. {
  796. enum AVPixelFormat res;
  797. PerThreadContext *p = avctx->thread_opaque;
  798. if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
  799. avctx->get_format == avcodec_default_get_format)
  800. return avctx->get_format(avctx, fmt);
  801. if (p->state != STATE_SETTING_UP) {
  802. av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
  803. return -1;
  804. }
  805. pthread_mutex_lock(&p->progress_mutex);
  806. p->available_formats = fmt;
  807. p->state = STATE_GET_FORMAT;
  808. pthread_cond_broadcast(&p->progress_cond);
  809. while (p->state != STATE_SETTING_UP)
  810. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  811. res = p->result_format;
  812. pthread_mutex_unlock(&p->progress_mutex);
  813. return res;
  814. }
  815. int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
  816. {
  817. int ret = thread_get_buffer_internal(avctx, f, flags);
  818. if (ret < 0)
  819. av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
  820. return ret;
  821. }
  822. void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
  823. {
  824. PerThreadContext *p = avctx->thread_opaque;
  825. FrameThreadContext *fctx;
  826. AVFrame *dst, *tmp;
  827. int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
  828. avctx->thread_safe_callbacks ||
  829. (
  830. #if FF_API_GET_BUFFER
  831. !avctx->get_buffer &&
  832. #endif
  833. avctx->get_buffer2 == avcodec_default_get_buffer2);
  834. if (!f->f->data[0])
  835. return;
  836. if (avctx->debug & FF_DEBUG_BUFFERS)
  837. av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
  838. av_buffer_unref(&f->progress);
  839. f->owner = NULL;
  840. if (can_direct_free) {
  841. av_frame_unref(f->f);
  842. return;
  843. }
  844. fctx = p->parent;
  845. pthread_mutex_lock(&fctx->buffer_mutex);
  846. if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
  847. goto fail;
  848. tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
  849. (p->num_released_buffers + 1) *
  850. sizeof(*p->released_buffers));
  851. if (!tmp)
  852. goto fail;
  853. p->released_buffers = tmp;
  854. dst = &p->released_buffers[p->num_released_buffers];
  855. av_frame_move_ref(dst, f->f);
  856. p->num_released_buffers++;
  857. fail:
  858. pthread_mutex_unlock(&fctx->buffer_mutex);
  859. }
  860. /**
  861. * Set the threading algorithms used.
  862. *
  863. * Threading requires more than one thread.
  864. * Frame threading requires entire frames to be passed to the codec,
  865. * and introduces extra decoding delay, so is incompatible with low_delay.
  866. *
  867. * @param avctx The context.
  868. */
  869. static void validate_thread_parameters(AVCodecContext *avctx)
  870. {
  871. int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
  872. && !(avctx->flags & CODEC_FLAG_TRUNCATED)
  873. && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
  874. && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
  875. if (avctx->thread_count == 1) {
  876. avctx->active_thread_type = 0;
  877. } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
  878. avctx->active_thread_type = FF_THREAD_FRAME;
  879. } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
  880. avctx->thread_type & FF_THREAD_SLICE) {
  881. avctx->active_thread_type = FF_THREAD_SLICE;
  882. } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
  883. avctx->thread_count = 1;
  884. avctx->active_thread_type = 0;
  885. }
  886. if (avctx->thread_count > MAX_AUTO_THREADS)
  887. av_log(avctx, AV_LOG_WARNING,
  888. "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
  889. avctx->thread_count, MAX_AUTO_THREADS);
  890. }
  891. int ff_thread_init(AVCodecContext *avctx)
  892. {
  893. #if HAVE_W32THREADS
  894. w32thread_init();
  895. #endif
  896. validate_thread_parameters(avctx);
  897. if (avctx->active_thread_type&FF_THREAD_SLICE)
  898. return thread_init(avctx);
  899. else if (avctx->active_thread_type&FF_THREAD_FRAME)
  900. return frame_thread_init(avctx);
  901. return 0;
  902. }
  903. void ff_thread_free(AVCodecContext *avctx)
  904. {
  905. if (avctx->active_thread_type&FF_THREAD_FRAME)
  906. frame_thread_free(avctx, avctx->thread_count);
  907. else
  908. thread_free(avctx);
  909. }