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.

1015 lines
30KB

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