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.

1023 lines
31KB

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