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.

1072 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. int i;
  308. if (p->state == STATE_INPUT_READY && !fctx->die) {
  309. pthread_mutex_lock(&p->mutex);
  310. while (p->state == STATE_INPUT_READY && !fctx->die)
  311. pthread_cond_wait(&p->input_cond, &p->mutex);
  312. pthread_mutex_unlock(&p->mutex);
  313. }
  314. if (fctx->die) break;
  315. if (!codec->update_thread_context && (avctx->thread_safe_callbacks || avctx->get_buffer == avcodec_default_get_buffer))
  316. ff_thread_finish_setup(avctx);
  317. pthread_mutex_lock(&p->mutex);
  318. avcodec_get_frame_defaults(&p->frame);
  319. p->got_frame = 0;
  320. p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
  321. if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
  322. p->state = STATE_INPUT_READY;
  323. pthread_mutex_lock(&p->progress_mutex);
  324. for (i = 0; i < MAX_BUFFERS; i++)
  325. if (p->progress_used[i]) {
  326. p->progress[i][0] = INT_MAX;
  327. p->progress[i][1] = INT_MAX;
  328. }
  329. pthread_cond_broadcast(&p->progress_cond);
  330. pthread_cond_signal(&p->output_cond);
  331. pthread_mutex_unlock(&p->progress_mutex);
  332. pthread_mutex_unlock(&p->mutex);
  333. }
  334. return NULL;
  335. }
  336. /**
  337. * Update the next thread's AVCodecContext with values from the reference thread's context.
  338. *
  339. * @param dst The destination context.
  340. * @param src The source context.
  341. * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
  342. */
  343. static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
  344. {
  345. int err = 0;
  346. if (dst != src) {
  347. dst->sub_id = src->sub_id;
  348. dst->time_base = src->time_base;
  349. dst->width = src->width;
  350. dst->height = src->height;
  351. dst->pix_fmt = src->pix_fmt;
  352. dst->coded_width = src->coded_width;
  353. dst->coded_height = src->coded_height;
  354. dst->has_b_frames = src->has_b_frames;
  355. dst->idct_algo = src->idct_algo;
  356. dst->bits_per_coded_sample = src->bits_per_coded_sample;
  357. dst->sample_aspect_ratio = src->sample_aspect_ratio;
  358. dst->dtg_active_format = src->dtg_active_format;
  359. dst->profile = src->profile;
  360. dst->level = src->level;
  361. dst->bits_per_raw_sample = src->bits_per_raw_sample;
  362. dst->ticks_per_frame = src->ticks_per_frame;
  363. dst->color_primaries = src->color_primaries;
  364. dst->color_trc = src->color_trc;
  365. dst->colorspace = src->colorspace;
  366. dst->color_range = src->color_range;
  367. dst->chroma_sample_location = src->chroma_sample_location;
  368. }
  369. if (for_user) {
  370. dst->delay = src->thread_count - 1;
  371. dst->coded_frame = src->coded_frame;
  372. } else {
  373. if (dst->codec->update_thread_context)
  374. err = dst->codec->update_thread_context(dst, src);
  375. }
  376. return err;
  377. }
  378. /**
  379. * Update the next thread's AVCodecContext with values set by the user.
  380. *
  381. * @param dst The destination context.
  382. * @param src The source context.
  383. * @return 0 on success, negative error code on failure
  384. */
  385. static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
  386. {
  387. #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
  388. dst->flags = src->flags;
  389. dst->draw_horiz_band= src->draw_horiz_band;
  390. dst->get_buffer = src->get_buffer;
  391. dst->release_buffer = src->release_buffer;
  392. dst->opaque = src->opaque;
  393. dst->dsp_mask = src->dsp_mask;
  394. dst->debug = src->debug;
  395. dst->debug_mv = src->debug_mv;
  396. dst->slice_flags = src->slice_flags;
  397. dst->flags2 = src->flags2;
  398. copy_fields(skip_loop_filter, bidir_refine);
  399. dst->frame_number = src->frame_number;
  400. dst->reordered_opaque = src->reordered_opaque;
  401. dst->thread_safe_callbacks = src->thread_safe_callbacks;
  402. if (src->slice_count && src->slice_offset) {
  403. if (dst->slice_count < src->slice_count) {
  404. int *tmp = av_realloc(dst->slice_offset, src->slice_count *
  405. sizeof(*dst->slice_offset));
  406. if (!tmp) {
  407. av_free(dst->slice_offset);
  408. return AVERROR(ENOMEM);
  409. }
  410. dst->slice_offset = tmp;
  411. }
  412. memcpy(dst->slice_offset, src->slice_offset,
  413. src->slice_count * sizeof(*dst->slice_offset));
  414. }
  415. dst->slice_count = src->slice_count;
  416. return 0;
  417. #undef copy_fields
  418. }
  419. static void free_progress(AVFrame *f)
  420. {
  421. PerThreadContext *p = f->owner->thread_opaque;
  422. int *progress = f->thread_opaque;
  423. p->progress_used[(progress - p->progress[0]) / 2] = 0;
  424. }
  425. /// Releases the buffers that this decoding thread was the last user of.
  426. static void release_delayed_buffers(PerThreadContext *p)
  427. {
  428. FrameThreadContext *fctx = p->parent;
  429. while (p->num_released_buffers > 0) {
  430. AVFrame *f;
  431. pthread_mutex_lock(&fctx->buffer_mutex);
  432. f = &p->released_buffers[--p->num_released_buffers];
  433. free_progress(f);
  434. f->thread_opaque = NULL;
  435. f->owner->release_buffer(f->owner, f);
  436. pthread_mutex_unlock(&fctx->buffer_mutex);
  437. }
  438. }
  439. static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
  440. {
  441. FrameThreadContext *fctx = p->parent;
  442. PerThreadContext *prev_thread = fctx->prev_thread;
  443. AVCodec *codec = p->avctx->codec;
  444. uint8_t *buf = p->avpkt.data;
  445. if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
  446. pthread_mutex_lock(&p->mutex);
  447. release_delayed_buffers(p);
  448. if (prev_thread) {
  449. int err;
  450. if (prev_thread->state == STATE_SETTING_UP) {
  451. pthread_mutex_lock(&prev_thread->progress_mutex);
  452. while (prev_thread->state == STATE_SETTING_UP)
  453. pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
  454. pthread_mutex_unlock(&prev_thread->progress_mutex);
  455. }
  456. err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
  457. if (err) {
  458. pthread_mutex_unlock(&p->mutex);
  459. return err;
  460. }
  461. }
  462. av_fast_malloc(&buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
  463. p->avpkt = *avpkt;
  464. p->avpkt.data = buf;
  465. memcpy(buf, avpkt->data, avpkt->size);
  466. memset(buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  467. p->state = STATE_SETTING_UP;
  468. pthread_cond_signal(&p->input_cond);
  469. pthread_mutex_unlock(&p->mutex);
  470. /*
  471. * If the client doesn't have a thread-safe get_buffer(),
  472. * then decoding threads call back to the main thread,
  473. * and it calls back to the client here.
  474. */
  475. if (!p->avctx->thread_safe_callbacks &&
  476. p->avctx->get_buffer != avcodec_default_get_buffer) {
  477. while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
  478. pthread_mutex_lock(&p->progress_mutex);
  479. while (p->state == STATE_SETTING_UP)
  480. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  481. if (p->state == STATE_GET_BUFFER) {
  482. p->result = p->avctx->get_buffer(p->avctx, p->requested_frame);
  483. p->state = STATE_SETTING_UP;
  484. pthread_cond_signal(&p->progress_cond);
  485. }
  486. pthread_mutex_unlock(&p->progress_mutex);
  487. }
  488. }
  489. fctx->prev_thread = p;
  490. fctx->next_decoding++;
  491. return 0;
  492. }
  493. int ff_thread_decode_frame(AVCodecContext *avctx,
  494. AVFrame *picture, int *got_picture_ptr,
  495. AVPacket *avpkt)
  496. {
  497. FrameThreadContext *fctx = avctx->thread_opaque;
  498. int finished = fctx->next_finished;
  499. PerThreadContext *p;
  500. int err;
  501. /*
  502. * Submit a packet to the next decoding thread.
  503. */
  504. p = &fctx->threads[fctx->next_decoding];
  505. err = update_context_from_user(p->avctx, avctx);
  506. if (err) return err;
  507. err = submit_packet(p, avpkt);
  508. if (err) return err;
  509. /*
  510. * If we're still receiving the initial packets, don't return a frame.
  511. */
  512. if (fctx->delaying && avpkt->size) {
  513. if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
  514. *got_picture_ptr=0;
  515. return avpkt->size;
  516. }
  517. /*
  518. * Return the next available frame from the oldest thread.
  519. * If we're at the end of the stream, then we have to skip threads that
  520. * didn't output a frame, because we don't want to accidentally signal
  521. * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
  522. */
  523. do {
  524. p = &fctx->threads[finished++];
  525. if (p->state != STATE_INPUT_READY) {
  526. pthread_mutex_lock(&p->progress_mutex);
  527. while (p->state != STATE_INPUT_READY)
  528. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  529. pthread_mutex_unlock(&p->progress_mutex);
  530. }
  531. *picture = p->frame;
  532. *got_picture_ptr = p->got_frame;
  533. picture->pkt_dts = p->avpkt.dts;
  534. picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
  535. picture->width = avctx->width;
  536. picture->height = avctx->height;
  537. picture->format = avctx->pix_fmt;
  538. /*
  539. * A later call with avkpt->size == 0 may loop over all threads,
  540. * including this one, searching for a frame to return before being
  541. * stopped by the "finished != fctx->next_finished" condition.
  542. * Make sure we don't mistakenly return the same frame again.
  543. */
  544. p->got_frame = 0;
  545. if (finished >= avctx->thread_count) finished = 0;
  546. } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
  547. update_context_from_thread(avctx, p->avctx, 1);
  548. if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
  549. fctx->next_finished = finished;
  550. /* return the size of the consumed packet if no error occurred */
  551. return (p->result >= 0) ? avpkt->size : p->result;
  552. }
  553. void ff_thread_report_progress(AVFrame *f, int n, int field)
  554. {
  555. PerThreadContext *p;
  556. int *progress = f->thread_opaque;
  557. if (!progress || progress[field] >= n) return;
  558. p = f->owner->thread_opaque;
  559. if (f->owner->debug&FF_DEBUG_THREADS)
  560. av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
  561. pthread_mutex_lock(&p->progress_mutex);
  562. progress[field] = n;
  563. pthread_cond_broadcast(&p->progress_cond);
  564. pthread_mutex_unlock(&p->progress_mutex);
  565. }
  566. void ff_thread_await_progress(AVFrame *f, int n, int field)
  567. {
  568. PerThreadContext *p;
  569. int *progress = f->thread_opaque;
  570. if (!progress || progress[field] >= n) return;
  571. p = f->owner->thread_opaque;
  572. if (f->owner->debug&FF_DEBUG_THREADS)
  573. av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
  574. pthread_mutex_lock(&p->progress_mutex);
  575. while (progress[field] < n)
  576. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  577. pthread_mutex_unlock(&p->progress_mutex);
  578. }
  579. void ff_thread_finish_setup(AVCodecContext *avctx) {
  580. PerThreadContext *p = avctx->thread_opaque;
  581. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
  582. if(p->state == STATE_SETUP_FINISHED){
  583. av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
  584. }
  585. pthread_mutex_lock(&p->progress_mutex);
  586. p->state = STATE_SETUP_FINISHED;
  587. pthread_cond_broadcast(&p->progress_cond);
  588. pthread_mutex_unlock(&p->progress_mutex);
  589. }
  590. /// Waits for all threads to finish.
  591. static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
  592. {
  593. int i;
  594. for (i = 0; i < thread_count; i++) {
  595. PerThreadContext *p = &fctx->threads[i];
  596. if (p->state != STATE_INPUT_READY) {
  597. pthread_mutex_lock(&p->progress_mutex);
  598. while (p->state != STATE_INPUT_READY)
  599. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  600. pthread_mutex_unlock(&p->progress_mutex);
  601. }
  602. p->got_frame = 0;
  603. }
  604. }
  605. static void frame_thread_free(AVCodecContext *avctx, int thread_count)
  606. {
  607. FrameThreadContext *fctx = avctx->thread_opaque;
  608. AVCodec *codec = avctx->codec;
  609. int i;
  610. park_frame_worker_threads(fctx, thread_count);
  611. if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
  612. update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
  613. fctx->die = 1;
  614. for (i = 0; i < thread_count; i++) {
  615. PerThreadContext *p = &fctx->threads[i];
  616. pthread_mutex_lock(&p->mutex);
  617. pthread_cond_signal(&p->input_cond);
  618. pthread_mutex_unlock(&p->mutex);
  619. if (p->thread_init)
  620. pthread_join(p->thread, NULL);
  621. p->thread_init=0;
  622. if (codec->close)
  623. codec->close(p->avctx);
  624. avctx->codec = NULL;
  625. release_delayed_buffers(p);
  626. }
  627. for (i = 0; i < thread_count; i++) {
  628. PerThreadContext *p = &fctx->threads[i];
  629. avcodec_default_free_buffers(p->avctx);
  630. pthread_mutex_destroy(&p->mutex);
  631. pthread_mutex_destroy(&p->progress_mutex);
  632. pthread_cond_destroy(&p->input_cond);
  633. pthread_cond_destroy(&p->progress_cond);
  634. pthread_cond_destroy(&p->output_cond);
  635. av_freep(&p->avpkt.data);
  636. if (i) {
  637. av_freep(&p->avctx->priv_data);
  638. av_freep(&p->avctx->internal);
  639. av_freep(&p->avctx->slice_offset);
  640. }
  641. av_freep(&p->avctx);
  642. }
  643. av_freep(&fctx->threads);
  644. pthread_mutex_destroy(&fctx->buffer_mutex);
  645. av_freep(&avctx->thread_opaque);
  646. }
  647. static int frame_thread_init(AVCodecContext *avctx)
  648. {
  649. int thread_count = avctx->thread_count;
  650. AVCodec *codec = avctx->codec;
  651. AVCodecContext *src = avctx;
  652. FrameThreadContext *fctx;
  653. int i, err = 0;
  654. if (!thread_count) {
  655. int nb_cpus = get_logical_cpus(avctx);
  656. if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
  657. nb_cpus = 1;
  658. // use number of cores + 1 as thread count if there is more than one
  659. if (nb_cpus > 1)
  660. thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
  661. else
  662. thread_count = avctx->thread_count = 1;
  663. }
  664. if (thread_count <= 1) {
  665. avctx->active_thread_type = 0;
  666. return 0;
  667. }
  668. avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
  669. fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
  670. pthread_mutex_init(&fctx->buffer_mutex, NULL);
  671. fctx->delaying = 1;
  672. for (i = 0; i < thread_count; i++) {
  673. AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
  674. PerThreadContext *p = &fctx->threads[i];
  675. pthread_mutex_init(&p->mutex, NULL);
  676. pthread_mutex_init(&p->progress_mutex, NULL);
  677. pthread_cond_init(&p->input_cond, NULL);
  678. pthread_cond_init(&p->progress_cond, NULL);
  679. pthread_cond_init(&p->output_cond, NULL);
  680. p->parent = fctx;
  681. p->avctx = copy;
  682. if (!copy) {
  683. err = AVERROR(ENOMEM);
  684. goto error;
  685. }
  686. *copy = *src;
  687. copy->thread_opaque = p;
  688. copy->pkt = &p->avpkt;
  689. if (!i) {
  690. src = copy;
  691. if (codec->init)
  692. err = codec->init(copy);
  693. update_context_from_thread(avctx, copy, 1);
  694. } else {
  695. copy->priv_data = av_malloc(codec->priv_data_size);
  696. if (!copy->priv_data) {
  697. err = AVERROR(ENOMEM);
  698. goto error;
  699. }
  700. memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
  701. copy->internal = av_malloc(sizeof(AVCodecInternal));
  702. if (!copy->internal) {
  703. err = AVERROR(ENOMEM);
  704. goto error;
  705. }
  706. *copy->internal = *src->internal;
  707. copy->internal->is_copy = 1;
  708. if (codec->init_thread_copy)
  709. err = codec->init_thread_copy(copy);
  710. }
  711. if (err) goto error;
  712. p->thread_init= !pthread_create(&p->thread, NULL, frame_worker_thread, p);
  713. if(!p->thread_init)
  714. goto error;
  715. }
  716. return 0;
  717. error:
  718. frame_thread_free(avctx, i+1);
  719. return err;
  720. }
  721. void ff_thread_flush(AVCodecContext *avctx)
  722. {
  723. FrameThreadContext *fctx = avctx->thread_opaque;
  724. if (!avctx->thread_opaque) return;
  725. park_frame_worker_threads(fctx, avctx->thread_count);
  726. if (fctx->prev_thread) {
  727. if (fctx->prev_thread != &fctx->threads[0])
  728. update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
  729. if (avctx->codec->flush)
  730. avctx->codec->flush(fctx->threads[0].avctx);
  731. }
  732. fctx->next_decoding = fctx->next_finished = 0;
  733. fctx->delaying = 1;
  734. fctx->prev_thread = NULL;
  735. }
  736. static int *allocate_progress(PerThreadContext *p)
  737. {
  738. int i;
  739. for (i = 0; i < MAX_BUFFERS; i++)
  740. if (!p->progress_used[i]) break;
  741. if (i == MAX_BUFFERS) {
  742. av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
  743. return NULL;
  744. }
  745. p->progress_used[i] = 1;
  746. return p->progress[i];
  747. }
  748. int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
  749. {
  750. PerThreadContext *p = avctx->thread_opaque;
  751. int *progress, err;
  752. f->owner = avctx;
  753. ff_init_buffer_info(avctx, f);
  754. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
  755. f->thread_opaque = NULL;
  756. return avctx->get_buffer(avctx, f);
  757. }
  758. if (p->state != STATE_SETTING_UP &&
  759. (avctx->codec->update_thread_context || (!avctx->thread_safe_callbacks &&
  760. avctx->get_buffer != avcodec_default_get_buffer))) {
  761. av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
  762. return -1;
  763. }
  764. pthread_mutex_lock(&p->parent->buffer_mutex);
  765. f->thread_opaque = progress = allocate_progress(p);
  766. if (!progress) {
  767. pthread_mutex_unlock(&p->parent->buffer_mutex);
  768. return -1;
  769. }
  770. progress[0] =
  771. progress[1] = -1;
  772. if (avctx->thread_safe_callbacks ||
  773. avctx->get_buffer == avcodec_default_get_buffer) {
  774. err = avctx->get_buffer(avctx, f);
  775. } else {
  776. p->requested_frame = f;
  777. p->state = STATE_GET_BUFFER;
  778. pthread_mutex_lock(&p->progress_mutex);
  779. pthread_cond_broadcast(&p->progress_cond);
  780. while (p->state != STATE_SETTING_UP)
  781. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  782. err = p->result;
  783. pthread_mutex_unlock(&p->progress_mutex);
  784. if (!avctx->codec->update_thread_context)
  785. ff_thread_finish_setup(avctx);
  786. }
  787. pthread_mutex_unlock(&p->parent->buffer_mutex);
  788. return err;
  789. }
  790. void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
  791. {
  792. PerThreadContext *p = avctx->thread_opaque;
  793. FrameThreadContext *fctx;
  794. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
  795. avctx->release_buffer(avctx, f);
  796. return;
  797. }
  798. if (p->num_released_buffers >= MAX_BUFFERS) {
  799. av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
  800. return;
  801. }
  802. if(avctx->debug & FF_DEBUG_BUFFERS)
  803. av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
  804. fctx = p->parent;
  805. pthread_mutex_lock(&fctx->buffer_mutex);
  806. p->released_buffers[p->num_released_buffers++] = *f;
  807. pthread_mutex_unlock(&fctx->buffer_mutex);
  808. memset(f->data, 0, sizeof(f->data));
  809. }
  810. /**
  811. * Set the threading algorithms used.
  812. *
  813. * Threading requires more than one thread.
  814. * Frame threading requires entire frames to be passed to the codec,
  815. * and introduces extra decoding delay, so is incompatible with low_delay.
  816. *
  817. * @param avctx The context.
  818. */
  819. static void validate_thread_parameters(AVCodecContext *avctx)
  820. {
  821. int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
  822. && !(avctx->flags & CODEC_FLAG_TRUNCATED)
  823. && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
  824. && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
  825. if (avctx->thread_count == 1) {
  826. avctx->active_thread_type = 0;
  827. } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
  828. avctx->active_thread_type = FF_THREAD_FRAME;
  829. } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
  830. avctx->thread_type & FF_THREAD_SLICE) {
  831. avctx->active_thread_type = FF_THREAD_SLICE;
  832. } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
  833. avctx->thread_count = 1;
  834. avctx->active_thread_type = 0;
  835. }
  836. }
  837. int ff_thread_init(AVCodecContext *avctx)
  838. {
  839. if (avctx->thread_opaque) {
  840. av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
  841. return -1;
  842. }
  843. #if HAVE_W32THREADS
  844. w32thread_init();
  845. #endif
  846. if (avctx->codec) {
  847. validate_thread_parameters(avctx);
  848. if (avctx->active_thread_type&FF_THREAD_SLICE)
  849. return thread_init(avctx);
  850. else if (avctx->active_thread_type&FF_THREAD_FRAME)
  851. return frame_thread_init(avctx);
  852. }
  853. return 0;
  854. }
  855. void ff_thread_free(AVCodecContext *avctx)
  856. {
  857. if (avctx->active_thread_type&FF_THREAD_FRAME)
  858. frame_thread_free(avctx, avctx->thread_count);
  859. else
  860. thread_free(avctx);
  861. }