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.

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