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.

935 lines
28KB

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