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.

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