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.

1031 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 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 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. thread_park_workers(c, avctx->thread_count);
  193. return 0;
  194. }
  195. static int 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 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. thread_park_workers(c, thread_count);
  245. avctx->execute = thread_execute;
  246. avctx->execute2 = 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->slice_flags = src->slice_flags;
  352. dst->flags2 = src->flags2;
  353. copy_fields(skip_loop_filter, subtitle_header);
  354. dst->frame_number = src->frame_number;
  355. dst->reordered_opaque = src->reordered_opaque;
  356. if (src->slice_count && src->slice_offset) {
  357. if (dst->slice_count < src->slice_count) {
  358. int *tmp = av_realloc(dst->slice_offset, src->slice_count *
  359. sizeof(*dst->slice_offset));
  360. if (!tmp) {
  361. av_free(dst->slice_offset);
  362. return AVERROR(ENOMEM);
  363. }
  364. dst->slice_offset = tmp;
  365. }
  366. memcpy(dst->slice_offset, src->slice_offset,
  367. src->slice_count * sizeof(*dst->slice_offset));
  368. }
  369. dst->slice_count = src->slice_count;
  370. return 0;
  371. #undef copy_fields
  372. }
  373. /// Releases the buffers that this decoding thread was the last user of.
  374. static void release_delayed_buffers(PerThreadContext *p)
  375. {
  376. FrameThreadContext *fctx = p->parent;
  377. while (p->num_released_buffers > 0) {
  378. AVFrame *f;
  379. pthread_mutex_lock(&fctx->buffer_mutex);
  380. // fix extended data in case the caller screwed it up
  381. av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO);
  382. f = &p->released_buffers[--p->num_released_buffers];
  383. f->extended_data = f->data;
  384. av_frame_unref(f);
  385. pthread_mutex_unlock(&fctx->buffer_mutex);
  386. }
  387. }
  388. static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
  389. {
  390. FrameThreadContext *fctx = p->parent;
  391. PerThreadContext *prev_thread = fctx->prev_thread;
  392. const AVCodec *codec = p->avctx->codec;
  393. if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
  394. pthread_mutex_lock(&p->mutex);
  395. release_delayed_buffers(p);
  396. if (prev_thread) {
  397. int err;
  398. if (prev_thread->state == STATE_SETTING_UP) {
  399. pthread_mutex_lock(&prev_thread->progress_mutex);
  400. while (prev_thread->state == STATE_SETTING_UP)
  401. pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
  402. pthread_mutex_unlock(&prev_thread->progress_mutex);
  403. }
  404. err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
  405. if (err) {
  406. pthread_mutex_unlock(&p->mutex);
  407. return err;
  408. }
  409. }
  410. av_buffer_unref(&p->avpkt.buf);
  411. p->avpkt = *avpkt;
  412. if (avpkt->buf)
  413. p->avpkt.buf = av_buffer_ref(avpkt->buf);
  414. else {
  415. av_fast_malloc(&p->buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
  416. p->avpkt.data = p->buf;
  417. memcpy(p->buf, avpkt->data, avpkt->size);
  418. memset(p->buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  419. }
  420. p->state = STATE_SETTING_UP;
  421. pthread_cond_signal(&p->input_cond);
  422. pthread_mutex_unlock(&p->mutex);
  423. /*
  424. * If the client doesn't have a thread-safe get_buffer(),
  425. * then decoding threads call back to the main thread,
  426. * and it calls back to the client here.
  427. */
  428. FF_DISABLE_DEPRECATION_WARNINGS
  429. if (!p->avctx->thread_safe_callbacks && (
  430. #if FF_API_GET_BUFFER
  431. p->avctx->get_buffer ||
  432. #endif
  433. p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
  434. FF_ENABLE_DEPRECATION_WARNINGS
  435. while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
  436. pthread_mutex_lock(&p->progress_mutex);
  437. while (p->state == STATE_SETTING_UP)
  438. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  439. if (p->state == STATE_GET_BUFFER) {
  440. p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
  441. p->state = STATE_SETTING_UP;
  442. pthread_cond_signal(&p->progress_cond);
  443. }
  444. pthread_mutex_unlock(&p->progress_mutex);
  445. }
  446. }
  447. fctx->prev_thread = p;
  448. fctx->next_decoding++;
  449. return 0;
  450. }
  451. int ff_thread_decode_frame(AVCodecContext *avctx,
  452. AVFrame *picture, int *got_picture_ptr,
  453. AVPacket *avpkt)
  454. {
  455. FrameThreadContext *fctx = avctx->thread_opaque;
  456. int finished = fctx->next_finished;
  457. PerThreadContext *p;
  458. int err;
  459. /*
  460. * Submit a packet to the next decoding thread.
  461. */
  462. p = &fctx->threads[fctx->next_decoding];
  463. err = update_context_from_user(p->avctx, avctx);
  464. if (err) return err;
  465. err = submit_packet(p, avpkt);
  466. if (err) return err;
  467. /*
  468. * If we're still receiving the initial packets, don't return a frame.
  469. */
  470. if (fctx->delaying) {
  471. if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
  472. *got_picture_ptr=0;
  473. if (avpkt->size)
  474. return avpkt->size;
  475. }
  476. /*
  477. * Return the next available frame from the oldest thread.
  478. * If we're at the end of the stream, then we have to skip threads that
  479. * didn't output a frame, because we don't want to accidentally signal
  480. * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
  481. */
  482. do {
  483. p = &fctx->threads[finished++];
  484. if (p->state != STATE_INPUT_READY) {
  485. pthread_mutex_lock(&p->progress_mutex);
  486. while (p->state != STATE_INPUT_READY)
  487. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  488. pthread_mutex_unlock(&p->progress_mutex);
  489. }
  490. av_frame_move_ref(picture, &p->frame);
  491. *got_picture_ptr = p->got_frame;
  492. picture->pkt_dts = p->avpkt.dts;
  493. /*
  494. * A later call with avkpt->size == 0 may loop over all threads,
  495. * including this one, searching for a frame to return before being
  496. * stopped by the "finished != fctx->next_finished" condition.
  497. * Make sure we don't mistakenly return the same frame again.
  498. */
  499. p->got_frame = 0;
  500. if (finished >= avctx->thread_count) finished = 0;
  501. } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
  502. update_context_from_thread(avctx, p->avctx, 1);
  503. if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
  504. fctx->next_finished = finished;
  505. /* return the size of the consumed packet if no error occurred */
  506. return (p->result >= 0) ? avpkt->size : p->result;
  507. }
  508. void ff_thread_report_progress(ThreadFrame *f, int n, int field)
  509. {
  510. PerThreadContext *p;
  511. int *progress = f->progress ? (int*)f->progress->data : NULL;
  512. if (!progress || progress[field] >= n) return;
  513. p = f->owner->thread_opaque;
  514. if (f->owner->debug&FF_DEBUG_THREADS)
  515. av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
  516. pthread_mutex_lock(&p->progress_mutex);
  517. progress[field] = n;
  518. pthread_cond_broadcast(&p->progress_cond);
  519. pthread_mutex_unlock(&p->progress_mutex);
  520. }
  521. void ff_thread_await_progress(ThreadFrame *f, int n, int field)
  522. {
  523. PerThreadContext *p;
  524. int *progress = f->progress ? (int*)f->progress->data : NULL;
  525. if (!progress || progress[field] >= n) return;
  526. p = f->owner->thread_opaque;
  527. if (f->owner->debug&FF_DEBUG_THREADS)
  528. av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
  529. pthread_mutex_lock(&p->progress_mutex);
  530. while (progress[field] < n)
  531. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  532. pthread_mutex_unlock(&p->progress_mutex);
  533. }
  534. void ff_thread_finish_setup(AVCodecContext *avctx) {
  535. PerThreadContext *p = avctx->thread_opaque;
  536. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
  537. pthread_mutex_lock(&p->progress_mutex);
  538. p->state = STATE_SETUP_FINISHED;
  539. pthread_cond_broadcast(&p->progress_cond);
  540. pthread_mutex_unlock(&p->progress_mutex);
  541. }
  542. /// Waits for all threads to finish.
  543. static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
  544. {
  545. int i;
  546. for (i = 0; i < thread_count; i++) {
  547. PerThreadContext *p = &fctx->threads[i];
  548. if (p->state != STATE_INPUT_READY) {
  549. pthread_mutex_lock(&p->progress_mutex);
  550. while (p->state != STATE_INPUT_READY)
  551. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  552. pthread_mutex_unlock(&p->progress_mutex);
  553. }
  554. }
  555. }
  556. static void frame_thread_free(AVCodecContext *avctx, int thread_count)
  557. {
  558. FrameThreadContext *fctx = avctx->thread_opaque;
  559. const AVCodec *codec = avctx->codec;
  560. int i;
  561. park_frame_worker_threads(fctx, thread_count);
  562. if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
  563. update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
  564. fctx->die = 1;
  565. for (i = 0; i < thread_count; i++) {
  566. PerThreadContext *p = &fctx->threads[i];
  567. pthread_mutex_lock(&p->mutex);
  568. pthread_cond_signal(&p->input_cond);
  569. pthread_mutex_unlock(&p->mutex);
  570. if (p->thread_init)
  571. pthread_join(p->thread, NULL);
  572. if (codec->close)
  573. codec->close(p->avctx);
  574. avctx->codec = NULL;
  575. release_delayed_buffers(p);
  576. av_frame_unref(&p->frame);
  577. }
  578. for (i = 0; i < thread_count; i++) {
  579. PerThreadContext *p = &fctx->threads[i];
  580. pthread_mutex_destroy(&p->mutex);
  581. pthread_mutex_destroy(&p->progress_mutex);
  582. pthread_cond_destroy(&p->input_cond);
  583. pthread_cond_destroy(&p->progress_cond);
  584. pthread_cond_destroy(&p->output_cond);
  585. av_buffer_unref(&p->avpkt.buf);
  586. av_freep(&p->buf);
  587. av_freep(&p->released_buffers);
  588. if (i) {
  589. av_freep(&p->avctx->priv_data);
  590. av_freep(&p->avctx->internal);
  591. av_freep(&p->avctx->slice_offset);
  592. }
  593. av_freep(&p->avctx);
  594. }
  595. av_freep(&fctx->threads);
  596. pthread_mutex_destroy(&fctx->buffer_mutex);
  597. av_freep(&avctx->thread_opaque);
  598. }
  599. static int frame_thread_init(AVCodecContext *avctx)
  600. {
  601. int thread_count = avctx->thread_count;
  602. const AVCodec *codec = avctx->codec;
  603. AVCodecContext *src = avctx;
  604. FrameThreadContext *fctx;
  605. int i, err = 0;
  606. if (!thread_count) {
  607. int nb_cpus = av_cpu_count();
  608. av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
  609. // use number of cores + 1 as thread count if there is more than one
  610. if (nb_cpus > 1)
  611. thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
  612. else
  613. thread_count = avctx->thread_count = 1;
  614. }
  615. if (thread_count <= 1) {
  616. avctx->active_thread_type = 0;
  617. return 0;
  618. }
  619. avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
  620. fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
  621. pthread_mutex_init(&fctx->buffer_mutex, NULL);
  622. fctx->delaying = 1;
  623. for (i = 0; i < thread_count; i++) {
  624. AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
  625. PerThreadContext *p = &fctx->threads[i];
  626. pthread_mutex_init(&p->mutex, NULL);
  627. pthread_mutex_init(&p->progress_mutex, NULL);
  628. pthread_cond_init(&p->input_cond, NULL);
  629. pthread_cond_init(&p->progress_cond, NULL);
  630. pthread_cond_init(&p->output_cond, NULL);
  631. p->parent = fctx;
  632. p->avctx = copy;
  633. if (!copy) {
  634. err = AVERROR(ENOMEM);
  635. goto error;
  636. }
  637. *copy = *src;
  638. copy->thread_opaque = p;
  639. copy->pkt = &p->avpkt;
  640. if (!i) {
  641. src = copy;
  642. if (codec->init)
  643. err = codec->init(copy);
  644. update_context_from_thread(avctx, copy, 1);
  645. } else {
  646. copy->priv_data = av_malloc(codec->priv_data_size);
  647. if (!copy->priv_data) {
  648. err = AVERROR(ENOMEM);
  649. goto error;
  650. }
  651. memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
  652. copy->internal = av_malloc(sizeof(AVCodecInternal));
  653. if (!copy->internal) {
  654. err = AVERROR(ENOMEM);
  655. goto error;
  656. }
  657. *copy->internal = *src->internal;
  658. copy->internal->is_copy = 1;
  659. if (codec->init_thread_copy)
  660. err = codec->init_thread_copy(copy);
  661. }
  662. if (err) goto error;
  663. if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
  664. p->thread_init = 1;
  665. }
  666. return 0;
  667. error:
  668. frame_thread_free(avctx, i+1);
  669. return err;
  670. }
  671. void ff_thread_flush(AVCodecContext *avctx)
  672. {
  673. int i;
  674. FrameThreadContext *fctx = avctx->thread_opaque;
  675. if (!avctx->thread_opaque) return;
  676. park_frame_worker_threads(fctx, avctx->thread_count);
  677. if (fctx->prev_thread) {
  678. if (fctx->prev_thread != &fctx->threads[0])
  679. update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
  680. if (avctx->codec->flush)
  681. avctx->codec->flush(fctx->threads[0].avctx);
  682. }
  683. fctx->next_decoding = fctx->next_finished = 0;
  684. fctx->delaying = 1;
  685. fctx->prev_thread = NULL;
  686. for (i = 0; i < avctx->thread_count; i++) {
  687. PerThreadContext *p = &fctx->threads[i];
  688. // Make sure decode flush calls with size=0 won't return old frames
  689. p->got_frame = 0;
  690. av_frame_unref(&p->frame);
  691. release_delayed_buffers(p);
  692. }
  693. }
  694. int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
  695. {
  696. PerThreadContext *p = avctx->thread_opaque;
  697. int err;
  698. f->owner = avctx;
  699. if (!(avctx->active_thread_type & FF_THREAD_FRAME))
  700. return ff_get_buffer(avctx, f->f, flags);
  701. if (p->state != STATE_SETTING_UP &&
  702. (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
  703. av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
  704. return -1;
  705. }
  706. if (avctx->internal->allocate_progress) {
  707. int *progress;
  708. f->progress = av_buffer_alloc(2 * sizeof(int));
  709. if (!f->progress) {
  710. return AVERROR(ENOMEM);
  711. }
  712. progress = (int*)f->progress->data;
  713. progress[0] = progress[1] = -1;
  714. }
  715. pthread_mutex_lock(&p->parent->buffer_mutex);
  716. FF_DISABLE_DEPRECATION_WARNINGS
  717. if (avctx->thread_safe_callbacks || (
  718. #if FF_API_GET_BUFFER
  719. !avctx->get_buffer &&
  720. #endif
  721. avctx->get_buffer2 == avcodec_default_get_buffer2)) {
  722. FF_ENABLE_DEPRECATION_WARNINGS
  723. err = ff_get_buffer(avctx, f->f, flags);
  724. } else {
  725. p->requested_frame = f->f;
  726. p->requested_flags = flags;
  727. p->state = STATE_GET_BUFFER;
  728. pthread_mutex_lock(&p->progress_mutex);
  729. pthread_cond_signal(&p->progress_cond);
  730. while (p->state != STATE_SETTING_UP)
  731. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  732. err = p->result;
  733. pthread_mutex_unlock(&p->progress_mutex);
  734. }
  735. if (!avctx->thread_safe_callbacks && !avctx->codec->update_thread_context)
  736. ff_thread_finish_setup(avctx);
  737. if (err)
  738. av_buffer_unref(&f->progress);
  739. pthread_mutex_unlock(&p->parent->buffer_mutex);
  740. return err;
  741. }
  742. void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
  743. {
  744. PerThreadContext *p = avctx->thread_opaque;
  745. FrameThreadContext *fctx;
  746. AVFrame *dst, *tmp;
  747. FF_DISABLE_DEPRECATION_WARNINGS
  748. int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
  749. avctx->thread_safe_callbacks ||
  750. (
  751. #if FF_API_GET_BUFFER
  752. !avctx->get_buffer &&
  753. #endif
  754. avctx->get_buffer2 == avcodec_default_get_buffer2);
  755. FF_ENABLE_DEPRECATION_WARNINGS
  756. if (!f->f->data[0])
  757. return;
  758. if (avctx->debug & FF_DEBUG_BUFFERS)
  759. av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
  760. av_buffer_unref(&f->progress);
  761. f->owner = NULL;
  762. if (can_direct_free) {
  763. av_frame_unref(f->f);
  764. return;
  765. }
  766. fctx = p->parent;
  767. pthread_mutex_lock(&fctx->buffer_mutex);
  768. if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
  769. goto fail;
  770. tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
  771. (p->num_released_buffers + 1) *
  772. sizeof(*p->released_buffers));
  773. if (!tmp)
  774. goto fail;
  775. p->released_buffers = tmp;
  776. dst = &p->released_buffers[p->num_released_buffers];
  777. av_frame_move_ref(dst, f->f);
  778. p->num_released_buffers++;
  779. fail:
  780. pthread_mutex_unlock(&fctx->buffer_mutex);
  781. }
  782. /**
  783. * Set the threading algorithms used.
  784. *
  785. * Threading requires more than one thread.
  786. * Frame threading requires entire frames to be passed to the codec,
  787. * and introduces extra decoding delay, so is incompatible with low_delay.
  788. *
  789. * @param avctx The context.
  790. */
  791. static void validate_thread_parameters(AVCodecContext *avctx)
  792. {
  793. int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
  794. && !(avctx->flags & CODEC_FLAG_TRUNCATED)
  795. && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
  796. && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
  797. if (avctx->thread_count == 1) {
  798. avctx->active_thread_type = 0;
  799. } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
  800. avctx->active_thread_type = FF_THREAD_FRAME;
  801. } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
  802. avctx->thread_type & FF_THREAD_SLICE) {
  803. avctx->active_thread_type = FF_THREAD_SLICE;
  804. } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
  805. avctx->thread_count = 1;
  806. avctx->active_thread_type = 0;
  807. }
  808. if (avctx->thread_count > MAX_AUTO_THREADS)
  809. av_log(avctx, AV_LOG_WARNING,
  810. "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
  811. avctx->thread_count, MAX_AUTO_THREADS);
  812. }
  813. int ff_thread_init(AVCodecContext *avctx)
  814. {
  815. #if HAVE_W32THREADS
  816. w32thread_init();
  817. #endif
  818. validate_thread_parameters(avctx);
  819. if (avctx->active_thread_type&FF_THREAD_SLICE)
  820. return thread_init_internal(avctx);
  821. else if (avctx->active_thread_type&FF_THREAD_FRAME)
  822. return frame_thread_init(avctx);
  823. return 0;
  824. }
  825. void ff_thread_free(AVCodecContext *avctx)
  826. {
  827. if (avctx->active_thread_type&FF_THREAD_FRAME)
  828. frame_thread_free(avctx, avctx->thread_count);
  829. else
  830. thread_free(avctx);
  831. }