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.

929 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 Libav.
  10. *
  11. * Libav is free software; you can redistribute it and/or
  12. * modify it under the terms of the GNU Lesser General Public
  13. * License as published by the Free Software Foundation; either
  14. * version 2.1 of the License, or (at your option) any later version.
  15. *
  16. * Libav is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  19. * Lesser General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Lesser General Public
  22. * License along with Libav; if not, write to the Free Software
  23. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  24. */
  25. /**
  26. * @file
  27. * Multithreading support functions
  28. * @see doc/multithreading.txt
  29. */
  30. #include "config.h"
  31. #include "avcodec.h"
  32. #include "thread.h"
  33. #if HAVE_PTHREADS
  34. #include <pthread.h>
  35. #elif HAVE_W32THREADS
  36. #include "w32pthreads.h"
  37. #endif
  38. typedef int (action_func)(AVCodecContext *c, void *arg);
  39. typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
  40. typedef struct ThreadContext {
  41. pthread_t *workers;
  42. action_func *func;
  43. action_func2 *func2;
  44. void *args;
  45. int *rets;
  46. int rets_count;
  47. int job_count;
  48. int job_size;
  49. pthread_cond_t last_job_cond;
  50. pthread_cond_t current_job_cond;
  51. pthread_mutex_t current_job_lock;
  52. int current_job;
  53. int done;
  54. } ThreadContext;
  55. /// Max number of frame buffers that can be allocated when using frame threads.
  56. #define MAX_BUFFERS (32+1)
  57. /**
  58. * Context used by codec threads and stored in their AVCodecContext thread_opaque.
  59. */
  60. typedef struct PerThreadContext {
  61. struct FrameThreadContext *parent;
  62. pthread_t thread;
  63. pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
  64. pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
  65. pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
  66. pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
  67. pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
  68. AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
  69. AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
  70. int allocated_buf_size; ///< Size allocated for avpkt.data
  71. AVFrame frame; ///< Output frame (for decoding) or input (for encoding).
  72. int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
  73. int result; ///< The result of the last codec decode/encode() call.
  74. enum {
  75. STATE_INPUT_READY, ///< Set when the thread is awaiting a packet.
  76. STATE_SETTING_UP, ///< Set before the codec has called ff_thread_finish_setup().
  77. STATE_GET_BUFFER, /**<
  78. * Set when the codec calls get_buffer().
  79. * State is returned to STATE_SETTING_UP afterwards.
  80. */
  81. STATE_SETUP_FINISHED ///< Set after the codec has called ff_thread_finish_setup().
  82. } state;
  83. /**
  84. * Array of frames passed to ff_thread_release_buffer().
  85. * Frames are released after all threads referencing them are finished.
  86. */
  87. AVFrame released_buffers[MAX_BUFFERS];
  88. int num_released_buffers;
  89. /**
  90. * Array of progress values used by ff_thread_get_buffer().
  91. */
  92. int progress[MAX_BUFFERS][2];
  93. uint8_t progress_used[MAX_BUFFERS];
  94. AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
  95. } PerThreadContext;
  96. /**
  97. * Context stored in the client AVCodecContext thread_opaque.
  98. */
  99. typedef struct FrameThreadContext {
  100. PerThreadContext *threads; ///< The contexts for each thread.
  101. PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
  102. pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
  103. int next_decoding; ///< The next context to submit a packet to.
  104. int next_finished; ///< The next context to return output from.
  105. int delaying; /**<
  106. * Set for the first N packets, where N is the number of threads.
  107. * While it is set, ff_thread_en/decode_frame won't return any results.
  108. */
  109. int die; ///< Set when threads should exit.
  110. } FrameThreadContext;
  111. static void* attribute_align_arg worker(void *v)
  112. {
  113. AVCodecContext *avctx = v;
  114. ThreadContext *c = avctx->thread_opaque;
  115. int our_job = c->job_count;
  116. int thread_count = avctx->thread_count;
  117. int self_id;
  118. pthread_mutex_lock(&c->current_job_lock);
  119. self_id = c->current_job++;
  120. for (;;){
  121. while (our_job >= c->job_count) {
  122. if (c->current_job == thread_count + c->job_count)
  123. pthread_cond_signal(&c->last_job_cond);
  124. pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
  125. our_job = self_id;
  126. if (c->done) {
  127. pthread_mutex_unlock(&c->current_job_lock);
  128. return NULL;
  129. }
  130. }
  131. pthread_mutex_unlock(&c->current_job_lock);
  132. c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
  133. c->func2(avctx, c->args, our_job, self_id);
  134. pthread_mutex_lock(&c->current_job_lock);
  135. our_job = c->current_job++;
  136. }
  137. }
  138. static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
  139. {
  140. pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
  141. pthread_mutex_unlock(&c->current_job_lock);
  142. }
  143. static void thread_free(AVCodecContext *avctx)
  144. {
  145. ThreadContext *c = avctx->thread_opaque;
  146. int i;
  147. pthread_mutex_lock(&c->current_job_lock);
  148. c->done = 1;
  149. pthread_cond_broadcast(&c->current_job_cond);
  150. pthread_mutex_unlock(&c->current_job_lock);
  151. for (i=0; i<avctx->thread_count; i++)
  152. pthread_join(c->workers[i], NULL);
  153. pthread_mutex_destroy(&c->current_job_lock);
  154. pthread_cond_destroy(&c->current_job_cond);
  155. pthread_cond_destroy(&c->last_job_cond);
  156. av_free(c->workers);
  157. av_freep(&avctx->thread_opaque);
  158. }
  159. static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
  160. {
  161. ThreadContext *c= avctx->thread_opaque;
  162. int dummy_ret;
  163. if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
  164. return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
  165. if (job_count <= 0)
  166. return 0;
  167. pthread_mutex_lock(&c->current_job_lock);
  168. c->current_job = avctx->thread_count;
  169. c->job_count = job_count;
  170. c->job_size = job_size;
  171. c->args = arg;
  172. c->func = func;
  173. if (ret) {
  174. c->rets = ret;
  175. c->rets_count = job_count;
  176. } else {
  177. c->rets = &dummy_ret;
  178. c->rets_count = 1;
  179. }
  180. pthread_cond_broadcast(&c->current_job_cond);
  181. avcodec_thread_park_workers(c, avctx->thread_count);
  182. return 0;
  183. }
  184. static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
  185. {
  186. ThreadContext *c= avctx->thread_opaque;
  187. c->func2 = func2;
  188. return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
  189. }
  190. static int thread_init(AVCodecContext *avctx)
  191. {
  192. int i;
  193. ThreadContext *c;
  194. int thread_count = avctx->thread_count;
  195. if (thread_count <= 1)
  196. return 0;
  197. c = av_mallocz(sizeof(ThreadContext));
  198. if (!c)
  199. return -1;
  200. c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
  201. if (!c->workers) {
  202. av_free(c);
  203. return -1;
  204. }
  205. avctx->thread_opaque = c;
  206. c->current_job = 0;
  207. c->job_count = 0;
  208. c->job_size = 0;
  209. c->done = 0;
  210. pthread_cond_init(&c->current_job_cond, NULL);
  211. pthread_cond_init(&c->last_job_cond, NULL);
  212. pthread_mutex_init(&c->current_job_lock, NULL);
  213. pthread_mutex_lock(&c->current_job_lock);
  214. for (i=0; i<thread_count; i++) {
  215. if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
  216. avctx->thread_count = i;
  217. pthread_mutex_unlock(&c->current_job_lock);
  218. ff_thread_free(avctx);
  219. return -1;
  220. }
  221. }
  222. avcodec_thread_park_workers(c, thread_count);
  223. avctx->execute = avcodec_thread_execute;
  224. avctx->execute2 = avcodec_thread_execute2;
  225. return 0;
  226. }
  227. /**
  228. * Codec worker thread.
  229. *
  230. * Automatically calls ff_thread_finish_setup() if the codec does
  231. * not provide an update_thread_context method, or if the codec returns
  232. * before calling it.
  233. */
  234. static attribute_align_arg void *frame_worker_thread(void *arg)
  235. {
  236. PerThreadContext *p = arg;
  237. FrameThreadContext *fctx = p->parent;
  238. AVCodecContext *avctx = p->avctx;
  239. AVCodec *codec = avctx->codec;
  240. while (1) {
  241. if (p->state == STATE_INPUT_READY && !fctx->die) {
  242. pthread_mutex_lock(&p->mutex);
  243. while (p->state == STATE_INPUT_READY && !fctx->die)
  244. pthread_cond_wait(&p->input_cond, &p->mutex);
  245. pthread_mutex_unlock(&p->mutex);
  246. }
  247. if (fctx->die) break;
  248. if (!codec->update_thread_context && avctx->thread_safe_callbacks)
  249. ff_thread_finish_setup(avctx);
  250. pthread_mutex_lock(&p->mutex);
  251. avcodec_get_frame_defaults(&p->frame);
  252. p->got_frame = 0;
  253. p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
  254. if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
  255. p->state = STATE_INPUT_READY;
  256. pthread_mutex_lock(&p->progress_mutex);
  257. pthread_cond_signal(&p->output_cond);
  258. pthread_mutex_unlock(&p->progress_mutex);
  259. pthread_mutex_unlock(&p->mutex);
  260. }
  261. return NULL;
  262. }
  263. /**
  264. * Updates the next thread's AVCodecContext with values from the reference thread's context.
  265. *
  266. * @param dst The destination context.
  267. * @param src The source context.
  268. * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
  269. */
  270. static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
  271. {
  272. int err = 0;
  273. if (dst != src) {
  274. dst->sub_id = src->sub_id;
  275. dst->time_base = src->time_base;
  276. dst->width = src->width;
  277. dst->height = src->height;
  278. dst->pix_fmt = src->pix_fmt;
  279. dst->coded_width = src->coded_width;
  280. dst->coded_height = src->coded_height;
  281. dst->has_b_frames = src->has_b_frames;
  282. dst->idct_algo = src->idct_algo;
  283. dst->slice_count = src->slice_count;
  284. dst->bits_per_coded_sample = src->bits_per_coded_sample;
  285. dst->sample_aspect_ratio = src->sample_aspect_ratio;
  286. dst->dtg_active_format = src->dtg_active_format;
  287. dst->profile = src->profile;
  288. dst->level = src->level;
  289. dst->bits_per_raw_sample = src->bits_per_raw_sample;
  290. dst->ticks_per_frame = src->ticks_per_frame;
  291. dst->color_primaries = src->color_primaries;
  292. dst->color_trc = src->color_trc;
  293. dst->colorspace = src->colorspace;
  294. dst->color_range = src->color_range;
  295. dst->chroma_sample_location = src->chroma_sample_location;
  296. }
  297. if (for_user) {
  298. dst->coded_frame = src->coded_frame;
  299. dst->has_b_frames += src->thread_count - 1;
  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. pthread_mutex_lock(&p->progress_mutex);
  488. p->state = STATE_SETUP_FINISHED;
  489. pthread_cond_broadcast(&p->progress_cond);
  490. pthread_mutex_unlock(&p->progress_mutex);
  491. }
  492. /// Waits for all threads to finish.
  493. static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
  494. {
  495. int i;
  496. for (i = 0; i < thread_count; i++) {
  497. PerThreadContext *p = &fctx->threads[i];
  498. if (p->state != STATE_INPUT_READY) {
  499. pthread_mutex_lock(&p->progress_mutex);
  500. while (p->state != STATE_INPUT_READY)
  501. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  502. pthread_mutex_unlock(&p->progress_mutex);
  503. }
  504. }
  505. }
  506. static void frame_thread_free(AVCodecContext *avctx, int thread_count)
  507. {
  508. FrameThreadContext *fctx = avctx->thread_opaque;
  509. AVCodec *codec = avctx->codec;
  510. int i;
  511. park_frame_worker_threads(fctx, thread_count);
  512. if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
  513. update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
  514. fctx->die = 1;
  515. for (i = 0; i < thread_count; i++) {
  516. PerThreadContext *p = &fctx->threads[i];
  517. pthread_mutex_lock(&p->mutex);
  518. pthread_cond_signal(&p->input_cond);
  519. pthread_mutex_unlock(&p->mutex);
  520. pthread_join(p->thread, NULL);
  521. if (codec->close)
  522. codec->close(p->avctx);
  523. avctx->codec = NULL;
  524. release_delayed_buffers(p);
  525. }
  526. for (i = 0; i < thread_count; i++) {
  527. PerThreadContext *p = &fctx->threads[i];
  528. avcodec_default_free_buffers(p->avctx);
  529. pthread_mutex_destroy(&p->mutex);
  530. pthread_mutex_destroy(&p->progress_mutex);
  531. pthread_cond_destroy(&p->input_cond);
  532. pthread_cond_destroy(&p->progress_cond);
  533. pthread_cond_destroy(&p->output_cond);
  534. av_freep(&p->avpkt.data);
  535. if (i)
  536. av_freep(&p->avctx->priv_data);
  537. av_freep(&p->avctx);
  538. }
  539. av_freep(&fctx->threads);
  540. pthread_mutex_destroy(&fctx->buffer_mutex);
  541. av_freep(&avctx->thread_opaque);
  542. }
  543. static int frame_thread_init(AVCodecContext *avctx)
  544. {
  545. int thread_count = avctx->thread_count;
  546. AVCodec *codec = avctx->codec;
  547. AVCodecContext *src = avctx;
  548. FrameThreadContext *fctx;
  549. int i, err = 0;
  550. if (thread_count <= 1) {
  551. avctx->active_thread_type = 0;
  552. return 0;
  553. }
  554. avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
  555. fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
  556. pthread_mutex_init(&fctx->buffer_mutex, NULL);
  557. fctx->delaying = 1;
  558. for (i = 0; i < thread_count; i++) {
  559. AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
  560. PerThreadContext *p = &fctx->threads[i];
  561. pthread_mutex_init(&p->mutex, NULL);
  562. pthread_mutex_init(&p->progress_mutex, NULL);
  563. pthread_cond_init(&p->input_cond, NULL);
  564. pthread_cond_init(&p->progress_cond, NULL);
  565. pthread_cond_init(&p->output_cond, NULL);
  566. p->parent = fctx;
  567. p->avctx = copy;
  568. *copy = *src;
  569. copy->thread_opaque = p;
  570. copy->pkt = &p->avpkt;
  571. if (!i) {
  572. src = copy;
  573. if (codec->init)
  574. err = codec->init(copy);
  575. update_context_from_thread(avctx, copy, 1);
  576. } else {
  577. copy->is_copy = 1;
  578. copy->priv_data = av_malloc(codec->priv_data_size);
  579. memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
  580. if (codec->init_thread_copy)
  581. err = codec->init_thread_copy(copy);
  582. }
  583. if (err) goto error;
  584. pthread_create(&p->thread, NULL, frame_worker_thread, p);
  585. }
  586. return 0;
  587. error:
  588. frame_thread_free(avctx, i+1);
  589. return err;
  590. }
  591. void ff_thread_flush(AVCodecContext *avctx)
  592. {
  593. FrameThreadContext *fctx = avctx->thread_opaque;
  594. if (!avctx->thread_opaque) return;
  595. park_frame_worker_threads(fctx, avctx->thread_count);
  596. if (fctx->prev_thread) {
  597. if (fctx->prev_thread != &fctx->threads[0])
  598. update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
  599. if (avctx->codec->flush)
  600. avctx->codec->flush(fctx->threads[0].avctx);
  601. }
  602. fctx->next_decoding = fctx->next_finished = 0;
  603. fctx->delaying = 1;
  604. fctx->prev_thread = NULL;
  605. }
  606. static int *allocate_progress(PerThreadContext *p)
  607. {
  608. int i;
  609. for (i = 0; i < MAX_BUFFERS; i++)
  610. if (!p->progress_used[i]) break;
  611. if (i == MAX_BUFFERS) {
  612. av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
  613. return NULL;
  614. }
  615. p->progress_used[i] = 1;
  616. return p->progress[i];
  617. }
  618. int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
  619. {
  620. PerThreadContext *p = avctx->thread_opaque;
  621. int *progress, err;
  622. f->owner = avctx;
  623. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
  624. f->thread_opaque = NULL;
  625. return avctx->get_buffer(avctx, f);
  626. }
  627. if (p->state != STATE_SETTING_UP &&
  628. (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
  629. av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
  630. return -1;
  631. }
  632. pthread_mutex_lock(&p->parent->buffer_mutex);
  633. f->thread_opaque = progress = allocate_progress(p);
  634. if (!progress) {
  635. pthread_mutex_unlock(&p->parent->buffer_mutex);
  636. return -1;
  637. }
  638. progress[0] =
  639. progress[1] = -1;
  640. if (avctx->thread_safe_callbacks ||
  641. avctx->get_buffer == avcodec_default_get_buffer) {
  642. err = avctx->get_buffer(avctx, f);
  643. } else {
  644. p->requested_frame = f;
  645. p->state = STATE_GET_BUFFER;
  646. pthread_mutex_lock(&p->progress_mutex);
  647. pthread_cond_signal(&p->progress_cond);
  648. while (p->state != STATE_SETTING_UP)
  649. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  650. err = p->result;
  651. pthread_mutex_unlock(&p->progress_mutex);
  652. if (!avctx->codec->update_thread_context)
  653. ff_thread_finish_setup(avctx);
  654. }
  655. pthread_mutex_unlock(&p->parent->buffer_mutex);
  656. /*
  657. * Buffer age is difficult to keep track of between
  658. * multiple threads, and the optimizations it allows
  659. * are not worth the effort. It is disabled for now.
  660. */
  661. f->age = INT_MAX;
  662. return err;
  663. }
  664. void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
  665. {
  666. PerThreadContext *p = avctx->thread_opaque;
  667. FrameThreadContext *fctx;
  668. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
  669. avctx->release_buffer(avctx, f);
  670. return;
  671. }
  672. if (p->num_released_buffers >= MAX_BUFFERS) {
  673. av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
  674. return;
  675. }
  676. if(avctx->debug & FF_DEBUG_BUFFERS)
  677. av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p, %d buffers used\n",
  678. f, f->owner->internal_buffer_count);
  679. fctx = p->parent;
  680. pthread_mutex_lock(&fctx->buffer_mutex);
  681. p->released_buffers[p->num_released_buffers++] = *f;
  682. pthread_mutex_unlock(&fctx->buffer_mutex);
  683. memset(f->data, 0, sizeof(f->data));
  684. }
  685. /**
  686. * Set the threading algorithms used.
  687. *
  688. * Threading requires more than one thread.
  689. * Frame threading requires entire frames to be passed to the codec,
  690. * and introduces extra decoding delay, so is incompatible with low_delay.
  691. *
  692. * @param avctx The context.
  693. */
  694. static void validate_thread_parameters(AVCodecContext *avctx)
  695. {
  696. int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
  697. && !(avctx->flags & CODEC_FLAG_TRUNCATED)
  698. && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
  699. && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
  700. if (avctx->thread_count == 1) {
  701. avctx->active_thread_type = 0;
  702. } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
  703. avctx->active_thread_type = FF_THREAD_FRAME;
  704. } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
  705. avctx->thread_type & FF_THREAD_SLICE) {
  706. avctx->active_thread_type = FF_THREAD_SLICE;
  707. }
  708. }
  709. int ff_thread_init(AVCodecContext *avctx)
  710. {
  711. if (avctx->thread_opaque) {
  712. av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
  713. return -1;
  714. }
  715. #if HAVE_W32THREADS
  716. w32thread_init();
  717. #endif
  718. if (avctx->codec) {
  719. validate_thread_parameters(avctx);
  720. if (avctx->active_thread_type&FF_THREAD_SLICE)
  721. return thread_init(avctx);
  722. else if (avctx->active_thread_type&FF_THREAD_FRAME)
  723. return frame_thread_init(avctx);
  724. }
  725. return 0;
  726. }
  727. void ff_thread_free(AVCodecContext *avctx)
  728. {
  729. if (avctx->active_thread_type&FF_THREAD_FRAME)
  730. frame_thread_free(avctx, avctx->thread_count);
  731. else
  732. thread_free(avctx);
  733. }