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.

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