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.

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