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.

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