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.

1075 lines
33KB

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