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.

1046 lines
31KB

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