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.

1061 lines
32KB

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