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.

909 lines
27KB

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