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.

1056 lines
32KB

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