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.

1016 lines
30KB

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