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.

937 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. dst->has_b_frames += src->thread_count - 1;
  301. } else {
  302. if (dst->codec->update_thread_context)
  303. err = dst->codec->update_thread_context(dst, src);
  304. }
  305. return err;
  306. }
  307. /**
  308. * Update the next thread's AVCodecContext with values set by the user.
  309. *
  310. * @param dst The destination context.
  311. * @param src The source context.
  312. */
  313. static void update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
  314. {
  315. #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
  316. dst->flags = src->flags;
  317. dst->draw_horiz_band= src->draw_horiz_band;
  318. dst->get_buffer = src->get_buffer;
  319. dst->release_buffer = src->release_buffer;
  320. dst->opaque = src->opaque;
  321. dst->dsp_mask = src->dsp_mask;
  322. dst->debug = src->debug;
  323. dst->debug_mv = src->debug_mv;
  324. dst->slice_flags = src->slice_flags;
  325. dst->flags2 = src->flags2;
  326. copy_fields(skip_loop_filter, bidir_refine);
  327. dst->frame_number = src->frame_number;
  328. dst->reordered_opaque = src->reordered_opaque;
  329. #undef copy_fields
  330. }
  331. static void free_progress(AVFrame *f)
  332. {
  333. PerThreadContext *p = f->owner->thread_opaque;
  334. int *progress = f->thread_opaque;
  335. p->progress_used[(progress - p->progress[0]) / 2] = 0;
  336. }
  337. /// Releases the buffers that this decoding thread was the last user of.
  338. static void release_delayed_buffers(PerThreadContext *p)
  339. {
  340. FrameThreadContext *fctx = p->parent;
  341. while (p->num_released_buffers > 0) {
  342. AVFrame *f;
  343. pthread_mutex_lock(&fctx->buffer_mutex);
  344. f = &p->released_buffers[--p->num_released_buffers];
  345. free_progress(f);
  346. f->thread_opaque = NULL;
  347. f->owner->release_buffer(f->owner, f);
  348. pthread_mutex_unlock(&fctx->buffer_mutex);
  349. }
  350. }
  351. static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
  352. {
  353. FrameThreadContext *fctx = p->parent;
  354. PerThreadContext *prev_thread = fctx->prev_thread;
  355. AVCodec *codec = p->avctx->codec;
  356. uint8_t *buf = p->avpkt.data;
  357. if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
  358. pthread_mutex_lock(&p->mutex);
  359. release_delayed_buffers(p);
  360. if (prev_thread) {
  361. int err;
  362. if (prev_thread->state == STATE_SETTING_UP) {
  363. pthread_mutex_lock(&prev_thread->progress_mutex);
  364. while (prev_thread->state == STATE_SETTING_UP)
  365. pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
  366. pthread_mutex_unlock(&prev_thread->progress_mutex);
  367. }
  368. err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
  369. if (err) {
  370. pthread_mutex_unlock(&p->mutex);
  371. return err;
  372. }
  373. }
  374. av_fast_malloc(&buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
  375. p->avpkt = *avpkt;
  376. p->avpkt.data = buf;
  377. memcpy(buf, avpkt->data, avpkt->size);
  378. memset(buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  379. p->state = STATE_SETTING_UP;
  380. pthread_cond_signal(&p->input_cond);
  381. pthread_mutex_unlock(&p->mutex);
  382. /*
  383. * If the client doesn't have a thread-safe get_buffer(),
  384. * then decoding threads call back to the main thread,
  385. * and it calls back to the client here.
  386. */
  387. if (!p->avctx->thread_safe_callbacks &&
  388. p->avctx->get_buffer != avcodec_default_get_buffer) {
  389. while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
  390. pthread_mutex_lock(&p->progress_mutex);
  391. while (p->state == STATE_SETTING_UP)
  392. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  393. if (p->state == STATE_GET_BUFFER) {
  394. p->result = p->avctx->get_buffer(p->avctx, p->requested_frame);
  395. p->state = STATE_SETTING_UP;
  396. pthread_cond_signal(&p->progress_cond);
  397. }
  398. pthread_mutex_unlock(&p->progress_mutex);
  399. }
  400. }
  401. fctx->prev_thread = p;
  402. return 0;
  403. }
  404. int ff_thread_decode_frame(AVCodecContext *avctx,
  405. AVFrame *picture, int *got_picture_ptr,
  406. AVPacket *avpkt)
  407. {
  408. FrameThreadContext *fctx = avctx->thread_opaque;
  409. int finished = fctx->next_finished;
  410. PerThreadContext *p;
  411. int err;
  412. /*
  413. * Submit a packet to the next decoding thread.
  414. */
  415. p = &fctx->threads[fctx->next_decoding];
  416. update_context_from_user(p->avctx, avctx);
  417. err = submit_packet(p, avpkt);
  418. if (err) return err;
  419. fctx->next_decoding++;
  420. /*
  421. * If we're still receiving the initial packets, don't return a frame.
  422. */
  423. if (fctx->delaying && avpkt->size) {
  424. if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
  425. *got_picture_ptr=0;
  426. return 0;
  427. }
  428. /*
  429. * Return the next available frame from the oldest thread.
  430. * If we're at the end of the stream, then we have to skip threads that
  431. * didn't output a frame, because we don't want to accidentally signal
  432. * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
  433. */
  434. do {
  435. p = &fctx->threads[finished++];
  436. if (p->state != STATE_INPUT_READY) {
  437. pthread_mutex_lock(&p->progress_mutex);
  438. while (p->state != STATE_INPUT_READY)
  439. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  440. pthread_mutex_unlock(&p->progress_mutex);
  441. }
  442. *picture = p->frame;
  443. *got_picture_ptr = p->got_frame;
  444. picture->pkt_dts = p->avpkt.dts;
  445. /*
  446. * A later call with avkpt->size == 0 may loop over all threads,
  447. * including this one, searching for a frame to return before being
  448. * stopped by the "finished != fctx->next_finished" condition.
  449. * Make sure we don't mistakenly return the same frame again.
  450. */
  451. p->got_frame = 0;
  452. if (finished >= avctx->thread_count) finished = 0;
  453. } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
  454. update_context_from_thread(avctx, p->avctx, 1);
  455. if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
  456. fctx->next_finished = finished;
  457. return p->result;
  458. }
  459. void ff_thread_report_progress(AVFrame *f, int n, int field)
  460. {
  461. PerThreadContext *p;
  462. int *progress = f->thread_opaque;
  463. if (!progress || progress[field] >= n) return;
  464. p = f->owner->thread_opaque;
  465. if (f->owner->debug&FF_DEBUG_THREADS)
  466. av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
  467. pthread_mutex_lock(&p->progress_mutex);
  468. progress[field] = n;
  469. pthread_cond_broadcast(&p->progress_cond);
  470. pthread_mutex_unlock(&p->progress_mutex);
  471. }
  472. void ff_thread_await_progress(AVFrame *f, int n, int field)
  473. {
  474. PerThreadContext *p;
  475. int *progress = f->thread_opaque;
  476. if (!progress || progress[field] >= n) return;
  477. p = f->owner->thread_opaque;
  478. if (f->owner->debug&FF_DEBUG_THREADS)
  479. av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
  480. pthread_mutex_lock(&p->progress_mutex);
  481. while (progress[field] < n)
  482. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  483. pthread_mutex_unlock(&p->progress_mutex);
  484. }
  485. void ff_thread_finish_setup(AVCodecContext *avctx) {
  486. PerThreadContext *p = avctx->thread_opaque;
  487. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
  488. if(p->state == STATE_SETUP_FINISHED){
  489. av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
  490. }
  491. pthread_mutex_lock(&p->progress_mutex);
  492. p->state = STATE_SETUP_FINISHED;
  493. pthread_cond_broadcast(&p->progress_cond);
  494. pthread_mutex_unlock(&p->progress_mutex);
  495. }
  496. /// Waits for all threads to finish.
  497. static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
  498. {
  499. int i;
  500. for (i = 0; i < thread_count; i++) {
  501. PerThreadContext *p = &fctx->threads[i];
  502. if (p->state != STATE_INPUT_READY) {
  503. pthread_mutex_lock(&p->progress_mutex);
  504. while (p->state != STATE_INPUT_READY)
  505. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  506. pthread_mutex_unlock(&p->progress_mutex);
  507. }
  508. }
  509. }
  510. static void frame_thread_free(AVCodecContext *avctx, int thread_count)
  511. {
  512. FrameThreadContext *fctx = avctx->thread_opaque;
  513. AVCodec *codec = avctx->codec;
  514. int i;
  515. park_frame_worker_threads(fctx, thread_count);
  516. if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
  517. update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
  518. fctx->die = 1;
  519. for (i = 0; i < thread_count; i++) {
  520. PerThreadContext *p = &fctx->threads[i];
  521. pthread_mutex_lock(&p->mutex);
  522. pthread_cond_signal(&p->input_cond);
  523. pthread_mutex_unlock(&p->mutex);
  524. pthread_join(p->thread, NULL);
  525. if (codec->close)
  526. codec->close(p->avctx);
  527. avctx->codec = NULL;
  528. release_delayed_buffers(p);
  529. }
  530. for (i = 0; i < thread_count; i++) {
  531. PerThreadContext *p = &fctx->threads[i];
  532. avcodec_default_free_buffers(p->avctx);
  533. pthread_mutex_destroy(&p->mutex);
  534. pthread_mutex_destroy(&p->progress_mutex);
  535. pthread_cond_destroy(&p->input_cond);
  536. pthread_cond_destroy(&p->progress_cond);
  537. pthread_cond_destroy(&p->output_cond);
  538. av_freep(&p->avpkt.data);
  539. if (i)
  540. av_freep(&p->avctx->priv_data);
  541. av_freep(&p->avctx);
  542. }
  543. av_freep(&fctx->threads);
  544. pthread_mutex_destroy(&fctx->buffer_mutex);
  545. av_freep(&avctx->thread_opaque);
  546. avctx->has_b_frames -= avctx->thread_count - 1;
  547. }
  548. static int frame_thread_init(AVCodecContext *avctx)
  549. {
  550. int thread_count = avctx->thread_count;
  551. AVCodec *codec = avctx->codec;
  552. AVCodecContext *src = avctx;
  553. FrameThreadContext *fctx;
  554. int i, err = 0;
  555. if (thread_count <= 1) {
  556. avctx->active_thread_type = 0;
  557. return 0;
  558. }
  559. avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
  560. fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
  561. pthread_mutex_init(&fctx->buffer_mutex, NULL);
  562. fctx->delaying = 1;
  563. for (i = 0; i < thread_count; i++) {
  564. AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
  565. PerThreadContext *p = &fctx->threads[i];
  566. pthread_mutex_init(&p->mutex, NULL);
  567. pthread_mutex_init(&p->progress_mutex, NULL);
  568. pthread_cond_init(&p->input_cond, NULL);
  569. pthread_cond_init(&p->progress_cond, NULL);
  570. pthread_cond_init(&p->output_cond, NULL);
  571. p->parent = fctx;
  572. p->avctx = copy;
  573. *copy = *src;
  574. copy->thread_opaque = p;
  575. copy->pkt = &p->avpkt;
  576. if (!i) {
  577. src = copy;
  578. if (codec->init)
  579. err = codec->init(copy);
  580. update_context_from_thread(avctx, copy, 1);
  581. } else {
  582. copy->is_copy = 1;
  583. copy->priv_data = av_malloc(codec->priv_data_size);
  584. memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
  585. if (codec->init_thread_copy)
  586. err = codec->init_thread_copy(copy);
  587. }
  588. if (err) goto error;
  589. pthread_create(&p->thread, NULL, frame_worker_thread, p);
  590. }
  591. return 0;
  592. error:
  593. frame_thread_free(avctx, i+1);
  594. return err;
  595. }
  596. void ff_thread_flush(AVCodecContext *avctx)
  597. {
  598. FrameThreadContext *fctx = avctx->thread_opaque;
  599. if (!avctx->thread_opaque) return;
  600. park_frame_worker_threads(fctx, avctx->thread_count);
  601. if (fctx->prev_thread) {
  602. if (fctx->prev_thread != &fctx->threads[0])
  603. update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
  604. if (avctx->codec->flush)
  605. avctx->codec->flush(fctx->threads[0].avctx);
  606. }
  607. fctx->next_decoding = fctx->next_finished = 0;
  608. fctx->delaying = 1;
  609. fctx->prev_thread = NULL;
  610. }
  611. static int *allocate_progress(PerThreadContext *p)
  612. {
  613. int i;
  614. for (i = 0; i < MAX_BUFFERS; i++)
  615. if (!p->progress_used[i]) break;
  616. if (i == MAX_BUFFERS) {
  617. av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
  618. return NULL;
  619. }
  620. p->progress_used[i] = 1;
  621. return p->progress[i];
  622. }
  623. int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
  624. {
  625. PerThreadContext *p = avctx->thread_opaque;
  626. int *progress, err;
  627. f->owner = avctx;
  628. ff_init_buffer_info(avctx, f);
  629. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
  630. f->thread_opaque = NULL;
  631. return avctx->get_buffer(avctx, f);
  632. }
  633. if (p->state != STATE_SETTING_UP &&
  634. (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
  635. av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
  636. return -1;
  637. }
  638. pthread_mutex_lock(&p->parent->buffer_mutex);
  639. f->thread_opaque = progress = allocate_progress(p);
  640. if (!progress) {
  641. pthread_mutex_unlock(&p->parent->buffer_mutex);
  642. return -1;
  643. }
  644. progress[0] =
  645. progress[1] = -1;
  646. if (avctx->thread_safe_callbacks ||
  647. avctx->get_buffer == avcodec_default_get_buffer) {
  648. err = avctx->get_buffer(avctx, f);
  649. } else {
  650. p->requested_frame = f;
  651. p->state = STATE_GET_BUFFER;
  652. pthread_mutex_lock(&p->progress_mutex);
  653. pthread_cond_signal(&p->progress_cond);
  654. while (p->state != STATE_SETTING_UP)
  655. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  656. err = p->result;
  657. pthread_mutex_unlock(&p->progress_mutex);
  658. if (!avctx->codec->update_thread_context)
  659. ff_thread_finish_setup(avctx);
  660. }
  661. pthread_mutex_unlock(&p->parent->buffer_mutex);
  662. /*
  663. * Buffer age is difficult to keep track of between
  664. * multiple threads, and the optimizations it allows
  665. * are not worth the effort. It is disabled for now.
  666. */
  667. f->age = INT_MAX;
  668. return err;
  669. }
  670. void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
  671. {
  672. PerThreadContext *p = avctx->thread_opaque;
  673. FrameThreadContext *fctx;
  674. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
  675. avctx->release_buffer(avctx, f);
  676. return;
  677. }
  678. if (p->num_released_buffers >= MAX_BUFFERS) {
  679. av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
  680. return;
  681. }
  682. if(avctx->debug & FF_DEBUG_BUFFERS)
  683. av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p, %d buffers used\n",
  684. f, f->owner->internal_buffer_count);
  685. fctx = p->parent;
  686. pthread_mutex_lock(&fctx->buffer_mutex);
  687. p->released_buffers[p->num_released_buffers++] = *f;
  688. pthread_mutex_unlock(&fctx->buffer_mutex);
  689. memset(f->data, 0, sizeof(f->data));
  690. }
  691. /**
  692. * Set the threading algorithms used.
  693. *
  694. * Threading requires more than one thread.
  695. * Frame threading requires entire frames to be passed to the codec,
  696. * and introduces extra decoding delay, so is incompatible with low_delay.
  697. *
  698. * @param avctx The context.
  699. */
  700. static void validate_thread_parameters(AVCodecContext *avctx)
  701. {
  702. int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
  703. && !(avctx->flags & CODEC_FLAG_TRUNCATED)
  704. && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
  705. && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
  706. if (avctx->thread_count == 1) {
  707. avctx->active_thread_type = 0;
  708. } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
  709. avctx->active_thread_type = FF_THREAD_FRAME;
  710. } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
  711. avctx->thread_type & FF_THREAD_SLICE) {
  712. avctx->active_thread_type = FF_THREAD_SLICE;
  713. }
  714. }
  715. int ff_thread_init(AVCodecContext *avctx)
  716. {
  717. if (avctx->thread_opaque) {
  718. av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
  719. return -1;
  720. }
  721. #if HAVE_W32THREADS
  722. w32thread_init();
  723. #endif
  724. if (avctx->codec) {
  725. validate_thread_parameters(avctx);
  726. if (avctx->active_thread_type&FF_THREAD_SLICE)
  727. return thread_init(avctx);
  728. else if (avctx->active_thread_type&FF_THREAD_FRAME)
  729. return frame_thread_init(avctx);
  730. }
  731. return 0;
  732. }
  733. void ff_thread_free(AVCodecContext *avctx)
  734. {
  735. if (avctx->active_thread_type&FF_THREAD_FRAME)
  736. frame_thread_free(avctx, avctx->thread_count);
  737. else
  738. thread_free(avctx);
  739. }