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.

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