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.

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