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.

1137 lines
35KB

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