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.

1140 lines
35KB

  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/avassert.h"
  55. #include "libavutil/common.h"
  56. #if HAVE_PTHREADS
  57. #include <pthread.h>
  58. #elif HAVE_W32THREADS
  59. #include "w32pthreads.h"
  60. #elif HAVE_OS2THREADS
  61. #include "os2threads.h"
  62. #endif
  63. typedef int (action_func)(AVCodecContext *c, void *arg);
  64. typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
  65. typedef struct ThreadContext {
  66. pthread_t *workers;
  67. action_func *func;
  68. action_func2 *func2;
  69. void *args;
  70. int *rets;
  71. int rets_count;
  72. int job_count;
  73. int job_size;
  74. pthread_cond_t last_job_cond;
  75. pthread_cond_t current_job_cond;
  76. pthread_mutex_t current_job_lock;
  77. int current_job;
  78. unsigned int current_execute;
  79. int done;
  80. } ThreadContext;
  81. /**
  82. * Context used by codec threads and stored in their AVCodecContext thread_opaque.
  83. */
  84. typedef struct PerThreadContext {
  85. struct FrameThreadContext *parent;
  86. pthread_t thread;
  87. int thread_init;
  88. pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
  89. pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
  90. pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
  91. pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
  92. pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
  93. AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
  94. AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
  95. uint8_t *buf; ///< backup storage for packet data when the input packet is not refcounted
  96. int allocated_buf_size; ///< Size allocated for buf
  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;
  114. int num_released_buffers;
  115. int released_buffers_allocated;
  116. AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
  117. int requested_flags; ///< flags passed to get_buffer() for requested_frame
  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. int ff_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 = ff_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. const AVCodec *codec = avctx->codec;
  312. pthread_mutex_lock(&p->mutex);
  313. while (1) {
  314. while (p->state == STATE_INPUT_READY && !fctx->die)
  315. pthread_cond_wait(&p->input_cond, &p->mutex);
  316. if (fctx->die) break;
  317. if (!codec->update_thread_context && (avctx->thread_safe_callbacks || (
  318. #if FF_API_GET_BUFFER
  319. !avctx->get_buffer &&
  320. #endif
  321. avctx->get_buffer2 == avcodec_default_get_buffer2)))
  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. #if 0 //BUFREF-FIXME
  332. for (i = 0; i < MAX_BUFFERS; i++)
  333. if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != AV_CODEC_ID_H264)) {
  334. p->progress[i][0] = INT_MAX;
  335. p->progress[i][1] = INT_MAX;
  336. }
  337. #endif
  338. p->state = STATE_INPUT_READY;
  339. pthread_cond_broadcast(&p->progress_cond);
  340. pthread_cond_signal(&p->output_cond);
  341. pthread_mutex_unlock(&p->progress_mutex);
  342. }
  343. pthread_mutex_unlock(&p->mutex);
  344. return NULL;
  345. }
  346. /**
  347. * Update the next thread's AVCodecContext with values from the reference thread's context.
  348. *
  349. * @param dst The destination context.
  350. * @param src The source context.
  351. * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
  352. */
  353. static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
  354. {
  355. int err = 0;
  356. if (dst != src) {
  357. dst->time_base = src->time_base;
  358. dst->width = src->width;
  359. dst->height = src->height;
  360. dst->pix_fmt = src->pix_fmt;
  361. dst->coded_width = src->coded_width;
  362. dst->coded_height = src->coded_height;
  363. dst->has_b_frames = src->has_b_frames;
  364. dst->idct_algo = src->idct_algo;
  365. dst->bits_per_coded_sample = src->bits_per_coded_sample;
  366. dst->sample_aspect_ratio = src->sample_aspect_ratio;
  367. dst->dtg_active_format = src->dtg_active_format;
  368. dst->profile = src->profile;
  369. dst->level = src->level;
  370. dst->bits_per_raw_sample = src->bits_per_raw_sample;
  371. dst->ticks_per_frame = src->ticks_per_frame;
  372. dst->color_primaries = src->color_primaries;
  373. dst->color_trc = src->color_trc;
  374. dst->colorspace = src->colorspace;
  375. dst->color_range = src->color_range;
  376. dst->chroma_sample_location = src->chroma_sample_location;
  377. dst->hwaccel = src->hwaccel;
  378. dst->hwaccel_context = src->hwaccel_context;
  379. }
  380. if (for_user) {
  381. dst->delay = src->thread_count - 1;
  382. dst->coded_frame = src->coded_frame;
  383. } else {
  384. if (dst->codec->update_thread_context)
  385. err = dst->codec->update_thread_context(dst, src);
  386. }
  387. return err;
  388. }
  389. /**
  390. * Update the next thread's AVCodecContext with values set by the user.
  391. *
  392. * @param dst The destination context.
  393. * @param src The source context.
  394. * @return 0 on success, negative error code on failure
  395. */
  396. static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
  397. {
  398. #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
  399. dst->flags = src->flags;
  400. dst->draw_horiz_band= src->draw_horiz_band;
  401. dst->get_buffer2 = src->get_buffer2;
  402. #if FF_API_GET_BUFFER
  403. dst->get_buffer = src->get_buffer;
  404. dst->release_buffer = src->release_buffer;
  405. #endif
  406. dst->opaque = src->opaque;
  407. dst->debug = src->debug;
  408. dst->debug_mv = src->debug_mv;
  409. dst->slice_flags = src->slice_flags;
  410. dst->flags2 = src->flags2;
  411. copy_fields(skip_loop_filter, subtitle_header);
  412. dst->frame_number = src->frame_number;
  413. dst->reordered_opaque = src->reordered_opaque;
  414. dst->thread_safe_callbacks = src->thread_safe_callbacks;
  415. if (src->slice_count && src->slice_offset) {
  416. if (dst->slice_count < src->slice_count) {
  417. int *tmp = av_realloc(dst->slice_offset, src->slice_count *
  418. sizeof(*dst->slice_offset));
  419. if (!tmp) {
  420. av_free(dst->slice_offset);
  421. return AVERROR(ENOMEM);
  422. }
  423. dst->slice_offset = tmp;
  424. }
  425. memcpy(dst->slice_offset, src->slice_offset,
  426. src->slice_count * sizeof(*dst->slice_offset));
  427. }
  428. dst->slice_count = src->slice_count;
  429. return 0;
  430. #undef copy_fields
  431. }
  432. /// Releases the buffers that this decoding thread was the last user of.
  433. static void release_delayed_buffers(PerThreadContext *p)
  434. {
  435. FrameThreadContext *fctx = p->parent;
  436. while (p->num_released_buffers > 0) {
  437. AVFrame *f;
  438. pthread_mutex_lock(&fctx->buffer_mutex);
  439. // fix extended data in case the caller screwed it up
  440. av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO);
  441. f = &p->released_buffers[--p->num_released_buffers];
  442. f->extended_data = f->data;
  443. av_frame_unref(f);
  444. pthread_mutex_unlock(&fctx->buffer_mutex);
  445. }
  446. }
  447. static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
  448. {
  449. FrameThreadContext *fctx = p->parent;
  450. PerThreadContext *prev_thread = fctx->prev_thread;
  451. const AVCodec *codec = p->avctx->codec;
  452. if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
  453. pthread_mutex_lock(&p->mutex);
  454. release_delayed_buffers(p);
  455. if (prev_thread) {
  456. int err;
  457. if (prev_thread->state == STATE_SETTING_UP) {
  458. pthread_mutex_lock(&prev_thread->progress_mutex);
  459. while (prev_thread->state == STATE_SETTING_UP)
  460. pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
  461. pthread_mutex_unlock(&prev_thread->progress_mutex);
  462. }
  463. err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
  464. if (err) {
  465. pthread_mutex_unlock(&p->mutex);
  466. return err;
  467. }
  468. }
  469. av_buffer_unref(&p->avpkt.buf);
  470. p->avpkt = *avpkt;
  471. if (avpkt->buf)
  472. p->avpkt.buf = av_buffer_ref(avpkt->buf);
  473. else {
  474. av_fast_malloc(&p->buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
  475. p->avpkt.data = p->buf;
  476. memcpy(p->buf, avpkt->data, avpkt->size);
  477. memset(p->buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  478. }
  479. p->state = STATE_SETTING_UP;
  480. pthread_cond_signal(&p->input_cond);
  481. pthread_mutex_unlock(&p->mutex);
  482. /*
  483. * If the client doesn't have a thread-safe get_buffer(),
  484. * then decoding threads call back to the main thread,
  485. * and it calls back to the client here.
  486. */
  487. if (!p->avctx->thread_safe_callbacks && (
  488. #if FF_API_GET_BUFFER
  489. p->avctx->get_buffer ||
  490. #endif
  491. p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
  492. while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
  493. pthread_mutex_lock(&p->progress_mutex);
  494. while (p->state == STATE_SETTING_UP)
  495. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  496. if (p->state == STATE_GET_BUFFER) {
  497. p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
  498. p->state = STATE_SETTING_UP;
  499. pthread_cond_signal(&p->progress_cond);
  500. }
  501. pthread_mutex_unlock(&p->progress_mutex);
  502. }
  503. }
  504. fctx->prev_thread = p;
  505. fctx->next_decoding++;
  506. return 0;
  507. }
  508. int ff_thread_decode_frame(AVCodecContext *avctx,
  509. AVFrame *picture, int *got_picture_ptr,
  510. AVPacket *avpkt)
  511. {
  512. FrameThreadContext *fctx = avctx->thread_opaque;
  513. int finished = fctx->next_finished;
  514. PerThreadContext *p;
  515. int err;
  516. /*
  517. * Submit a packet to the next decoding thread.
  518. */
  519. p = &fctx->threads[fctx->next_decoding];
  520. err = update_context_from_user(p->avctx, avctx);
  521. if (err) return err;
  522. err = submit_packet(p, avpkt);
  523. if (err) return err;
  524. /*
  525. * If we're still receiving the initial packets, don't return a frame.
  526. */
  527. if (fctx->delaying) {
  528. if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
  529. *got_picture_ptr=0;
  530. if (avpkt->size)
  531. return avpkt->size;
  532. }
  533. /*
  534. * Return the next available frame from the oldest thread.
  535. * If we're at the end of the stream, then we have to skip threads that
  536. * didn't output a frame, because we don't want to accidentally signal
  537. * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
  538. */
  539. do {
  540. p = &fctx->threads[finished++];
  541. if (p->state != STATE_INPUT_READY) {
  542. pthread_mutex_lock(&p->progress_mutex);
  543. while (p->state != STATE_INPUT_READY)
  544. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  545. pthread_mutex_unlock(&p->progress_mutex);
  546. }
  547. av_frame_move_ref(picture, &p->frame);
  548. *got_picture_ptr = p->got_frame;
  549. picture->pkt_dts = p->avpkt.dts;
  550. /*
  551. * A later call with avkpt->size == 0 may loop over all threads,
  552. * including this one, searching for a frame to return before being
  553. * stopped by the "finished != fctx->next_finished" condition.
  554. * Make sure we don't mistakenly return the same frame again.
  555. */
  556. p->got_frame = 0;
  557. if (finished >= avctx->thread_count) finished = 0;
  558. } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
  559. update_context_from_thread(avctx, p->avctx, 1);
  560. if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
  561. fctx->next_finished = finished;
  562. /* return the size of the consumed packet if no error occurred */
  563. return (p->result >= 0) ? avpkt->size : p->result;
  564. }
  565. void ff_thread_report_progress(ThreadFrame *f, int n, int field)
  566. {
  567. PerThreadContext *p;
  568. volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
  569. if (!progress || progress[field] >= n) return;
  570. p = f->owner->thread_opaque;
  571. if (f->owner->debug&FF_DEBUG_THREADS)
  572. av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
  573. pthread_mutex_lock(&p->progress_mutex);
  574. progress[field] = n;
  575. pthread_cond_broadcast(&p->progress_cond);
  576. pthread_mutex_unlock(&p->progress_mutex);
  577. }
  578. void ff_thread_await_progress(ThreadFrame *f, int n, int field)
  579. {
  580. PerThreadContext *p;
  581. volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
  582. if (!progress || progress[field] >= n) return;
  583. p = f->owner->thread_opaque;
  584. if (f->owner->debug&FF_DEBUG_THREADS)
  585. av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
  586. pthread_mutex_lock(&p->progress_mutex);
  587. while (progress[field] < n)
  588. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  589. pthread_mutex_unlock(&p->progress_mutex);
  590. }
  591. void ff_thread_finish_setup(AVCodecContext *avctx) {
  592. PerThreadContext *p = avctx->thread_opaque;
  593. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
  594. if(p->state == STATE_SETUP_FINISHED){
  595. av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
  596. }
  597. pthread_mutex_lock(&p->progress_mutex);
  598. p->state = STATE_SETUP_FINISHED;
  599. pthread_cond_broadcast(&p->progress_cond);
  600. pthread_mutex_unlock(&p->progress_mutex);
  601. }
  602. /// Waits for all threads to finish.
  603. static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
  604. {
  605. int i;
  606. for (i = 0; i < thread_count; i++) {
  607. PerThreadContext *p = &fctx->threads[i];
  608. if (p->state != STATE_INPUT_READY) {
  609. pthread_mutex_lock(&p->progress_mutex);
  610. while (p->state != STATE_INPUT_READY)
  611. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  612. pthread_mutex_unlock(&p->progress_mutex);
  613. }
  614. p->got_frame = 0;
  615. }
  616. }
  617. static void frame_thread_free(AVCodecContext *avctx, int thread_count)
  618. {
  619. FrameThreadContext *fctx = avctx->thread_opaque;
  620. const AVCodec *codec = avctx->codec;
  621. int i;
  622. park_frame_worker_threads(fctx, thread_count);
  623. if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
  624. if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
  625. av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
  626. fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
  627. fctx->threads->avctx->internal->is_copy = 1;
  628. }
  629. fctx->die = 1;
  630. for (i = 0; i < thread_count; i++) {
  631. PerThreadContext *p = &fctx->threads[i];
  632. pthread_mutex_lock(&p->mutex);
  633. pthread_cond_signal(&p->input_cond);
  634. pthread_mutex_unlock(&p->mutex);
  635. if (p->thread_init)
  636. pthread_join(p->thread, NULL);
  637. p->thread_init=0;
  638. if (codec->close)
  639. codec->close(p->avctx);
  640. avctx->codec = NULL;
  641. release_delayed_buffers(p);
  642. av_frame_unref(&p->frame);
  643. }
  644. for (i = 0; i < thread_count; i++) {
  645. PerThreadContext *p = &fctx->threads[i];
  646. pthread_mutex_destroy(&p->mutex);
  647. pthread_mutex_destroy(&p->progress_mutex);
  648. pthread_cond_destroy(&p->input_cond);
  649. pthread_cond_destroy(&p->progress_cond);
  650. pthread_cond_destroy(&p->output_cond);
  651. av_buffer_unref(&p->avpkt.buf);
  652. av_freep(&p->buf);
  653. av_freep(&p->released_buffers);
  654. if (i) {
  655. av_freep(&p->avctx->priv_data);
  656. av_freep(&p->avctx->internal);
  657. av_freep(&p->avctx->slice_offset);
  658. }
  659. av_freep(&p->avctx);
  660. }
  661. av_freep(&fctx->threads);
  662. pthread_mutex_destroy(&fctx->buffer_mutex);
  663. av_freep(&avctx->thread_opaque);
  664. }
  665. static int frame_thread_init(AVCodecContext *avctx)
  666. {
  667. int thread_count = avctx->thread_count;
  668. const AVCodec *codec = avctx->codec;
  669. AVCodecContext *src = avctx;
  670. FrameThreadContext *fctx;
  671. int i, err = 0;
  672. if (!thread_count) {
  673. int nb_cpus = ff_get_logical_cpus(avctx);
  674. if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
  675. nb_cpus = 1;
  676. // use number of cores + 1 as thread count if there is more than one
  677. if (nb_cpus > 1)
  678. thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
  679. else
  680. thread_count = avctx->thread_count = 1;
  681. }
  682. if (thread_count <= 1) {
  683. avctx->active_thread_type = 0;
  684. return 0;
  685. }
  686. avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
  687. fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
  688. pthread_mutex_init(&fctx->buffer_mutex, NULL);
  689. fctx->delaying = 1;
  690. for (i = 0; i < thread_count; i++) {
  691. AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
  692. PerThreadContext *p = &fctx->threads[i];
  693. pthread_mutex_init(&p->mutex, NULL);
  694. pthread_mutex_init(&p->progress_mutex, NULL);
  695. pthread_cond_init(&p->input_cond, NULL);
  696. pthread_cond_init(&p->progress_cond, NULL);
  697. pthread_cond_init(&p->output_cond, NULL);
  698. p->parent = fctx;
  699. p->avctx = copy;
  700. if (!copy) {
  701. err = AVERROR(ENOMEM);
  702. goto error;
  703. }
  704. *copy = *src;
  705. copy->thread_opaque = p;
  706. copy->pkt = &p->avpkt;
  707. if (!i) {
  708. src = copy;
  709. if (codec->init)
  710. err = codec->init(copy);
  711. update_context_from_thread(avctx, copy, 1);
  712. } else {
  713. copy->priv_data = av_malloc(codec->priv_data_size);
  714. if (!copy->priv_data) {
  715. err = AVERROR(ENOMEM);
  716. goto error;
  717. }
  718. memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
  719. copy->internal = av_malloc(sizeof(AVCodecInternal));
  720. if (!copy->internal) {
  721. err = AVERROR(ENOMEM);
  722. goto error;
  723. }
  724. *copy->internal = *src->internal;
  725. copy->internal->is_copy = 1;
  726. if (codec->init_thread_copy)
  727. err = codec->init_thread_copy(copy);
  728. }
  729. if (err) goto error;
  730. err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
  731. p->thread_init= !err;
  732. if(!p->thread_init)
  733. goto error;
  734. }
  735. return 0;
  736. error:
  737. frame_thread_free(avctx, i+1);
  738. return err;
  739. }
  740. void ff_thread_flush(AVCodecContext *avctx)
  741. {
  742. int i;
  743. FrameThreadContext *fctx = avctx->thread_opaque;
  744. if (!avctx->thread_opaque) return;
  745. park_frame_worker_threads(fctx, avctx->thread_count);
  746. if (fctx->prev_thread) {
  747. if (fctx->prev_thread != &fctx->threads[0])
  748. update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
  749. if (avctx->codec->flush)
  750. avctx->codec->flush(fctx->threads[0].avctx);
  751. }
  752. fctx->next_decoding = fctx->next_finished = 0;
  753. fctx->delaying = 1;
  754. fctx->prev_thread = NULL;
  755. for (i = 0; i < avctx->thread_count; i++) {
  756. PerThreadContext *p = &fctx->threads[i];
  757. // Make sure decode flush calls with size=0 won't return old frames
  758. p->got_frame = 0;
  759. av_frame_unref(&p->frame);
  760. release_delayed_buffers(p);
  761. }
  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. #if FF_API_GET_BUFFER
  769. avctx->get_buffer ||
  770. #endif
  771. avctx->get_buffer2 != avcodec_default_get_buffer2)))) {
  772. return 0;
  773. }
  774. return 1;
  775. }
  776. static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
  777. {
  778. PerThreadContext *p = avctx->thread_opaque;
  779. int err;
  780. f->owner = avctx;
  781. ff_init_buffer_info(avctx, f->f);
  782. if (!(avctx->active_thread_type & FF_THREAD_FRAME))
  783. return ff_get_buffer(avctx, f->f, flags);
  784. if (p->state != STATE_SETTING_UP &&
  785. (avctx->codec->update_thread_context || (!avctx->thread_safe_callbacks && (
  786. #if FF_API_GET_BUFFER
  787. avctx->get_buffer ||
  788. #endif
  789. avctx->get_buffer2 != avcodec_default_get_buffer2)))) {
  790. av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
  791. return -1;
  792. }
  793. if (avctx->internal->allocate_progress) {
  794. int *progress;
  795. f->progress = av_buffer_alloc(2 * sizeof(int));
  796. if (!f->progress) {
  797. return AVERROR(ENOMEM);
  798. }
  799. progress = (int*)f->progress->data;
  800. progress[0] = progress[1] = -1;
  801. }
  802. pthread_mutex_lock(&p->parent->buffer_mutex);
  803. if (avctx->thread_safe_callbacks || (
  804. #if FF_API_GET_BUFFER
  805. !avctx->get_buffer &&
  806. #endif
  807. avctx->get_buffer2 == avcodec_default_get_buffer2)) {
  808. err = ff_get_buffer(avctx, f->f, flags);
  809. } else {
  810. pthread_mutex_lock(&p->progress_mutex);
  811. p->requested_frame = f->f;
  812. p->requested_flags = flags;
  813. p->state = STATE_GET_BUFFER;
  814. pthread_cond_broadcast(&p->progress_cond);
  815. while (p->state != STATE_SETTING_UP)
  816. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  817. err = p->result;
  818. pthread_mutex_unlock(&p->progress_mutex);
  819. if (!avctx->codec->update_thread_context)
  820. ff_thread_finish_setup(avctx);
  821. }
  822. if (err)
  823. av_buffer_unref(&f->progress);
  824. pthread_mutex_unlock(&p->parent->buffer_mutex);
  825. return err;
  826. }
  827. int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
  828. {
  829. int ret = thread_get_buffer_internal(avctx, f, flags);
  830. if (ret < 0)
  831. av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
  832. return ret;
  833. }
  834. void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
  835. {
  836. PerThreadContext *p = avctx->thread_opaque;
  837. FrameThreadContext *fctx;
  838. AVFrame *dst, *tmp;
  839. int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
  840. avctx->thread_safe_callbacks ||
  841. (
  842. #if FF_API_GET_BUFFER
  843. !avctx->get_buffer &&
  844. #endif
  845. avctx->get_buffer2 == avcodec_default_get_buffer2);
  846. if (!f->f->data[0])
  847. return;
  848. if (avctx->debug & FF_DEBUG_BUFFERS)
  849. av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
  850. av_buffer_unref(&f->progress);
  851. f->owner = NULL;
  852. if (can_direct_free) {
  853. av_frame_unref(f->f);
  854. return;
  855. }
  856. fctx = p->parent;
  857. pthread_mutex_lock(&fctx->buffer_mutex);
  858. if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
  859. goto fail;
  860. tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
  861. (p->num_released_buffers + 1) *
  862. sizeof(*p->released_buffers));
  863. if (!tmp)
  864. goto fail;
  865. p->released_buffers = tmp;
  866. dst = &p->released_buffers[p->num_released_buffers];
  867. av_frame_move_ref(dst, f->f);
  868. p->num_released_buffers++;
  869. fail:
  870. pthread_mutex_unlock(&fctx->buffer_mutex);
  871. }
  872. /**
  873. * Set the threading algorithms used.
  874. *
  875. * Threading requires more than one thread.
  876. * Frame threading requires entire frames to be passed to the codec,
  877. * and introduces extra decoding delay, so is incompatible with low_delay.
  878. *
  879. * @param avctx The context.
  880. */
  881. static void validate_thread_parameters(AVCodecContext *avctx)
  882. {
  883. int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
  884. && !(avctx->flags & CODEC_FLAG_TRUNCATED)
  885. && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
  886. && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
  887. if (avctx->thread_count == 1) {
  888. avctx->active_thread_type = 0;
  889. } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
  890. avctx->active_thread_type = FF_THREAD_FRAME;
  891. } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
  892. avctx->thread_type & FF_THREAD_SLICE) {
  893. avctx->active_thread_type = FF_THREAD_SLICE;
  894. } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
  895. avctx->thread_count = 1;
  896. avctx->active_thread_type = 0;
  897. }
  898. if (avctx->thread_count > MAX_AUTO_THREADS)
  899. av_log(avctx, AV_LOG_WARNING,
  900. "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
  901. avctx->thread_count, MAX_AUTO_THREADS);
  902. }
  903. int ff_thread_init(AVCodecContext *avctx)
  904. {
  905. if (avctx->thread_opaque) {
  906. av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
  907. return -1;
  908. }
  909. #if HAVE_W32THREADS
  910. w32thread_init();
  911. #endif
  912. if (avctx->codec) {
  913. validate_thread_parameters(avctx);
  914. if (avctx->active_thread_type&FF_THREAD_SLICE)
  915. return thread_init(avctx);
  916. else if (avctx->active_thread_type&FF_THREAD_FRAME)
  917. return frame_thread_init(avctx);
  918. }
  919. return 0;
  920. }
  921. void ff_thread_free(AVCodecContext *avctx)
  922. {
  923. if (avctx->active_thread_type&FF_THREAD_FRAME)
  924. frame_thread_free(avctx, avctx->thread_count);
  925. else
  926. thread_free(avctx);
  927. }