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.

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