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.

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