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.

1086 lines
33KB

  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_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/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_GETPROCESSAFFINITYMASK
  147. DWORD_PTR proc_aff, sys_aff;
  148. ret = GetProcessAffinityMask(GetCurrentProcess(), &proc_aff, &sys_aff);
  149. if (ret)
  150. nb_cpus = av_popcount64(proc_aff);
  151. #elif HAVE_SYSCTL && defined(HW_NCPU)
  152. int mib[2] = { CTL_HW, HW_NCPU };
  153. size_t len = sizeof(nb_cpus);
  154. ret = sysctl(mib, 2, &nb_cpus, &len, NULL, 0);
  155. if (ret == -1)
  156. nb_cpus = 0;
  157. #elif HAVE_SYSCONF && defined(_SC_NPROC_ONLN)
  158. nb_cpus = sysconf(_SC_NPROC_ONLN);
  159. #elif HAVE_SYSCONF && defined(_SC_NPROCESSORS_ONLN)
  160. nb_cpus = sysconf(_SC_NPROCESSORS_ONLN);
  161. #endif
  162. av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
  163. if (avctx->height)
  164. nb_cpus = FFMIN(nb_cpus, (avctx->height+15)/16);
  165. return nb_cpus;
  166. }
  167. static void* attribute_align_arg worker(void *v)
  168. {
  169. AVCodecContext *avctx = v;
  170. ThreadContext *c = avctx->thread_opaque;
  171. int our_job = c->job_count;
  172. int thread_count = avctx->thread_count;
  173. int self_id;
  174. pthread_mutex_lock(&c->current_job_lock);
  175. self_id = c->current_job++;
  176. for (;;){
  177. while (our_job >= c->job_count) {
  178. if (c->current_job == thread_count + c->job_count)
  179. pthread_cond_signal(&c->last_job_cond);
  180. pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
  181. our_job = self_id;
  182. if (c->done) {
  183. pthread_mutex_unlock(&c->current_job_lock);
  184. return NULL;
  185. }
  186. }
  187. pthread_mutex_unlock(&c->current_job_lock);
  188. c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
  189. c->func2(avctx, c->args, our_job, self_id);
  190. pthread_mutex_lock(&c->current_job_lock);
  191. our_job = c->current_job++;
  192. }
  193. }
  194. static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
  195. {
  196. pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
  197. pthread_mutex_unlock(&c->current_job_lock);
  198. }
  199. static void thread_free(AVCodecContext *avctx)
  200. {
  201. ThreadContext *c = avctx->thread_opaque;
  202. int i;
  203. pthread_mutex_lock(&c->current_job_lock);
  204. c->done = 1;
  205. pthread_cond_broadcast(&c->current_job_cond);
  206. pthread_mutex_unlock(&c->current_job_lock);
  207. for (i=0; i<avctx->thread_count; i++)
  208. pthread_join(c->workers[i], NULL);
  209. pthread_mutex_destroy(&c->current_job_lock);
  210. pthread_cond_destroy(&c->current_job_cond);
  211. pthread_cond_destroy(&c->last_job_cond);
  212. av_free(c->workers);
  213. av_freep(&avctx->thread_opaque);
  214. }
  215. static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
  216. {
  217. ThreadContext *c= avctx->thread_opaque;
  218. int dummy_ret;
  219. if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
  220. return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
  221. if (job_count <= 0)
  222. return 0;
  223. pthread_mutex_lock(&c->current_job_lock);
  224. c->current_job = avctx->thread_count;
  225. c->job_count = job_count;
  226. c->job_size = job_size;
  227. c->args = arg;
  228. c->func = func;
  229. if (ret) {
  230. c->rets = ret;
  231. c->rets_count = job_count;
  232. } else {
  233. c->rets = &dummy_ret;
  234. c->rets_count = 1;
  235. }
  236. pthread_cond_broadcast(&c->current_job_cond);
  237. avcodec_thread_park_workers(c, avctx->thread_count);
  238. return 0;
  239. }
  240. static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
  241. {
  242. ThreadContext *c= avctx->thread_opaque;
  243. c->func2 = func2;
  244. return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
  245. }
  246. static int thread_init(AVCodecContext *avctx)
  247. {
  248. int i;
  249. ThreadContext *c;
  250. int thread_count = avctx->thread_count;
  251. if (!thread_count) {
  252. int nb_cpus = get_logical_cpus(avctx);
  253. // use number of cores + 1 as thread count if there is more than one
  254. if (nb_cpus > 1)
  255. thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
  256. else
  257. thread_count = avctx->thread_count = 1;
  258. }
  259. if (thread_count <= 1) {
  260. avctx->active_thread_type = 0;
  261. return 0;
  262. }
  263. c = av_mallocz(sizeof(ThreadContext));
  264. if (!c)
  265. return -1;
  266. c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
  267. if (!c->workers) {
  268. av_free(c);
  269. return -1;
  270. }
  271. avctx->thread_opaque = c;
  272. c->current_job = 0;
  273. c->job_count = 0;
  274. c->job_size = 0;
  275. c->done = 0;
  276. pthread_cond_init(&c->current_job_cond, NULL);
  277. pthread_cond_init(&c->last_job_cond, NULL);
  278. pthread_mutex_init(&c->current_job_lock, NULL);
  279. pthread_mutex_lock(&c->current_job_lock);
  280. for (i=0; i<thread_count; i++) {
  281. if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
  282. avctx->thread_count = i;
  283. pthread_mutex_unlock(&c->current_job_lock);
  284. ff_thread_free(avctx);
  285. return -1;
  286. }
  287. }
  288. avcodec_thread_park_workers(c, thread_count);
  289. avctx->execute = avcodec_thread_execute;
  290. avctx->execute2 = avcodec_thread_execute2;
  291. return 0;
  292. }
  293. /**
  294. * Codec worker thread.
  295. *
  296. * Automatically calls ff_thread_finish_setup() if the codec does
  297. * not provide an update_thread_context method, or if the codec returns
  298. * before calling it.
  299. */
  300. static attribute_align_arg void *frame_worker_thread(void *arg)
  301. {
  302. PerThreadContext *p = arg;
  303. FrameThreadContext *fctx = p->parent;
  304. AVCodecContext *avctx = p->avctx;
  305. AVCodec *codec = avctx->codec;
  306. pthread_mutex_lock(&p->mutex);
  307. while (1) {
  308. int i;
  309. while (p->state == STATE_INPUT_READY && !fctx->die)
  310. pthread_cond_wait(&p->input_cond, &p->mutex);
  311. if (fctx->die) break;
  312. if (!codec->update_thread_context && (avctx->thread_safe_callbacks || avctx->get_buffer == avcodec_default_get_buffer))
  313. ff_thread_finish_setup(avctx);
  314. avcodec_get_frame_defaults(&p->frame);
  315. p->got_frame = 0;
  316. p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
  317. if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
  318. pthread_mutex_lock(&p->progress_mutex);
  319. for (i = 0; i < MAX_BUFFERS; i++)
  320. if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != CODEC_ID_H264)) {
  321. p->progress[i][0] = INT_MAX;
  322. p->progress[i][1] = INT_MAX;
  323. }
  324. p->state = STATE_INPUT_READY;
  325. pthread_cond_broadcast(&p->progress_cond);
  326. pthread_cond_signal(&p->output_cond);
  327. pthread_mutex_unlock(&p->progress_mutex);
  328. }
  329. pthread_mutex_unlock(&p->mutex);
  330. return NULL;
  331. }
  332. /**
  333. * Update the next thread's AVCodecContext with values from the reference thread's context.
  334. *
  335. * @param dst The destination context.
  336. * @param src The source context.
  337. * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
  338. */
  339. static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
  340. {
  341. int err = 0;
  342. if (dst != src) {
  343. dst->time_base = src->time_base;
  344. dst->width = src->width;
  345. dst->height = src->height;
  346. dst->pix_fmt = src->pix_fmt;
  347. dst->coded_width = src->coded_width;
  348. dst->coded_height = src->coded_height;
  349. dst->has_b_frames = src->has_b_frames;
  350. dst->idct_algo = src->idct_algo;
  351. dst->bits_per_coded_sample = src->bits_per_coded_sample;
  352. dst->sample_aspect_ratio = src->sample_aspect_ratio;
  353. dst->dtg_active_format = src->dtg_active_format;
  354. dst->profile = src->profile;
  355. dst->level = src->level;
  356. dst->bits_per_raw_sample = src->bits_per_raw_sample;
  357. dst->ticks_per_frame = src->ticks_per_frame;
  358. dst->color_primaries = src->color_primaries;
  359. dst->color_trc = src->color_trc;
  360. dst->colorspace = src->colorspace;
  361. dst->color_range = src->color_range;
  362. dst->chroma_sample_location = src->chroma_sample_location;
  363. }
  364. if (for_user) {
  365. dst->delay = src->thread_count - 1;
  366. dst->coded_frame = src->coded_frame;
  367. } else {
  368. if (dst->codec->update_thread_context)
  369. err = dst->codec->update_thread_context(dst, src);
  370. }
  371. return err;
  372. }
  373. /**
  374. * Update the next thread's AVCodecContext with values set by the user.
  375. *
  376. * @param dst The destination context.
  377. * @param src The source context.
  378. * @return 0 on success, negative error code on failure
  379. */
  380. static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
  381. {
  382. #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
  383. dst->flags = src->flags;
  384. dst->draw_horiz_band= src->draw_horiz_band;
  385. dst->get_buffer = src->get_buffer;
  386. dst->release_buffer = src->release_buffer;
  387. dst->opaque = src->opaque;
  388. dst->debug = src->debug;
  389. dst->debug_mv = src->debug_mv;
  390. dst->slice_flags = src->slice_flags;
  391. dst->flags2 = src->flags2;
  392. copy_fields(skip_loop_filter, subtitle_header);
  393. dst->frame_number = src->frame_number;
  394. dst->reordered_opaque = src->reordered_opaque;
  395. dst->thread_safe_callbacks = src->thread_safe_callbacks;
  396. if (src->slice_count && src->slice_offset) {
  397. if (dst->slice_count < src->slice_count) {
  398. int *tmp = av_realloc(dst->slice_offset, src->slice_count *
  399. sizeof(*dst->slice_offset));
  400. if (!tmp) {
  401. av_free(dst->slice_offset);
  402. return AVERROR(ENOMEM);
  403. }
  404. dst->slice_offset = tmp;
  405. }
  406. memcpy(dst->slice_offset, src->slice_offset,
  407. src->slice_count * sizeof(*dst->slice_offset));
  408. }
  409. dst->slice_count = src->slice_count;
  410. return 0;
  411. #undef copy_fields
  412. }
  413. static void free_progress(AVFrame *f)
  414. {
  415. PerThreadContext *p = f->owner->thread_opaque;
  416. int *progress = f->thread_opaque;
  417. p->progress_used[(progress - p->progress[0]) / 2] = 0;
  418. }
  419. /// Releases the buffers that this decoding thread was the last user of.
  420. static void release_delayed_buffers(PerThreadContext *p)
  421. {
  422. FrameThreadContext *fctx = p->parent;
  423. while (p->num_released_buffers > 0) {
  424. AVFrame *f;
  425. pthread_mutex_lock(&fctx->buffer_mutex);
  426. f = &p->released_buffers[--p->num_released_buffers];
  427. free_progress(f);
  428. f->thread_opaque = NULL;
  429. f->owner->release_buffer(f->owner, f);
  430. pthread_mutex_unlock(&fctx->buffer_mutex);
  431. }
  432. }
  433. static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
  434. {
  435. FrameThreadContext *fctx = p->parent;
  436. PerThreadContext *prev_thread = fctx->prev_thread;
  437. AVCodec *codec = p->avctx->codec;
  438. uint8_t *buf = p->avpkt.data;
  439. if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
  440. pthread_mutex_lock(&p->mutex);
  441. release_delayed_buffers(p);
  442. if (prev_thread) {
  443. int err;
  444. if (prev_thread->state == STATE_SETTING_UP) {
  445. pthread_mutex_lock(&prev_thread->progress_mutex);
  446. while (prev_thread->state == STATE_SETTING_UP)
  447. pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
  448. pthread_mutex_unlock(&prev_thread->progress_mutex);
  449. }
  450. err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
  451. if (err) {
  452. pthread_mutex_unlock(&p->mutex);
  453. return err;
  454. }
  455. }
  456. av_fast_malloc(&buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
  457. p->avpkt = *avpkt;
  458. p->avpkt.data = buf;
  459. memcpy(buf, avpkt->data, avpkt->size);
  460. memset(buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  461. p->state = STATE_SETTING_UP;
  462. pthread_cond_signal(&p->input_cond);
  463. pthread_mutex_unlock(&p->mutex);
  464. /*
  465. * If the client doesn't have a thread-safe get_buffer(),
  466. * then decoding threads call back to the main thread,
  467. * and it calls back to the client here.
  468. */
  469. if (!p->avctx->thread_safe_callbacks &&
  470. p->avctx->get_buffer != avcodec_default_get_buffer) {
  471. while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
  472. pthread_mutex_lock(&p->progress_mutex);
  473. while (p->state == STATE_SETTING_UP)
  474. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  475. if (p->state == STATE_GET_BUFFER) {
  476. p->result = p->avctx->get_buffer(p->avctx, p->requested_frame);
  477. p->state = STATE_SETTING_UP;
  478. pthread_cond_signal(&p->progress_cond);
  479. }
  480. pthread_mutex_unlock(&p->progress_mutex);
  481. }
  482. }
  483. fctx->prev_thread = p;
  484. fctx->next_decoding++;
  485. return 0;
  486. }
  487. int ff_thread_decode_frame(AVCodecContext *avctx,
  488. AVFrame *picture, int *got_picture_ptr,
  489. AVPacket *avpkt)
  490. {
  491. FrameThreadContext *fctx = avctx->thread_opaque;
  492. int finished = fctx->next_finished;
  493. PerThreadContext *p;
  494. int err;
  495. /*
  496. * Submit a packet to the next decoding thread.
  497. */
  498. p = &fctx->threads[fctx->next_decoding];
  499. err = update_context_from_user(p->avctx, avctx);
  500. if (err) return err;
  501. err = submit_packet(p, avpkt);
  502. if (err) return err;
  503. /*
  504. * If we're still receiving the initial packets, don't return a frame.
  505. */
  506. if (fctx->delaying) {
  507. if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
  508. *got_picture_ptr=0;
  509. if (avpkt->size)
  510. return avpkt->size;
  511. }
  512. /*
  513. * Return the next available frame from the oldest thread.
  514. * If we're at the end of the stream, then we have to skip threads that
  515. * didn't output a frame, because we don't want to accidentally signal
  516. * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
  517. */
  518. do {
  519. p = &fctx->threads[finished++];
  520. if (p->state != STATE_INPUT_READY) {
  521. pthread_mutex_lock(&p->progress_mutex);
  522. while (p->state != STATE_INPUT_READY)
  523. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  524. pthread_mutex_unlock(&p->progress_mutex);
  525. }
  526. *picture = p->frame;
  527. *got_picture_ptr = p->got_frame;
  528. picture->pkt_dts = p->avpkt.dts;
  529. /*
  530. * A later call with avkpt->size == 0 may loop over all threads,
  531. * including this one, searching for a frame to return before being
  532. * stopped by the "finished != fctx->next_finished" condition.
  533. * Make sure we don't mistakenly return the same frame again.
  534. */
  535. p->got_frame = 0;
  536. if (finished >= avctx->thread_count) finished = 0;
  537. } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
  538. update_context_from_thread(avctx, p->avctx, 1);
  539. if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
  540. fctx->next_finished = finished;
  541. /* return the size of the consumed packet if no error occurred */
  542. return (p->result >= 0) ? avpkt->size : p->result;
  543. }
  544. void ff_thread_report_progress(AVFrame *f, int n, int field)
  545. {
  546. PerThreadContext *p;
  547. int *progress = f->thread_opaque;
  548. if (!progress || progress[field] >= n) return;
  549. p = f->owner->thread_opaque;
  550. if (f->owner->debug&FF_DEBUG_THREADS)
  551. av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
  552. pthread_mutex_lock(&p->progress_mutex);
  553. progress[field] = n;
  554. pthread_cond_broadcast(&p->progress_cond);
  555. pthread_mutex_unlock(&p->progress_mutex);
  556. }
  557. void ff_thread_await_progress(AVFrame *f, int n, int field)
  558. {
  559. PerThreadContext *p;
  560. int *progress = f->thread_opaque;
  561. if (!progress || progress[field] >= n) return;
  562. p = f->owner->thread_opaque;
  563. if (f->owner->debug&FF_DEBUG_THREADS)
  564. av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
  565. pthread_mutex_lock(&p->progress_mutex);
  566. while (progress[field] < n)
  567. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  568. pthread_mutex_unlock(&p->progress_mutex);
  569. }
  570. void ff_thread_finish_setup(AVCodecContext *avctx) {
  571. PerThreadContext *p = avctx->thread_opaque;
  572. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
  573. if(p->state == STATE_SETUP_FINISHED){
  574. av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
  575. }
  576. pthread_mutex_lock(&p->progress_mutex);
  577. p->state = STATE_SETUP_FINISHED;
  578. pthread_cond_broadcast(&p->progress_cond);
  579. pthread_mutex_unlock(&p->progress_mutex);
  580. }
  581. /// Waits for all threads to finish.
  582. static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
  583. {
  584. int i;
  585. for (i = 0; i < thread_count; i++) {
  586. PerThreadContext *p = &fctx->threads[i];
  587. if (p->state != STATE_INPUT_READY) {
  588. pthread_mutex_lock(&p->progress_mutex);
  589. while (p->state != STATE_INPUT_READY)
  590. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  591. pthread_mutex_unlock(&p->progress_mutex);
  592. }
  593. p->got_frame = 0;
  594. }
  595. }
  596. static void frame_thread_free(AVCodecContext *avctx, int thread_count)
  597. {
  598. FrameThreadContext *fctx = avctx->thread_opaque;
  599. AVCodec *codec = avctx->codec;
  600. int i;
  601. park_frame_worker_threads(fctx, thread_count);
  602. if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
  603. update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
  604. fctx->die = 1;
  605. for (i = 0; i < thread_count; i++) {
  606. PerThreadContext *p = &fctx->threads[i];
  607. pthread_mutex_lock(&p->mutex);
  608. pthread_cond_signal(&p->input_cond);
  609. pthread_mutex_unlock(&p->mutex);
  610. if (p->thread_init)
  611. pthread_join(p->thread, NULL);
  612. p->thread_init=0;
  613. if (codec->close)
  614. codec->close(p->avctx);
  615. avctx->codec = NULL;
  616. release_delayed_buffers(p);
  617. }
  618. for (i = 0; i < thread_count; i++) {
  619. PerThreadContext *p = &fctx->threads[i];
  620. avcodec_default_free_buffers(p->avctx);
  621. pthread_mutex_destroy(&p->mutex);
  622. pthread_mutex_destroy(&p->progress_mutex);
  623. pthread_cond_destroy(&p->input_cond);
  624. pthread_cond_destroy(&p->progress_cond);
  625. pthread_cond_destroy(&p->output_cond);
  626. av_freep(&p->avpkt.data);
  627. if (i) {
  628. av_freep(&p->avctx->priv_data);
  629. av_freep(&p->avctx->internal);
  630. av_freep(&p->avctx->slice_offset);
  631. }
  632. av_freep(&p->avctx);
  633. }
  634. av_freep(&fctx->threads);
  635. pthread_mutex_destroy(&fctx->buffer_mutex);
  636. av_freep(&avctx->thread_opaque);
  637. }
  638. static int frame_thread_init(AVCodecContext *avctx)
  639. {
  640. int thread_count = avctx->thread_count;
  641. AVCodec *codec = avctx->codec;
  642. AVCodecContext *src = avctx;
  643. FrameThreadContext *fctx;
  644. int i, err = 0;
  645. if (!thread_count) {
  646. int nb_cpus = get_logical_cpus(avctx);
  647. if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
  648. nb_cpus = 1;
  649. // use number of cores + 1 as thread count if there is more than one
  650. if (nb_cpus > 1)
  651. thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
  652. else
  653. thread_count = avctx->thread_count = 1;
  654. }
  655. if (thread_count <= 1) {
  656. avctx->active_thread_type = 0;
  657. return 0;
  658. }
  659. avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
  660. fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
  661. pthread_mutex_init(&fctx->buffer_mutex, NULL);
  662. fctx->delaying = 1;
  663. for (i = 0; i < thread_count; i++) {
  664. AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
  665. PerThreadContext *p = &fctx->threads[i];
  666. pthread_mutex_init(&p->mutex, NULL);
  667. pthread_mutex_init(&p->progress_mutex, NULL);
  668. pthread_cond_init(&p->input_cond, NULL);
  669. pthread_cond_init(&p->progress_cond, NULL);
  670. pthread_cond_init(&p->output_cond, NULL);
  671. p->parent = fctx;
  672. p->avctx = copy;
  673. if (!copy) {
  674. err = AVERROR(ENOMEM);
  675. goto error;
  676. }
  677. *copy = *src;
  678. copy->thread_opaque = p;
  679. copy->pkt = &p->avpkt;
  680. if (!i) {
  681. src = copy;
  682. if (codec->init)
  683. err = codec->init(copy);
  684. update_context_from_thread(avctx, copy, 1);
  685. } else {
  686. copy->priv_data = av_malloc(codec->priv_data_size);
  687. if (!copy->priv_data) {
  688. err = AVERROR(ENOMEM);
  689. goto error;
  690. }
  691. memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
  692. copy->internal = av_malloc(sizeof(AVCodecInternal));
  693. if (!copy->internal) {
  694. err = AVERROR(ENOMEM);
  695. goto error;
  696. }
  697. *copy->internal = *src->internal;
  698. copy->internal->is_copy = 1;
  699. if (codec->init_thread_copy)
  700. err = codec->init_thread_copy(copy);
  701. }
  702. if (err) goto error;
  703. err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
  704. p->thread_init= !err;
  705. if(!p->thread_init)
  706. goto error;
  707. }
  708. return 0;
  709. error:
  710. frame_thread_free(avctx, i+1);
  711. return err;
  712. }
  713. void ff_thread_flush(AVCodecContext *avctx)
  714. {
  715. FrameThreadContext *fctx = avctx->thread_opaque;
  716. int i;
  717. if (!avctx->thread_opaque) return;
  718. park_frame_worker_threads(fctx, avctx->thread_count);
  719. if (fctx->prev_thread) {
  720. if (fctx->prev_thread != &fctx->threads[0])
  721. update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
  722. if (avctx->codec->flush)
  723. avctx->codec->flush(fctx->threads[0].avctx);
  724. }
  725. fctx->next_decoding = fctx->next_finished = 0;
  726. fctx->delaying = 1;
  727. fctx->prev_thread = NULL;
  728. for (i = 0; i < avctx->thread_count; i++) {
  729. PerThreadContext *p = &fctx->threads[i];
  730. // Make sure decode flush calls with size=0 won't return old frames
  731. p->got_frame = 0;
  732. release_delayed_buffers(p);
  733. }
  734. }
  735. static int *allocate_progress(PerThreadContext *p)
  736. {
  737. int i;
  738. for (i = 0; i < MAX_BUFFERS; i++)
  739. if (!p->progress_used[i]) break;
  740. if (i == MAX_BUFFERS) {
  741. av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
  742. return NULL;
  743. }
  744. p->progress_used[i] = 1;
  745. return p->progress[i];
  746. }
  747. int ff_thread_can_start_frame(AVCodecContext *avctx)
  748. {
  749. PerThreadContext *p = avctx->thread_opaque;
  750. if ((avctx->active_thread_type&FF_THREAD_FRAME) && p->state != STATE_SETTING_UP &&
  751. (avctx->codec->update_thread_context || (!avctx->thread_safe_callbacks &&
  752. avctx->get_buffer != avcodec_default_get_buffer))) {
  753. return 0;
  754. }
  755. return 1;
  756. }
  757. int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
  758. {
  759. PerThreadContext *p = avctx->thread_opaque;
  760. int *progress, err;
  761. f->owner = avctx;
  762. ff_init_buffer_info(avctx, f);
  763. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
  764. f->thread_opaque = NULL;
  765. return avctx->get_buffer(avctx, f);
  766. }
  767. if (p->state != STATE_SETTING_UP &&
  768. (avctx->codec->update_thread_context || (!avctx->thread_safe_callbacks &&
  769. avctx->get_buffer != avcodec_default_get_buffer))) {
  770. av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
  771. return -1;
  772. }
  773. pthread_mutex_lock(&p->parent->buffer_mutex);
  774. f->thread_opaque = progress = allocate_progress(p);
  775. if (!progress) {
  776. pthread_mutex_unlock(&p->parent->buffer_mutex);
  777. return -1;
  778. }
  779. progress[0] =
  780. progress[1] = -1;
  781. if (avctx->thread_safe_callbacks ||
  782. avctx->get_buffer == avcodec_default_get_buffer) {
  783. err = avctx->get_buffer(avctx, f);
  784. } else {
  785. p->requested_frame = f;
  786. p->state = STATE_GET_BUFFER;
  787. pthread_mutex_lock(&p->progress_mutex);
  788. pthread_cond_broadcast(&p->progress_cond);
  789. while (p->state != STATE_SETTING_UP)
  790. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  791. err = p->result;
  792. pthread_mutex_unlock(&p->progress_mutex);
  793. if (!avctx->codec->update_thread_context)
  794. ff_thread_finish_setup(avctx);
  795. }
  796. if (err) {
  797. free_progress(f);
  798. f->thread_opaque = NULL;
  799. }
  800. pthread_mutex_unlock(&p->parent->buffer_mutex);
  801. return err;
  802. }
  803. void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
  804. {
  805. PerThreadContext *p = avctx->thread_opaque;
  806. FrameThreadContext *fctx;
  807. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
  808. avctx->release_buffer(avctx, f);
  809. return;
  810. }
  811. if (p->num_released_buffers >= MAX_BUFFERS) {
  812. av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
  813. return;
  814. }
  815. if(avctx->debug & FF_DEBUG_BUFFERS)
  816. av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
  817. fctx = p->parent;
  818. pthread_mutex_lock(&fctx->buffer_mutex);
  819. p->released_buffers[p->num_released_buffers++] = *f;
  820. pthread_mutex_unlock(&fctx->buffer_mutex);
  821. memset(f->data, 0, sizeof(f->data));
  822. }
  823. /**
  824. * Set the threading algorithms used.
  825. *
  826. * Threading requires more than one thread.
  827. * Frame threading requires entire frames to be passed to the codec,
  828. * and introduces extra decoding delay, so is incompatible with low_delay.
  829. *
  830. * @param avctx The context.
  831. */
  832. static void validate_thread_parameters(AVCodecContext *avctx)
  833. {
  834. int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
  835. && !(avctx->flags & CODEC_FLAG_TRUNCATED)
  836. && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
  837. && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
  838. if (avctx->thread_count == 1) {
  839. avctx->active_thread_type = 0;
  840. } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
  841. avctx->active_thread_type = FF_THREAD_FRAME;
  842. } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
  843. avctx->thread_type & FF_THREAD_SLICE) {
  844. avctx->active_thread_type = FF_THREAD_SLICE;
  845. } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
  846. avctx->thread_count = 1;
  847. avctx->active_thread_type = 0;
  848. }
  849. }
  850. int ff_thread_init(AVCodecContext *avctx)
  851. {
  852. if (avctx->thread_opaque) {
  853. av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
  854. return -1;
  855. }
  856. #if HAVE_W32THREADS
  857. w32thread_init();
  858. #endif
  859. if (avctx->codec) {
  860. validate_thread_parameters(avctx);
  861. if (avctx->active_thread_type&FF_THREAD_SLICE)
  862. return thread_init(avctx);
  863. else if (avctx->active_thread_type&FF_THREAD_FRAME)
  864. return frame_thread_init(avctx);
  865. }
  866. return 0;
  867. }
  868. void ff_thread_free(AVCodecContext *avctx)
  869. {
  870. if (avctx->active_thread_type&FF_THREAD_FRAME)
  871. frame_thread_free(avctx, avctx->thread_count);
  872. else
  873. thread_free(avctx);
  874. }