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.

948 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 "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. int thread_init;
  65. pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
  66. pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
  67. pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
  68. pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
  69. pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
  70. AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
  71. AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
  72. int allocated_buf_size; ///< Size allocated for avpkt.data
  73. AVFrame frame; ///< Output frame (for decoding) or input (for encoding).
  74. int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
  75. int result; ///< The result of the last codec decode/encode() call.
  76. enum {
  77. STATE_INPUT_READY, ///< Set when the thread is awaiting a packet.
  78. STATE_SETTING_UP, ///< Set before the codec has called ff_thread_finish_setup().
  79. STATE_GET_BUFFER, /**<
  80. * Set when the codec calls get_buffer().
  81. * State is returned to STATE_SETTING_UP afterwards.
  82. */
  83. STATE_SETUP_FINISHED ///< Set after the codec has called ff_thread_finish_setup().
  84. } state;
  85. /**
  86. * Array of frames passed to ff_thread_release_buffer().
  87. * Frames are released after all threads referencing them are finished.
  88. */
  89. AVFrame released_buffers[MAX_BUFFERS];
  90. int num_released_buffers;
  91. /**
  92. * Array of progress values used by ff_thread_get_buffer().
  93. */
  94. int progress[MAX_BUFFERS][2];
  95. uint8_t progress_used[MAX_BUFFERS];
  96. AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
  97. } PerThreadContext;
  98. /**
  99. * Context stored in the client AVCodecContext thread_opaque.
  100. */
  101. typedef struct FrameThreadContext {
  102. PerThreadContext *threads; ///< The contexts for each thread.
  103. PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
  104. pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
  105. int next_decoding; ///< The next context to submit a packet to.
  106. int next_finished; ///< The next context to return output from.
  107. int delaying; /**<
  108. * Set for the first N packets, where N is the number of threads.
  109. * While it is set, ff_thread_en/decode_frame won't return any results.
  110. */
  111. int die; ///< Set when threads should exit.
  112. } FrameThreadContext;
  113. static void* attribute_align_arg worker(void *v)
  114. {
  115. AVCodecContext *avctx = v;
  116. ThreadContext *c = avctx->thread_opaque;
  117. int our_job = c->job_count;
  118. int thread_count = avctx->thread_count;
  119. int self_id;
  120. pthread_mutex_lock(&c->current_job_lock);
  121. self_id = c->current_job++;
  122. for (;;){
  123. while (our_job >= c->job_count) {
  124. if (c->current_job == thread_count + c->job_count)
  125. pthread_cond_signal(&c->last_job_cond);
  126. pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
  127. our_job = self_id;
  128. if (c->done) {
  129. pthread_mutex_unlock(&c->current_job_lock);
  130. return NULL;
  131. }
  132. }
  133. pthread_mutex_unlock(&c->current_job_lock);
  134. c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
  135. c->func2(avctx, c->args, our_job, self_id);
  136. pthread_mutex_lock(&c->current_job_lock);
  137. our_job = c->current_job++;
  138. }
  139. }
  140. static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
  141. {
  142. pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
  143. pthread_mutex_unlock(&c->current_job_lock);
  144. }
  145. static void thread_free(AVCodecContext *avctx)
  146. {
  147. ThreadContext *c = avctx->thread_opaque;
  148. int i;
  149. pthread_mutex_lock(&c->current_job_lock);
  150. c->done = 1;
  151. pthread_cond_broadcast(&c->current_job_cond);
  152. pthread_mutex_unlock(&c->current_job_lock);
  153. for (i=0; i<avctx->thread_count; i++)
  154. pthread_join(c->workers[i], NULL);
  155. pthread_mutex_destroy(&c->current_job_lock);
  156. pthread_cond_destroy(&c->current_job_cond);
  157. pthread_cond_destroy(&c->last_job_cond);
  158. av_free(c->workers);
  159. av_freep(&avctx->thread_opaque);
  160. }
  161. static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
  162. {
  163. ThreadContext *c= avctx->thread_opaque;
  164. int dummy_ret;
  165. if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
  166. return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
  167. if (job_count <= 0)
  168. return 0;
  169. pthread_mutex_lock(&c->current_job_lock);
  170. c->current_job = avctx->thread_count;
  171. c->job_count = job_count;
  172. c->job_size = job_size;
  173. c->args = arg;
  174. c->func = func;
  175. if (ret) {
  176. c->rets = ret;
  177. c->rets_count = job_count;
  178. } else {
  179. c->rets = &dummy_ret;
  180. c->rets_count = 1;
  181. }
  182. pthread_cond_broadcast(&c->current_job_cond);
  183. avcodec_thread_park_workers(c, avctx->thread_count);
  184. return 0;
  185. }
  186. static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
  187. {
  188. ThreadContext *c= avctx->thread_opaque;
  189. c->func2 = func2;
  190. return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
  191. }
  192. static int thread_init(AVCodecContext *avctx)
  193. {
  194. int i;
  195. ThreadContext *c;
  196. int thread_count = avctx->thread_count;
  197. if (thread_count <= 1)
  198. return 0;
  199. c = av_mallocz(sizeof(ThreadContext));
  200. if (!c)
  201. return -1;
  202. c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
  203. if (!c->workers) {
  204. av_free(c);
  205. return -1;
  206. }
  207. avctx->thread_opaque = c;
  208. c->current_job = 0;
  209. c->job_count = 0;
  210. c->job_size = 0;
  211. c->done = 0;
  212. pthread_cond_init(&c->current_job_cond, NULL);
  213. pthread_cond_init(&c->last_job_cond, NULL);
  214. pthread_mutex_init(&c->current_job_lock, NULL);
  215. pthread_mutex_lock(&c->current_job_lock);
  216. for (i=0; i<thread_count; i++) {
  217. if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
  218. avctx->thread_count = i;
  219. pthread_mutex_unlock(&c->current_job_lock);
  220. ff_thread_free(avctx);
  221. return -1;
  222. }
  223. }
  224. avcodec_thread_park_workers(c, thread_count);
  225. avctx->execute = avcodec_thread_execute;
  226. avctx->execute2 = avcodec_thread_execute2;
  227. return 0;
  228. }
  229. /**
  230. * Codec worker thread.
  231. *
  232. * Automatically calls ff_thread_finish_setup() if the codec does
  233. * not provide an update_thread_context method, or if the codec returns
  234. * before calling it.
  235. */
  236. static attribute_align_arg void *frame_worker_thread(void *arg)
  237. {
  238. PerThreadContext *p = arg;
  239. FrameThreadContext *fctx = p->parent;
  240. AVCodecContext *avctx = p->avctx;
  241. AVCodec *codec = avctx->codec;
  242. while (1) {
  243. if (p->state == STATE_INPUT_READY && !fctx->die) {
  244. pthread_mutex_lock(&p->mutex);
  245. while (p->state == STATE_INPUT_READY && !fctx->die)
  246. pthread_cond_wait(&p->input_cond, &p->mutex);
  247. pthread_mutex_unlock(&p->mutex);
  248. }
  249. if (fctx->die) break;
  250. if (!codec->update_thread_context && avctx->thread_safe_callbacks)
  251. ff_thread_finish_setup(avctx);
  252. pthread_mutex_lock(&p->mutex);
  253. avcodec_get_frame_defaults(&p->frame);
  254. p->got_frame = 0;
  255. p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
  256. if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
  257. p->state = STATE_INPUT_READY;
  258. pthread_mutex_lock(&p->progress_mutex);
  259. pthread_cond_signal(&p->output_cond);
  260. pthread_mutex_unlock(&p->progress_mutex);
  261. pthread_mutex_unlock(&p->mutex);
  262. }
  263. return NULL;
  264. }
  265. /**
  266. * Updates the next thread's AVCodecContext with values from the reference thread's context.
  267. *
  268. * @param dst The destination context.
  269. * @param src The source context.
  270. * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
  271. */
  272. static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
  273. {
  274. int err = 0;
  275. if (dst != src) {
  276. dst->sub_id = src->sub_id;
  277. dst->time_base = src->time_base;
  278. dst->width = src->width;
  279. dst->height = src->height;
  280. dst->pix_fmt = src->pix_fmt;
  281. dst->coded_width = src->coded_width;
  282. dst->coded_height = src->coded_height;
  283. dst->has_b_frames = src->has_b_frames;
  284. dst->idct_algo = src->idct_algo;
  285. dst->slice_count = src->slice_count;
  286. dst->bits_per_coded_sample = src->bits_per_coded_sample;
  287. dst->sample_aspect_ratio = src->sample_aspect_ratio;
  288. dst->dtg_active_format = src->dtg_active_format;
  289. dst->profile = src->profile;
  290. dst->level = src->level;
  291. dst->bits_per_raw_sample = src->bits_per_raw_sample;
  292. dst->ticks_per_frame = src->ticks_per_frame;
  293. dst->color_primaries = src->color_primaries;
  294. dst->color_trc = src->color_trc;
  295. dst->colorspace = src->colorspace;
  296. dst->color_range = src->color_range;
  297. dst->chroma_sample_location = src->chroma_sample_location;
  298. }
  299. if (for_user) {
  300. dst->coded_frame = src->coded_frame;
  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. fctx->next_decoding++;
  403. return 0;
  404. }
  405. int ff_thread_decode_frame(AVCodecContext *avctx,
  406. AVFrame *picture, int *got_picture_ptr,
  407. AVPacket *avpkt)
  408. {
  409. FrameThreadContext *fctx = avctx->thread_opaque;
  410. int finished = fctx->next_finished;
  411. PerThreadContext *p;
  412. int err;
  413. /*
  414. * Submit a packet to the next decoding thread.
  415. */
  416. p = &fctx->threads[fctx->next_decoding];
  417. update_context_from_user(p->avctx, avctx);
  418. err = submit_packet(p, avpkt);
  419. if (err) return err;
  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 avpkt->size;
  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 the size of the consumed packet if no error occurred */
  458. return (p->result >= 0) ? avpkt->size : p->result;
  459. }
  460. void ff_thread_report_progress(AVFrame *f, int n, int field)
  461. {
  462. PerThreadContext *p;
  463. int *progress = f->thread_opaque;
  464. if (!progress || progress[field] >= n) return;
  465. p = f->owner->thread_opaque;
  466. if (f->owner->debug&FF_DEBUG_THREADS)
  467. av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
  468. pthread_mutex_lock(&p->progress_mutex);
  469. progress[field] = n;
  470. pthread_cond_broadcast(&p->progress_cond);
  471. pthread_mutex_unlock(&p->progress_mutex);
  472. }
  473. void ff_thread_await_progress(AVFrame *f, int n, int field)
  474. {
  475. PerThreadContext *p;
  476. int *progress = f->thread_opaque;
  477. if (!progress || progress[field] >= n) return;
  478. p = f->owner->thread_opaque;
  479. if (f->owner->debug&FF_DEBUG_THREADS)
  480. av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
  481. pthread_mutex_lock(&p->progress_mutex);
  482. while (progress[field] < n)
  483. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  484. pthread_mutex_unlock(&p->progress_mutex);
  485. }
  486. void ff_thread_finish_setup(AVCodecContext *avctx) {
  487. PerThreadContext *p = avctx->thread_opaque;
  488. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
  489. pthread_mutex_lock(&p->progress_mutex);
  490. p->state = STATE_SETUP_FINISHED;
  491. pthread_cond_broadcast(&p->progress_cond);
  492. pthread_mutex_unlock(&p->progress_mutex);
  493. }
  494. /// Waits for all threads to finish.
  495. static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
  496. {
  497. int i;
  498. for (i = 0; i < thread_count; i++) {
  499. PerThreadContext *p = &fctx->threads[i];
  500. if (p->state != STATE_INPUT_READY) {
  501. pthread_mutex_lock(&p->progress_mutex);
  502. while (p->state != STATE_INPUT_READY)
  503. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  504. pthread_mutex_unlock(&p->progress_mutex);
  505. }
  506. }
  507. }
  508. static void frame_thread_free(AVCodecContext *avctx, int thread_count)
  509. {
  510. FrameThreadContext *fctx = avctx->thread_opaque;
  511. AVCodec *codec = avctx->codec;
  512. int i;
  513. park_frame_worker_threads(fctx, thread_count);
  514. if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
  515. update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
  516. fctx->die = 1;
  517. for (i = 0; i < thread_count; i++) {
  518. PerThreadContext *p = &fctx->threads[i];
  519. pthread_mutex_lock(&p->mutex);
  520. pthread_cond_signal(&p->input_cond);
  521. pthread_mutex_unlock(&p->mutex);
  522. if (p->thread_init)
  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->internal);
  541. }
  542. av_freep(&p->avctx);
  543. }
  544. av_freep(&fctx->threads);
  545. pthread_mutex_destroy(&fctx->buffer_mutex);
  546. av_freep(&avctx->thread_opaque);
  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. if (!copy) {
  574. err = AVERROR(ENOMEM);
  575. goto error;
  576. }
  577. *copy = *src;
  578. copy->thread_opaque = p;
  579. copy->pkt = &p->avpkt;
  580. if (!i) {
  581. src = copy;
  582. if (codec->init)
  583. err = codec->init(copy);
  584. update_context_from_thread(avctx, copy, 1);
  585. } else {
  586. copy->priv_data = av_malloc(codec->priv_data_size);
  587. if (!copy->priv_data) {
  588. err = AVERROR(ENOMEM);
  589. goto error;
  590. }
  591. memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
  592. copy->internal = av_malloc(sizeof(AVCodecInternal));
  593. if (!copy->internal) {
  594. err = AVERROR(ENOMEM);
  595. goto error;
  596. }
  597. *(copy->internal) = *(src->internal);
  598. copy->internal->is_copy = 1;
  599. if (codec->init_thread_copy)
  600. err = codec->init_thread_copy(copy);
  601. }
  602. if (err) goto error;
  603. if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
  604. p->thread_init = 1;
  605. }
  606. return 0;
  607. error:
  608. frame_thread_free(avctx, i+1);
  609. return err;
  610. }
  611. void ff_thread_flush(AVCodecContext *avctx)
  612. {
  613. FrameThreadContext *fctx = avctx->thread_opaque;
  614. if (!avctx->thread_opaque) return;
  615. park_frame_worker_threads(fctx, avctx->thread_count);
  616. if (fctx->prev_thread) {
  617. if (fctx->prev_thread != &fctx->threads[0])
  618. update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
  619. if (avctx->codec->flush)
  620. avctx->codec->flush(fctx->threads[0].avctx);
  621. }
  622. fctx->next_decoding = fctx->next_finished = 0;
  623. fctx->delaying = 1;
  624. fctx->prev_thread = NULL;
  625. }
  626. static int *allocate_progress(PerThreadContext *p)
  627. {
  628. int i;
  629. for (i = 0; i < MAX_BUFFERS; i++)
  630. if (!p->progress_used[i]) break;
  631. if (i == MAX_BUFFERS) {
  632. av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
  633. return NULL;
  634. }
  635. p->progress_used[i] = 1;
  636. return p->progress[i];
  637. }
  638. int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
  639. {
  640. PerThreadContext *p = avctx->thread_opaque;
  641. int *progress, err;
  642. f->owner = avctx;
  643. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
  644. f->thread_opaque = NULL;
  645. return avctx->get_buffer(avctx, f);
  646. }
  647. if (p->state != STATE_SETTING_UP &&
  648. (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
  649. av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
  650. return -1;
  651. }
  652. pthread_mutex_lock(&p->parent->buffer_mutex);
  653. f->thread_opaque = progress = allocate_progress(p);
  654. if (!progress) {
  655. pthread_mutex_unlock(&p->parent->buffer_mutex);
  656. return -1;
  657. }
  658. progress[0] =
  659. progress[1] = -1;
  660. if (avctx->thread_safe_callbacks ||
  661. avctx->get_buffer == avcodec_default_get_buffer) {
  662. err = avctx->get_buffer(avctx, f);
  663. } else {
  664. p->requested_frame = f;
  665. p->state = STATE_GET_BUFFER;
  666. pthread_mutex_lock(&p->progress_mutex);
  667. pthread_cond_signal(&p->progress_cond);
  668. while (p->state != STATE_SETTING_UP)
  669. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  670. err = p->result;
  671. pthread_mutex_unlock(&p->progress_mutex);
  672. if (!avctx->codec->update_thread_context)
  673. ff_thread_finish_setup(avctx);
  674. }
  675. pthread_mutex_unlock(&p->parent->buffer_mutex);
  676. /*
  677. * Buffer age is difficult to keep track of between
  678. * multiple threads, and the optimizations it allows
  679. * are not worth the effort. It is disabled for now.
  680. */
  681. f->age = INT_MAX;
  682. return err;
  683. }
  684. void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
  685. {
  686. PerThreadContext *p = avctx->thread_opaque;
  687. FrameThreadContext *fctx;
  688. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
  689. avctx->release_buffer(avctx, f);
  690. return;
  691. }
  692. if (p->num_released_buffers >= MAX_BUFFERS) {
  693. av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
  694. return;
  695. }
  696. if(avctx->debug & FF_DEBUG_BUFFERS)
  697. av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
  698. fctx = p->parent;
  699. pthread_mutex_lock(&fctx->buffer_mutex);
  700. p->released_buffers[p->num_released_buffers++] = *f;
  701. pthread_mutex_unlock(&fctx->buffer_mutex);
  702. memset(f->data, 0, sizeof(f->data));
  703. }
  704. /**
  705. * Set the threading algorithms used.
  706. *
  707. * Threading requires more than one thread.
  708. * Frame threading requires entire frames to be passed to the codec,
  709. * and introduces extra decoding delay, so is incompatible with low_delay.
  710. *
  711. * @param avctx The context.
  712. */
  713. static void validate_thread_parameters(AVCodecContext *avctx)
  714. {
  715. int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
  716. && !(avctx->flags & CODEC_FLAG_TRUNCATED)
  717. && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
  718. && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
  719. if (avctx->thread_count == 1) {
  720. avctx->active_thread_type = 0;
  721. } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
  722. avctx->active_thread_type = FF_THREAD_FRAME;
  723. } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
  724. avctx->thread_type & FF_THREAD_SLICE) {
  725. avctx->active_thread_type = FF_THREAD_SLICE;
  726. }
  727. }
  728. int ff_thread_init(AVCodecContext *avctx)
  729. {
  730. if (avctx->thread_opaque) {
  731. av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
  732. return -1;
  733. }
  734. #if HAVE_W32THREADS
  735. w32thread_init();
  736. #endif
  737. if (avctx->codec) {
  738. validate_thread_parameters(avctx);
  739. if (avctx->active_thread_type&FF_THREAD_SLICE)
  740. return thread_init(avctx);
  741. else if (avctx->active_thread_type&FF_THREAD_FRAME)
  742. return frame_thread_init(avctx);
  743. }
  744. return 0;
  745. }
  746. void ff_thread_free(AVCodecContext *avctx)
  747. {
  748. if (avctx->active_thread_type&FF_THREAD_FRAME)
  749. frame_thread_free(avctx, avctx->thread_count);
  750. else
  751. thread_free(avctx);
  752. }