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.

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