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.

986 lines
29KB

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