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.

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