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.

1006 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. picture->width = avctx->width;
  491. picture->height = avctx->height;
  492. picture->format = avctx->pix_fmt;
  493. /*
  494. * A later call with avkpt->size == 0 may loop over all threads,
  495. * including this one, searching for a frame to return before being
  496. * stopped by the "finished != fctx->next_finished" condition.
  497. * Make sure we don't mistakenly return the same frame again.
  498. */
  499. p->got_frame = 0;
  500. if (finished >= avctx->thread_count) finished = 0;
  501. } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
  502. update_context_from_thread(avctx, p->avctx, 1);
  503. if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
  504. fctx->next_finished = finished;
  505. /* return the size of the consumed packet if no error occurred */
  506. return (p->result >= 0) ? avpkt->size : p->result;
  507. }
  508. void ff_thread_report_progress(AVFrame *f, int n, int field)
  509. {
  510. PerThreadContext *p;
  511. int *progress = f->thread_opaque;
  512. if (!progress || progress[field] >= n) return;
  513. p = f->owner->thread_opaque;
  514. if (f->owner->debug&FF_DEBUG_THREADS)
  515. av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
  516. pthread_mutex_lock(&p->progress_mutex);
  517. progress[field] = n;
  518. pthread_cond_broadcast(&p->progress_cond);
  519. pthread_mutex_unlock(&p->progress_mutex);
  520. }
  521. void ff_thread_await_progress(AVFrame *f, int n, int field)
  522. {
  523. PerThreadContext *p;
  524. int *progress = f->thread_opaque;
  525. if (!progress || progress[field] >= n) return;
  526. p = f->owner->thread_opaque;
  527. if (f->owner->debug&FF_DEBUG_THREADS)
  528. av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
  529. pthread_mutex_lock(&p->progress_mutex);
  530. while (progress[field] < n)
  531. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  532. pthread_mutex_unlock(&p->progress_mutex);
  533. }
  534. void ff_thread_finish_setup(AVCodecContext *avctx) {
  535. PerThreadContext *p = avctx->thread_opaque;
  536. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
  537. pthread_mutex_lock(&p->progress_mutex);
  538. p->state = STATE_SETUP_FINISHED;
  539. pthread_cond_broadcast(&p->progress_cond);
  540. pthread_mutex_unlock(&p->progress_mutex);
  541. }
  542. /// Waits for all threads to finish.
  543. static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
  544. {
  545. int i;
  546. for (i = 0; i < thread_count; i++) {
  547. PerThreadContext *p = &fctx->threads[i];
  548. if (p->state != STATE_INPUT_READY) {
  549. pthread_mutex_lock(&p->progress_mutex);
  550. while (p->state != STATE_INPUT_READY)
  551. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  552. pthread_mutex_unlock(&p->progress_mutex);
  553. }
  554. }
  555. }
  556. static void frame_thread_free(AVCodecContext *avctx, int thread_count)
  557. {
  558. FrameThreadContext *fctx = avctx->thread_opaque;
  559. AVCodec *codec = avctx->codec;
  560. int i;
  561. park_frame_worker_threads(fctx, thread_count);
  562. if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
  563. update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
  564. fctx->die = 1;
  565. for (i = 0; i < thread_count; i++) {
  566. PerThreadContext *p = &fctx->threads[i];
  567. pthread_mutex_lock(&p->mutex);
  568. pthread_cond_signal(&p->input_cond);
  569. pthread_mutex_unlock(&p->mutex);
  570. if (p->thread_init)
  571. pthread_join(p->thread, NULL);
  572. if (codec->close)
  573. codec->close(p->avctx);
  574. avctx->codec = NULL;
  575. release_delayed_buffers(p);
  576. }
  577. for (i = 0; i < thread_count; i++) {
  578. PerThreadContext *p = &fctx->threads[i];
  579. avcodec_default_free_buffers(p->avctx);
  580. pthread_mutex_destroy(&p->mutex);
  581. pthread_mutex_destroy(&p->progress_mutex);
  582. pthread_cond_destroy(&p->input_cond);
  583. pthread_cond_destroy(&p->progress_cond);
  584. pthread_cond_destroy(&p->output_cond);
  585. av_freep(&p->avpkt.data);
  586. if (i) {
  587. av_freep(&p->avctx->priv_data);
  588. av_freep(&p->avctx->internal);
  589. }
  590. av_freep(&p->avctx);
  591. }
  592. av_freep(&fctx->threads);
  593. pthread_mutex_destroy(&fctx->buffer_mutex);
  594. av_freep(&avctx->thread_opaque);
  595. }
  596. static int frame_thread_init(AVCodecContext *avctx)
  597. {
  598. int thread_count = avctx->thread_count;
  599. AVCodec *codec = avctx->codec;
  600. AVCodecContext *src = avctx;
  601. FrameThreadContext *fctx;
  602. int i, err = 0;
  603. if (!thread_count) {
  604. int nb_cpus = get_logical_cpus(avctx);
  605. // use number of cores + 1 as thread count if there is motre than one
  606. if (nb_cpus > 1)
  607. thread_count = avctx->thread_count = nb_cpus + 1;
  608. }
  609. if (thread_count <= 1) {
  610. avctx->active_thread_type = 0;
  611. return 0;
  612. }
  613. avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
  614. fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
  615. pthread_mutex_init(&fctx->buffer_mutex, NULL);
  616. fctx->delaying = 1;
  617. for (i = 0; i < thread_count; i++) {
  618. AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
  619. PerThreadContext *p = &fctx->threads[i];
  620. pthread_mutex_init(&p->mutex, NULL);
  621. pthread_mutex_init(&p->progress_mutex, NULL);
  622. pthread_cond_init(&p->input_cond, NULL);
  623. pthread_cond_init(&p->progress_cond, NULL);
  624. pthread_cond_init(&p->output_cond, NULL);
  625. p->parent = fctx;
  626. p->avctx = copy;
  627. if (!copy) {
  628. err = AVERROR(ENOMEM);
  629. goto error;
  630. }
  631. *copy = *src;
  632. copy->thread_opaque = p;
  633. copy->pkt = &p->avpkt;
  634. if (!i) {
  635. src = copy;
  636. if (codec->init)
  637. err = codec->init(copy);
  638. update_context_from_thread(avctx, copy, 1);
  639. } else {
  640. copy->priv_data = av_malloc(codec->priv_data_size);
  641. if (!copy->priv_data) {
  642. err = AVERROR(ENOMEM);
  643. goto error;
  644. }
  645. memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
  646. copy->internal = av_malloc(sizeof(AVCodecInternal));
  647. if (!copy->internal) {
  648. err = AVERROR(ENOMEM);
  649. goto error;
  650. }
  651. *(copy->internal) = *(src->internal);
  652. copy->internal->is_copy = 1;
  653. if (codec->init_thread_copy)
  654. err = codec->init_thread_copy(copy);
  655. }
  656. if (err) goto error;
  657. if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
  658. p->thread_init = 1;
  659. }
  660. return 0;
  661. error:
  662. frame_thread_free(avctx, i+1);
  663. return err;
  664. }
  665. void ff_thread_flush(AVCodecContext *avctx)
  666. {
  667. FrameThreadContext *fctx = avctx->thread_opaque;
  668. if (!avctx->thread_opaque) return;
  669. park_frame_worker_threads(fctx, avctx->thread_count);
  670. if (fctx->prev_thread) {
  671. if (fctx->prev_thread != &fctx->threads[0])
  672. update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
  673. if (avctx->codec->flush)
  674. avctx->codec->flush(fctx->threads[0].avctx);
  675. }
  676. fctx->next_decoding = fctx->next_finished = 0;
  677. fctx->delaying = 1;
  678. fctx->prev_thread = NULL;
  679. }
  680. static int *allocate_progress(PerThreadContext *p)
  681. {
  682. int i;
  683. for (i = 0; i < MAX_BUFFERS; i++)
  684. if (!p->progress_used[i]) break;
  685. if (i == MAX_BUFFERS) {
  686. av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
  687. return NULL;
  688. }
  689. p->progress_used[i] = 1;
  690. return p->progress[i];
  691. }
  692. int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
  693. {
  694. PerThreadContext *p = avctx->thread_opaque;
  695. int *progress, err;
  696. f->owner = avctx;
  697. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
  698. f->thread_opaque = NULL;
  699. return avctx->get_buffer(avctx, f);
  700. }
  701. if (p->state != STATE_SETTING_UP &&
  702. (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
  703. av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
  704. return -1;
  705. }
  706. pthread_mutex_lock(&p->parent->buffer_mutex);
  707. f->thread_opaque = progress = allocate_progress(p);
  708. if (!progress) {
  709. pthread_mutex_unlock(&p->parent->buffer_mutex);
  710. return -1;
  711. }
  712. progress[0] =
  713. progress[1] = -1;
  714. if (avctx->thread_safe_callbacks ||
  715. avctx->get_buffer == avcodec_default_get_buffer) {
  716. err = avctx->get_buffer(avctx, f);
  717. } else {
  718. p->requested_frame = f;
  719. p->state = STATE_GET_BUFFER;
  720. pthread_mutex_lock(&p->progress_mutex);
  721. pthread_cond_signal(&p->progress_cond);
  722. while (p->state != STATE_SETTING_UP)
  723. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  724. err = p->result;
  725. pthread_mutex_unlock(&p->progress_mutex);
  726. if (!avctx->codec->update_thread_context)
  727. ff_thread_finish_setup(avctx);
  728. }
  729. pthread_mutex_unlock(&p->parent->buffer_mutex);
  730. return err;
  731. }
  732. void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
  733. {
  734. PerThreadContext *p = avctx->thread_opaque;
  735. FrameThreadContext *fctx;
  736. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
  737. avctx->release_buffer(avctx, f);
  738. return;
  739. }
  740. if (p->num_released_buffers >= MAX_BUFFERS) {
  741. av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
  742. return;
  743. }
  744. if(avctx->debug & FF_DEBUG_BUFFERS)
  745. av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
  746. fctx = p->parent;
  747. pthread_mutex_lock(&fctx->buffer_mutex);
  748. p->released_buffers[p->num_released_buffers++] = *f;
  749. pthread_mutex_unlock(&fctx->buffer_mutex);
  750. memset(f->data, 0, sizeof(f->data));
  751. }
  752. /**
  753. * Set the threading algorithms used.
  754. *
  755. * Threading requires more than one thread.
  756. * Frame threading requires entire frames to be passed to the codec,
  757. * and introduces extra decoding delay, so is incompatible with low_delay.
  758. *
  759. * @param avctx The context.
  760. */
  761. static void validate_thread_parameters(AVCodecContext *avctx)
  762. {
  763. int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
  764. && !(avctx->flags & CODEC_FLAG_TRUNCATED)
  765. && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
  766. && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
  767. if (avctx->thread_count == 1) {
  768. avctx->active_thread_type = 0;
  769. } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
  770. avctx->active_thread_type = FF_THREAD_FRAME;
  771. } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
  772. avctx->thread_type & FF_THREAD_SLICE) {
  773. avctx->active_thread_type = FF_THREAD_SLICE;
  774. }
  775. }
  776. int ff_thread_init(AVCodecContext *avctx)
  777. {
  778. if (avctx->thread_opaque) {
  779. av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
  780. return -1;
  781. }
  782. #if HAVE_W32THREADS
  783. w32thread_init();
  784. #endif
  785. if (avctx->codec) {
  786. validate_thread_parameters(avctx);
  787. if (avctx->active_thread_type&FF_THREAD_SLICE)
  788. return thread_init(avctx);
  789. else if (avctx->active_thread_type&FF_THREAD_FRAME)
  790. return frame_thread_init(avctx);
  791. }
  792. return 0;
  793. }
  794. void ff_thread_free(AVCodecContext *avctx)
  795. {
  796. if (avctx->active_thread_type&FF_THREAD_FRAME)
  797. frame_thread_free(avctx, avctx->thread_count);
  798. else
  799. thread_free(avctx);
  800. }