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.

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