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.

1115 lines
35KB

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