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.

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