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.

1069 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. }
  357. if (for_user) {
  358. dst->coded_frame = src->coded_frame;
  359. } else {
  360. if (dst->codec->update_thread_context)
  361. err = dst->codec->update_thread_context(dst, src);
  362. }
  363. return err;
  364. }
  365. /**
  366. * Update the next thread's AVCodecContext with values set by the user.
  367. *
  368. * @param dst The destination context.
  369. * @param src The source context.
  370. * @return 0 on success, negative error code on failure
  371. */
  372. static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
  373. {
  374. #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
  375. dst->flags = src->flags;
  376. dst->draw_horiz_band= src->draw_horiz_band;
  377. dst->get_buffer2 = src->get_buffer2;
  378. #if FF_API_GET_BUFFER
  379. dst->get_buffer = src->get_buffer;
  380. dst->release_buffer = src->release_buffer;
  381. #endif
  382. dst->opaque = src->opaque;
  383. dst->debug = src->debug;
  384. dst->debug_mv = src->debug_mv;
  385. dst->slice_flags = src->slice_flags;
  386. dst->flags2 = src->flags2;
  387. copy_fields(skip_loop_filter, subtitle_header);
  388. dst->frame_number = src->frame_number;
  389. dst->reordered_opaque = src->reordered_opaque;
  390. if (src->slice_count && src->slice_offset) {
  391. if (dst->slice_count < src->slice_count) {
  392. int *tmp = av_realloc(dst->slice_offset, src->slice_count *
  393. sizeof(*dst->slice_offset));
  394. if (!tmp) {
  395. av_free(dst->slice_offset);
  396. return AVERROR(ENOMEM);
  397. }
  398. dst->slice_offset = tmp;
  399. }
  400. memcpy(dst->slice_offset, src->slice_offset,
  401. src->slice_count * sizeof(*dst->slice_offset));
  402. }
  403. dst->slice_count = src->slice_count;
  404. return 0;
  405. #undef copy_fields
  406. }
  407. /// Releases the buffers that this decoding thread was the last user of.
  408. static void release_delayed_buffers(PerThreadContext *p)
  409. {
  410. FrameThreadContext *fctx = p->parent;
  411. while (p->num_released_buffers > 0) {
  412. AVFrame *f;
  413. pthread_mutex_lock(&fctx->buffer_mutex);
  414. // fix extended data in case the caller screwed it up
  415. av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO);
  416. f = &p->released_buffers[--p->num_released_buffers];
  417. f->extended_data = f->data;
  418. av_frame_unref(f);
  419. pthread_mutex_unlock(&fctx->buffer_mutex);
  420. }
  421. }
  422. static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
  423. {
  424. FrameThreadContext *fctx = p->parent;
  425. PerThreadContext *prev_thread = fctx->prev_thread;
  426. const AVCodec *codec = p->avctx->codec;
  427. if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
  428. pthread_mutex_lock(&p->mutex);
  429. release_delayed_buffers(p);
  430. if (prev_thread) {
  431. int err;
  432. if (prev_thread->state == STATE_SETTING_UP) {
  433. pthread_mutex_lock(&prev_thread->progress_mutex);
  434. while (prev_thread->state == STATE_SETTING_UP)
  435. pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
  436. pthread_mutex_unlock(&prev_thread->progress_mutex);
  437. }
  438. err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
  439. if (err) {
  440. pthread_mutex_unlock(&p->mutex);
  441. return err;
  442. }
  443. }
  444. av_buffer_unref(&p->avpkt.buf);
  445. p->avpkt = *avpkt;
  446. if (avpkt->buf)
  447. p->avpkt.buf = av_buffer_ref(avpkt->buf);
  448. else {
  449. av_fast_malloc(&p->buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
  450. p->avpkt.data = p->buf;
  451. memcpy(p->buf, avpkt->data, avpkt->size);
  452. memset(p->buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  453. }
  454. p->state = STATE_SETTING_UP;
  455. pthread_cond_signal(&p->input_cond);
  456. pthread_mutex_unlock(&p->mutex);
  457. /*
  458. * If the client doesn't have a thread-safe get_buffer(),
  459. * then decoding threads call back to the main thread,
  460. * and it calls back to the client here.
  461. */
  462. if (!p->avctx->thread_safe_callbacks && (
  463. #if FF_API_GET_BUFFER
  464. p->avctx->get_buffer ||
  465. #endif
  466. p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
  467. while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
  468. pthread_mutex_lock(&p->progress_mutex);
  469. while (p->state == STATE_SETTING_UP)
  470. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  471. if (p->state == STATE_GET_BUFFER) {
  472. p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
  473. p->state = STATE_SETTING_UP;
  474. pthread_cond_signal(&p->progress_cond);
  475. }
  476. pthread_mutex_unlock(&p->progress_mutex);
  477. }
  478. }
  479. fctx->prev_thread = p;
  480. fctx->next_decoding++;
  481. return 0;
  482. }
  483. int ff_thread_decode_frame(AVCodecContext *avctx,
  484. AVFrame *picture, int *got_picture_ptr,
  485. AVPacket *avpkt)
  486. {
  487. FrameThreadContext *fctx = avctx->thread_opaque;
  488. int finished = fctx->next_finished;
  489. PerThreadContext *p;
  490. int err;
  491. /*
  492. * Submit a packet to the next decoding thread.
  493. */
  494. p = &fctx->threads[fctx->next_decoding];
  495. err = update_context_from_user(p->avctx, avctx);
  496. if (err) return err;
  497. err = submit_packet(p, avpkt);
  498. if (err) return err;
  499. /*
  500. * If we're still receiving the initial packets, don't return a frame.
  501. */
  502. if (fctx->delaying) {
  503. if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
  504. *got_picture_ptr=0;
  505. if (avpkt->size)
  506. return avpkt->size;
  507. }
  508. /*
  509. * Return the next available frame from the oldest thread.
  510. * If we're at the end of the stream, then we have to skip threads that
  511. * didn't output a frame, because we don't want to accidentally signal
  512. * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
  513. */
  514. do {
  515. p = &fctx->threads[finished++];
  516. if (p->state != STATE_INPUT_READY) {
  517. pthread_mutex_lock(&p->progress_mutex);
  518. while (p->state != STATE_INPUT_READY)
  519. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  520. pthread_mutex_unlock(&p->progress_mutex);
  521. }
  522. av_frame_move_ref(picture, &p->frame);
  523. *got_picture_ptr = p->got_frame;
  524. picture->pkt_dts = p->avpkt.dts;
  525. /*
  526. * A later call with avkpt->size == 0 may loop over all threads,
  527. * including this one, searching for a frame to return before being
  528. * stopped by the "finished != fctx->next_finished" condition.
  529. * Make sure we don't mistakenly return the same frame again.
  530. */
  531. p->got_frame = 0;
  532. if (finished >= avctx->thread_count) finished = 0;
  533. } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
  534. update_context_from_thread(avctx, p->avctx, 1);
  535. if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
  536. fctx->next_finished = finished;
  537. /* return the size of the consumed packet if no error occurred */
  538. return (p->result >= 0) ? avpkt->size : p->result;
  539. }
  540. void ff_thread_report_progress(ThreadFrame *f, int n, int field)
  541. {
  542. PerThreadContext *p;
  543. int *progress = f->progress ? (int*)f->progress->data : NULL;
  544. if (!progress || progress[field] >= n) return;
  545. p = f->owner->thread_opaque;
  546. if (f->owner->debug&FF_DEBUG_THREADS)
  547. av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
  548. pthread_mutex_lock(&p->progress_mutex);
  549. progress[field] = n;
  550. pthread_cond_broadcast(&p->progress_cond);
  551. pthread_mutex_unlock(&p->progress_mutex);
  552. }
  553. void ff_thread_await_progress(ThreadFrame *f, int n, int field)
  554. {
  555. PerThreadContext *p;
  556. int *progress = f->progress ? (int*)f->progress->data : NULL;
  557. if (!progress || progress[field] >= n) return;
  558. p = f->owner->thread_opaque;
  559. if (f->owner->debug&FF_DEBUG_THREADS)
  560. av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
  561. pthread_mutex_lock(&p->progress_mutex);
  562. while (progress[field] < n)
  563. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  564. pthread_mutex_unlock(&p->progress_mutex);
  565. }
  566. void ff_thread_finish_setup(AVCodecContext *avctx) {
  567. PerThreadContext *p = avctx->thread_opaque;
  568. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
  569. pthread_mutex_lock(&p->progress_mutex);
  570. p->state = STATE_SETUP_FINISHED;
  571. pthread_cond_broadcast(&p->progress_cond);
  572. pthread_mutex_unlock(&p->progress_mutex);
  573. }
  574. /// Waits for all threads to finish.
  575. static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
  576. {
  577. int i;
  578. for (i = 0; i < thread_count; i++) {
  579. PerThreadContext *p = &fctx->threads[i];
  580. if (p->state != STATE_INPUT_READY) {
  581. pthread_mutex_lock(&p->progress_mutex);
  582. while (p->state != STATE_INPUT_READY)
  583. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  584. pthread_mutex_unlock(&p->progress_mutex);
  585. }
  586. }
  587. }
  588. static void frame_thread_free(AVCodecContext *avctx, int thread_count)
  589. {
  590. FrameThreadContext *fctx = avctx->thread_opaque;
  591. const AVCodec *codec = avctx->codec;
  592. int i;
  593. park_frame_worker_threads(fctx, thread_count);
  594. if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
  595. update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
  596. fctx->die = 1;
  597. for (i = 0; i < thread_count; i++) {
  598. PerThreadContext *p = &fctx->threads[i];
  599. pthread_mutex_lock(&p->mutex);
  600. pthread_cond_signal(&p->input_cond);
  601. pthread_mutex_unlock(&p->mutex);
  602. if (p->thread_init)
  603. pthread_join(p->thread, NULL);
  604. if (codec->close)
  605. codec->close(p->avctx);
  606. avctx->codec = NULL;
  607. release_delayed_buffers(p);
  608. av_frame_unref(&p->frame);
  609. }
  610. for (i = 0; i < thread_count; i++) {
  611. PerThreadContext *p = &fctx->threads[i];
  612. pthread_mutex_destroy(&p->mutex);
  613. pthread_mutex_destroy(&p->progress_mutex);
  614. pthread_cond_destroy(&p->input_cond);
  615. pthread_cond_destroy(&p->progress_cond);
  616. pthread_cond_destroy(&p->output_cond);
  617. av_buffer_unref(&p->avpkt.buf);
  618. av_freep(&p->buf);
  619. av_freep(&p->released_buffers);
  620. if (i) {
  621. av_freep(&p->avctx->priv_data);
  622. av_freep(&p->avctx->internal);
  623. av_freep(&p->avctx->slice_offset);
  624. }
  625. av_freep(&p->avctx);
  626. }
  627. av_freep(&fctx->threads);
  628. pthread_mutex_destroy(&fctx->buffer_mutex);
  629. av_freep(&avctx->thread_opaque);
  630. }
  631. static int frame_thread_init(AVCodecContext *avctx)
  632. {
  633. int thread_count = avctx->thread_count;
  634. const AVCodec *codec = avctx->codec;
  635. AVCodecContext *src = avctx;
  636. FrameThreadContext *fctx;
  637. int i, err = 0;
  638. if (!thread_count) {
  639. int nb_cpus = get_logical_cpus(avctx);
  640. // use number of cores + 1 as thread count if there is more than one
  641. if (nb_cpus > 1)
  642. thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
  643. else
  644. thread_count = avctx->thread_count = 1;
  645. }
  646. if (thread_count <= 1) {
  647. avctx->active_thread_type = 0;
  648. return 0;
  649. }
  650. avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
  651. fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
  652. pthread_mutex_init(&fctx->buffer_mutex, NULL);
  653. fctx->delaying = 1;
  654. for (i = 0; i < thread_count; i++) {
  655. AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
  656. PerThreadContext *p = &fctx->threads[i];
  657. pthread_mutex_init(&p->mutex, NULL);
  658. pthread_mutex_init(&p->progress_mutex, NULL);
  659. pthread_cond_init(&p->input_cond, NULL);
  660. pthread_cond_init(&p->progress_cond, NULL);
  661. pthread_cond_init(&p->output_cond, NULL);
  662. p->parent = fctx;
  663. p->avctx = copy;
  664. if (!copy) {
  665. err = AVERROR(ENOMEM);
  666. goto error;
  667. }
  668. *copy = *src;
  669. copy->thread_opaque = p;
  670. copy->pkt = &p->avpkt;
  671. if (!i) {
  672. src = copy;
  673. if (codec->init)
  674. err = codec->init(copy);
  675. update_context_from_thread(avctx, copy, 1);
  676. } else {
  677. copy->priv_data = av_malloc(codec->priv_data_size);
  678. if (!copy->priv_data) {
  679. err = AVERROR(ENOMEM);
  680. goto error;
  681. }
  682. memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
  683. copy->internal = av_malloc(sizeof(AVCodecInternal));
  684. if (!copy->internal) {
  685. err = AVERROR(ENOMEM);
  686. goto error;
  687. }
  688. *copy->internal = *src->internal;
  689. copy->internal->is_copy = 1;
  690. if (codec->init_thread_copy)
  691. err = codec->init_thread_copy(copy);
  692. }
  693. if (err) goto error;
  694. if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
  695. p->thread_init = 1;
  696. }
  697. return 0;
  698. error:
  699. frame_thread_free(avctx, i+1);
  700. return err;
  701. }
  702. void ff_thread_flush(AVCodecContext *avctx)
  703. {
  704. int i;
  705. FrameThreadContext *fctx = avctx->thread_opaque;
  706. if (!avctx->thread_opaque) return;
  707. park_frame_worker_threads(fctx, avctx->thread_count);
  708. if (fctx->prev_thread) {
  709. if (fctx->prev_thread != &fctx->threads[0])
  710. update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
  711. if (avctx->codec->flush)
  712. avctx->codec->flush(fctx->threads[0].avctx);
  713. }
  714. fctx->next_decoding = fctx->next_finished = 0;
  715. fctx->delaying = 1;
  716. fctx->prev_thread = NULL;
  717. for (i = 0; i < avctx->thread_count; i++) {
  718. PerThreadContext *p = &fctx->threads[i];
  719. // Make sure decode flush calls with size=0 won't return old frames
  720. p->got_frame = 0;
  721. release_delayed_buffers(p);
  722. }
  723. }
  724. int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
  725. {
  726. PerThreadContext *p = avctx->thread_opaque;
  727. int err;
  728. f->owner = avctx;
  729. if (!(avctx->active_thread_type & FF_THREAD_FRAME))
  730. return ff_get_buffer(avctx, f->f, flags);
  731. if (p->state != STATE_SETTING_UP &&
  732. (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
  733. av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
  734. return -1;
  735. }
  736. if (avctx->internal->allocate_progress) {
  737. int *progress;
  738. f->progress = av_buffer_alloc(2 * sizeof(int));
  739. if (!f->progress) {
  740. return AVERROR(ENOMEM);
  741. }
  742. progress = (int*)f->progress->data;
  743. progress[0] = progress[1] = -1;
  744. }
  745. pthread_mutex_lock(&p->parent->buffer_mutex);
  746. if (avctx->thread_safe_callbacks || (
  747. #if FF_API_GET_BUFFER
  748. !avctx->get_buffer &&
  749. #endif
  750. avctx->get_buffer2 == avcodec_default_get_buffer2)) {
  751. err = ff_get_buffer(avctx, f->f, flags);
  752. } else {
  753. p->requested_frame = f->f;
  754. p->requested_flags = flags;
  755. p->state = STATE_GET_BUFFER;
  756. pthread_mutex_lock(&p->progress_mutex);
  757. pthread_cond_signal(&p->progress_cond);
  758. while (p->state != STATE_SETTING_UP)
  759. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  760. err = p->result;
  761. pthread_mutex_unlock(&p->progress_mutex);
  762. if (!avctx->codec->update_thread_context)
  763. ff_thread_finish_setup(avctx);
  764. }
  765. if (err)
  766. av_buffer_unref(&f->progress);
  767. pthread_mutex_unlock(&p->parent->buffer_mutex);
  768. return err;
  769. }
  770. void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
  771. {
  772. PerThreadContext *p = avctx->thread_opaque;
  773. FrameThreadContext *fctx;
  774. AVFrame *dst, *tmp;
  775. int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
  776. avctx->thread_safe_callbacks ||
  777. (
  778. #if FF_API_GET_BUFFER
  779. !avctx->get_buffer &&
  780. #endif
  781. avctx->get_buffer2 == avcodec_default_get_buffer2);
  782. if (!f->f->data[0])
  783. return;
  784. if (avctx->debug & FF_DEBUG_BUFFERS)
  785. av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
  786. av_buffer_unref(&f->progress);
  787. f->owner = NULL;
  788. if (can_direct_free) {
  789. av_frame_unref(f->f);
  790. return;
  791. }
  792. fctx = p->parent;
  793. pthread_mutex_lock(&fctx->buffer_mutex);
  794. if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
  795. goto fail;
  796. tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
  797. (p->num_released_buffers + 1) *
  798. sizeof(*p->released_buffers));
  799. if (!tmp)
  800. goto fail;
  801. p->released_buffers = tmp;
  802. dst = &p->released_buffers[p->num_released_buffers];
  803. av_frame_move_ref(dst, f->f);
  804. p->num_released_buffers++;
  805. fail:
  806. pthread_mutex_unlock(&fctx->buffer_mutex);
  807. }
  808. /**
  809. * Set the threading algorithms used.
  810. *
  811. * Threading requires more than one thread.
  812. * Frame threading requires entire frames to be passed to the codec,
  813. * and introduces extra decoding delay, so is incompatible with low_delay.
  814. *
  815. * @param avctx The context.
  816. */
  817. static void validate_thread_parameters(AVCodecContext *avctx)
  818. {
  819. int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
  820. && !(avctx->flags & CODEC_FLAG_TRUNCATED)
  821. && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
  822. && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
  823. if (avctx->thread_count == 1) {
  824. avctx->active_thread_type = 0;
  825. } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
  826. avctx->active_thread_type = FF_THREAD_FRAME;
  827. } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
  828. avctx->thread_type & FF_THREAD_SLICE) {
  829. avctx->active_thread_type = FF_THREAD_SLICE;
  830. } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
  831. avctx->thread_count = 1;
  832. avctx->active_thread_type = 0;
  833. }
  834. if (avctx->thread_count > MAX_AUTO_THREADS)
  835. av_log(avctx, AV_LOG_WARNING,
  836. "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
  837. avctx->thread_count, MAX_AUTO_THREADS);
  838. }
  839. int ff_thread_init(AVCodecContext *avctx)
  840. {
  841. if (avctx->thread_opaque) {
  842. av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
  843. return -1;
  844. }
  845. #if HAVE_W32THREADS
  846. w32thread_init();
  847. #endif
  848. if (avctx->codec) {
  849. validate_thread_parameters(avctx);
  850. if (avctx->active_thread_type&FF_THREAD_SLICE)
  851. return thread_init(avctx);
  852. else if (avctx->active_thread_type&FF_THREAD_FRAME)
  853. return frame_thread_init(avctx);
  854. }
  855. return 0;
  856. }
  857. void ff_thread_free(AVCodecContext *avctx)
  858. {
  859. if (avctx->active_thread_type&FF_THREAD_FRAME)
  860. frame_thread_free(avctx, avctx->thread_count);
  861. else
  862. thread_free(avctx);
  863. }