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.

1112 lines
34KB

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