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.

1064 lines
32KB

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