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.

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