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.

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