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.

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