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.

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