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.

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