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.

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