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.

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