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.

956 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 avpkt->size;
  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 the size of the consumed packet if no error occurred */
  460. return (p->result >= 0) ? avpkt->size : p->result;
  461. }
  462. void ff_thread_report_progress(AVFrame *f, int n, int field)
  463. {
  464. PerThreadContext *p;
  465. int *progress = f->thread_opaque;
  466. if (!progress || progress[field] >= n) return;
  467. p = f->owner->thread_opaque;
  468. if (f->owner->debug&FF_DEBUG_THREADS)
  469. av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
  470. pthread_mutex_lock(&p->progress_mutex);
  471. progress[field] = n;
  472. pthread_cond_broadcast(&p->progress_cond);
  473. pthread_mutex_unlock(&p->progress_mutex);
  474. }
  475. void ff_thread_await_progress(AVFrame *f, int n, int field)
  476. {
  477. PerThreadContext *p;
  478. int *progress = f->thread_opaque;
  479. if (!progress || progress[field] >= n) return;
  480. p = f->owner->thread_opaque;
  481. if (f->owner->debug&FF_DEBUG_THREADS)
  482. av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
  483. pthread_mutex_lock(&p->progress_mutex);
  484. while (progress[field] < n)
  485. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  486. pthread_mutex_unlock(&p->progress_mutex);
  487. }
  488. void ff_thread_finish_setup(AVCodecContext *avctx) {
  489. PerThreadContext *p = avctx->thread_opaque;
  490. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
  491. if(p->state == STATE_SETUP_FINISHED){
  492. av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
  493. }
  494. pthread_mutex_lock(&p->progress_mutex);
  495. p->state = STATE_SETUP_FINISHED;
  496. pthread_cond_broadcast(&p->progress_cond);
  497. pthread_mutex_unlock(&p->progress_mutex);
  498. }
  499. /// Waits for all threads to finish.
  500. static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
  501. {
  502. int i;
  503. for (i = 0; i < thread_count; i++) {
  504. PerThreadContext *p = &fctx->threads[i];
  505. if (p->state != STATE_INPUT_READY) {
  506. pthread_mutex_lock(&p->progress_mutex);
  507. while (p->state != STATE_INPUT_READY)
  508. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  509. pthread_mutex_unlock(&p->progress_mutex);
  510. }
  511. }
  512. }
  513. static void frame_thread_free(AVCodecContext *avctx, int thread_count)
  514. {
  515. FrameThreadContext *fctx = avctx->thread_opaque;
  516. AVCodec *codec = avctx->codec;
  517. int i;
  518. park_frame_worker_threads(fctx, thread_count);
  519. if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
  520. update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
  521. fctx->die = 1;
  522. for (i = 0; i < thread_count; i++) {
  523. PerThreadContext *p = &fctx->threads[i];
  524. pthread_mutex_lock(&p->mutex);
  525. pthread_cond_signal(&p->input_cond);
  526. pthread_mutex_unlock(&p->mutex);
  527. if (p->thread)
  528. pthread_join(p->thread, NULL);
  529. if (codec->close)
  530. codec->close(p->avctx);
  531. avctx->codec = NULL;
  532. release_delayed_buffers(p);
  533. }
  534. for (i = 0; i < thread_count; i++) {
  535. PerThreadContext *p = &fctx->threads[i];
  536. avcodec_default_free_buffers(p->avctx);
  537. pthread_mutex_destroy(&p->mutex);
  538. pthread_mutex_destroy(&p->progress_mutex);
  539. pthread_cond_destroy(&p->input_cond);
  540. pthread_cond_destroy(&p->progress_cond);
  541. pthread_cond_destroy(&p->output_cond);
  542. av_freep(&p->avpkt.data);
  543. if (i) {
  544. av_freep(&p->avctx->priv_data);
  545. av_freep(&p->avctx->internal);
  546. }
  547. av_freep(&p->avctx);
  548. }
  549. av_freep(&fctx->threads);
  550. pthread_mutex_destroy(&fctx->buffer_mutex);
  551. av_freep(&avctx->thread_opaque);
  552. }
  553. static int frame_thread_init(AVCodecContext *avctx)
  554. {
  555. int thread_count = avctx->thread_count;
  556. AVCodec *codec = avctx->codec;
  557. AVCodecContext *src = avctx;
  558. FrameThreadContext *fctx;
  559. int i, err = 0;
  560. if (thread_count <= 1) {
  561. avctx->active_thread_type = 0;
  562. return 0;
  563. }
  564. avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
  565. fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
  566. pthread_mutex_init(&fctx->buffer_mutex, NULL);
  567. fctx->delaying = 1;
  568. for (i = 0; i < thread_count; i++) {
  569. AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
  570. PerThreadContext *p = &fctx->threads[i];
  571. pthread_mutex_init(&p->mutex, NULL);
  572. pthread_mutex_init(&p->progress_mutex, NULL);
  573. pthread_cond_init(&p->input_cond, NULL);
  574. pthread_cond_init(&p->progress_cond, NULL);
  575. pthread_cond_init(&p->output_cond, NULL);
  576. p->parent = fctx;
  577. p->avctx = copy;
  578. if (!copy) {
  579. err = AVERROR(ENOMEM);
  580. goto error;
  581. }
  582. *copy = *src;
  583. copy->thread_opaque = p;
  584. copy->pkt = &p->avpkt;
  585. if (!i) {
  586. src = copy;
  587. if (codec->init)
  588. err = codec->init(copy);
  589. update_context_from_thread(avctx, copy, 1);
  590. } else {
  591. copy->priv_data = av_malloc(codec->priv_data_size);
  592. if (!copy->priv_data) {
  593. err = AVERROR(ENOMEM);
  594. goto error;
  595. }
  596. memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
  597. copy->internal = av_malloc(sizeof(AVCodecInternal));
  598. if (!copy->internal) {
  599. err = AVERROR(ENOMEM);
  600. goto error;
  601. }
  602. *(copy->internal) = *(src->internal);
  603. copy->internal->is_copy = 1;
  604. if (codec->init_thread_copy)
  605. err = codec->init_thread_copy(copy);
  606. }
  607. if (err) goto error;
  608. pthread_create(&p->thread, NULL, frame_worker_thread, p);
  609. }
  610. return 0;
  611. error:
  612. frame_thread_free(avctx, i+1);
  613. return err;
  614. }
  615. void ff_thread_flush(AVCodecContext *avctx)
  616. {
  617. FrameThreadContext *fctx = avctx->thread_opaque;
  618. if (!avctx->thread_opaque) return;
  619. park_frame_worker_threads(fctx, avctx->thread_count);
  620. if (fctx->prev_thread) {
  621. if (fctx->prev_thread != &fctx->threads[0])
  622. update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
  623. if (avctx->codec->flush)
  624. avctx->codec->flush(fctx->threads[0].avctx);
  625. }
  626. fctx->next_decoding = fctx->next_finished = 0;
  627. fctx->delaying = 1;
  628. fctx->prev_thread = NULL;
  629. }
  630. static int *allocate_progress(PerThreadContext *p)
  631. {
  632. int i;
  633. for (i = 0; i < MAX_BUFFERS; i++)
  634. if (!p->progress_used[i]) break;
  635. if (i == MAX_BUFFERS) {
  636. av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
  637. return NULL;
  638. }
  639. p->progress_used[i] = 1;
  640. return p->progress[i];
  641. }
  642. int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
  643. {
  644. PerThreadContext *p = avctx->thread_opaque;
  645. int *progress, err;
  646. f->owner = avctx;
  647. ff_init_buffer_info(avctx, f);
  648. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
  649. f->thread_opaque = NULL;
  650. return avctx->get_buffer(avctx, f);
  651. }
  652. if (p->state != STATE_SETTING_UP &&
  653. (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
  654. av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
  655. return -1;
  656. }
  657. pthread_mutex_lock(&p->parent->buffer_mutex);
  658. f->thread_opaque = progress = allocate_progress(p);
  659. if (!progress) {
  660. pthread_mutex_unlock(&p->parent->buffer_mutex);
  661. return -1;
  662. }
  663. progress[0] =
  664. progress[1] = -1;
  665. if (avctx->thread_safe_callbacks ||
  666. avctx->get_buffer == avcodec_default_get_buffer) {
  667. err = avctx->get_buffer(avctx, f);
  668. } else {
  669. p->requested_frame = f;
  670. p->state = STATE_GET_BUFFER;
  671. pthread_mutex_lock(&p->progress_mutex);
  672. pthread_cond_signal(&p->progress_cond);
  673. while (p->state != STATE_SETTING_UP)
  674. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  675. err = p->result;
  676. pthread_mutex_unlock(&p->progress_mutex);
  677. if (!avctx->codec->update_thread_context)
  678. ff_thread_finish_setup(avctx);
  679. }
  680. pthread_mutex_unlock(&p->parent->buffer_mutex);
  681. /*
  682. * Buffer age is difficult to keep track of between
  683. * multiple threads, and the optimizations it allows
  684. * are not worth the effort. It is disabled for now.
  685. */
  686. f->age = INT_MAX;
  687. return err;
  688. }
  689. void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
  690. {
  691. PerThreadContext *p = avctx->thread_opaque;
  692. FrameThreadContext *fctx;
  693. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
  694. avctx->release_buffer(avctx, f);
  695. return;
  696. }
  697. if (p->num_released_buffers >= MAX_BUFFERS) {
  698. av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
  699. return;
  700. }
  701. if(avctx->debug & FF_DEBUG_BUFFERS)
  702. av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
  703. fctx = p->parent;
  704. pthread_mutex_lock(&fctx->buffer_mutex);
  705. p->released_buffers[p->num_released_buffers++] = *f;
  706. pthread_mutex_unlock(&fctx->buffer_mutex);
  707. memset(f->data, 0, sizeof(f->data));
  708. }
  709. /**
  710. * Set the threading algorithms used.
  711. *
  712. * Threading requires more than one thread.
  713. * Frame threading requires entire frames to be passed to the codec,
  714. * and introduces extra decoding delay, so is incompatible with low_delay.
  715. *
  716. * @param avctx The context.
  717. */
  718. static void validate_thread_parameters(AVCodecContext *avctx)
  719. {
  720. int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
  721. && !(avctx->flags & CODEC_FLAG_TRUNCATED)
  722. && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
  723. && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
  724. if (avctx->thread_count == 1) {
  725. avctx->active_thread_type = 0;
  726. } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
  727. avctx->active_thread_type = FF_THREAD_FRAME;
  728. } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
  729. avctx->thread_type & FF_THREAD_SLICE) {
  730. avctx->active_thread_type = FF_THREAD_SLICE;
  731. }
  732. }
  733. int ff_thread_init(AVCodecContext *avctx)
  734. {
  735. if (avctx->thread_opaque) {
  736. av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
  737. return -1;
  738. }
  739. #if HAVE_W32THREADS
  740. w32thread_init();
  741. #endif
  742. if (avctx->codec) {
  743. validate_thread_parameters(avctx);
  744. if (avctx->active_thread_type&FF_THREAD_SLICE)
  745. return thread_init(avctx);
  746. else if (avctx->active_thread_type&FF_THREAD_FRAME)
  747. return frame_thread_init(avctx);
  748. }
  749. return 0;
  750. }
  751. void ff_thread_free(AVCodecContext *avctx)
  752. {
  753. if (avctx->active_thread_type&FF_THREAD_FRAME)
  754. frame_thread_free(avctx, avctx->thread_count);
  755. else
  756. thread_free(avctx);
  757. }