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.

1093 lines
33KB

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