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.

1170 lines
36KB

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