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.

961 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 || avctx->get_buffer == avcodec_default_get_buffer))
  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. dst->thread_safe_callbacks = src->thread_safe_callbacks;
  333. #undef copy_fields
  334. }
  335. static void free_progress(AVFrame *f)
  336. {
  337. PerThreadContext *p = f->owner->thread_opaque;
  338. int *progress = f->thread_opaque;
  339. p->progress_used[(progress - p->progress[0]) / 2] = 0;
  340. }
  341. /// Releases the buffers that this decoding thread was the last user of.
  342. static void release_delayed_buffers(PerThreadContext *p)
  343. {
  344. FrameThreadContext *fctx = p->parent;
  345. while (p->num_released_buffers > 0) {
  346. AVFrame *f;
  347. pthread_mutex_lock(&fctx->buffer_mutex);
  348. f = &p->released_buffers[--p->num_released_buffers];
  349. free_progress(f);
  350. f->thread_opaque = NULL;
  351. f->owner->release_buffer(f->owner, f);
  352. pthread_mutex_unlock(&fctx->buffer_mutex);
  353. }
  354. }
  355. static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
  356. {
  357. FrameThreadContext *fctx = p->parent;
  358. PerThreadContext *prev_thread = fctx->prev_thread;
  359. AVCodec *codec = p->avctx->codec;
  360. uint8_t *buf = p->avpkt.data;
  361. if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
  362. pthread_mutex_lock(&p->mutex);
  363. release_delayed_buffers(p);
  364. if (prev_thread) {
  365. int err;
  366. if (prev_thread->state == STATE_SETTING_UP) {
  367. pthread_mutex_lock(&prev_thread->progress_mutex);
  368. while (prev_thread->state == STATE_SETTING_UP)
  369. pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
  370. pthread_mutex_unlock(&prev_thread->progress_mutex);
  371. }
  372. err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
  373. if (err) {
  374. pthread_mutex_unlock(&p->mutex);
  375. return err;
  376. }
  377. }
  378. av_fast_malloc(&buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
  379. p->avpkt = *avpkt;
  380. p->avpkt.data = buf;
  381. memcpy(buf, avpkt->data, avpkt->size);
  382. memset(buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  383. p->state = STATE_SETTING_UP;
  384. pthread_cond_signal(&p->input_cond);
  385. pthread_mutex_unlock(&p->mutex);
  386. /*
  387. * If the client doesn't have a thread-safe get_buffer(),
  388. * then decoding threads call back to the main thread,
  389. * and it calls back to the client here.
  390. */
  391. if (!p->avctx->thread_safe_callbacks &&
  392. p->avctx->get_buffer != avcodec_default_get_buffer) {
  393. while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
  394. pthread_mutex_lock(&p->progress_mutex);
  395. while (p->state == STATE_SETTING_UP)
  396. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  397. if (p->state == STATE_GET_BUFFER) {
  398. p->result = p->avctx->get_buffer(p->avctx, p->requested_frame);
  399. p->state = STATE_SETTING_UP;
  400. pthread_cond_signal(&p->progress_cond);
  401. }
  402. pthread_mutex_unlock(&p->progress_mutex);
  403. }
  404. }
  405. fctx->prev_thread = p;
  406. fctx->next_decoding++;
  407. return 0;
  408. }
  409. int ff_thread_decode_frame(AVCodecContext *avctx,
  410. AVFrame *picture, int *got_picture_ptr,
  411. AVPacket *avpkt)
  412. {
  413. FrameThreadContext *fctx = avctx->thread_opaque;
  414. int finished = fctx->next_finished;
  415. PerThreadContext *p;
  416. int err;
  417. /*
  418. * Submit a packet to the next decoding thread.
  419. */
  420. p = &fctx->threads[fctx->next_decoding];
  421. update_context_from_user(p->avctx, avctx);
  422. err = submit_packet(p, avpkt);
  423. if (err) return err;
  424. /*
  425. * If we're still receiving the initial packets, don't return a frame.
  426. */
  427. if (fctx->delaying && avpkt->size) {
  428. if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
  429. *got_picture_ptr=0;
  430. return avpkt->size;
  431. }
  432. /*
  433. * Return the next available frame from the oldest thread.
  434. * If we're at the end of the stream, then we have to skip threads that
  435. * didn't output a frame, because we don't want to accidentally signal
  436. * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
  437. */
  438. do {
  439. p = &fctx->threads[finished++];
  440. if (p->state != STATE_INPUT_READY) {
  441. pthread_mutex_lock(&p->progress_mutex);
  442. while (p->state != STATE_INPUT_READY)
  443. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  444. pthread_mutex_unlock(&p->progress_mutex);
  445. }
  446. *picture = p->frame;
  447. *got_picture_ptr = p->got_frame;
  448. picture->pkt_dts = p->avpkt.dts;
  449. /*
  450. * A later call with avkpt->size == 0 may loop over all threads,
  451. * including this one, searching for a frame to return before being
  452. * stopped by the "finished != fctx->next_finished" condition.
  453. * Make sure we don't mistakenly return the same frame again.
  454. */
  455. p->got_frame = 0;
  456. if (finished >= avctx->thread_count) finished = 0;
  457. } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
  458. update_context_from_thread(avctx, p->avctx, 1);
  459. if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
  460. fctx->next_finished = finished;
  461. /* return the size of the consumed packet if no error occurred */
  462. return (p->result >= 0) ? avpkt->size : p->result;
  463. }
  464. void ff_thread_report_progress(AVFrame *f, int n, int field)
  465. {
  466. PerThreadContext *p;
  467. int *progress = f->thread_opaque;
  468. if (!progress || progress[field] >= n) return;
  469. p = f->owner->thread_opaque;
  470. if (f->owner->debug&FF_DEBUG_THREADS)
  471. av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
  472. pthread_mutex_lock(&p->progress_mutex);
  473. progress[field] = n;
  474. pthread_cond_broadcast(&p->progress_cond);
  475. pthread_mutex_unlock(&p->progress_mutex);
  476. }
  477. void ff_thread_await_progress(AVFrame *f, int n, int field)
  478. {
  479. PerThreadContext *p;
  480. int *progress = f->thread_opaque;
  481. if (!progress || progress[field] >= n) return;
  482. p = f->owner->thread_opaque;
  483. if (f->owner->debug&FF_DEBUG_THREADS)
  484. av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
  485. pthread_mutex_lock(&p->progress_mutex);
  486. while (progress[field] < n)
  487. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  488. pthread_mutex_unlock(&p->progress_mutex);
  489. }
  490. void ff_thread_finish_setup(AVCodecContext *avctx) {
  491. PerThreadContext *p = avctx->thread_opaque;
  492. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
  493. if(p->state == STATE_SETUP_FINISHED){
  494. av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
  495. }
  496. pthread_mutex_lock(&p->progress_mutex);
  497. p->state = STATE_SETUP_FINISHED;
  498. pthread_cond_broadcast(&p->progress_cond);
  499. pthread_mutex_unlock(&p->progress_mutex);
  500. }
  501. /// Waits for all threads to finish.
  502. static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
  503. {
  504. int i;
  505. for (i = 0; i < thread_count; i++) {
  506. PerThreadContext *p = &fctx->threads[i];
  507. if (p->state != STATE_INPUT_READY) {
  508. pthread_mutex_lock(&p->progress_mutex);
  509. while (p->state != STATE_INPUT_READY)
  510. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  511. pthread_mutex_unlock(&p->progress_mutex);
  512. }
  513. }
  514. }
  515. static void frame_thread_free(AVCodecContext *avctx, int thread_count)
  516. {
  517. FrameThreadContext *fctx = avctx->thread_opaque;
  518. AVCodec *codec = avctx->codec;
  519. int i;
  520. park_frame_worker_threads(fctx, thread_count);
  521. if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
  522. update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
  523. fctx->die = 1;
  524. for (i = 0; i < thread_count; i++) {
  525. PerThreadContext *p = &fctx->threads[i];
  526. pthread_mutex_lock(&p->mutex);
  527. pthread_cond_signal(&p->input_cond);
  528. pthread_mutex_unlock(&p->mutex);
  529. if (p->thread_init)
  530. pthread_join(p->thread, NULL);
  531. p->thread_init=0;
  532. if (codec->close)
  533. codec->close(p->avctx);
  534. avctx->codec = NULL;
  535. release_delayed_buffers(p);
  536. }
  537. for (i = 0; i < thread_count; i++) {
  538. PerThreadContext *p = &fctx->threads[i];
  539. avcodec_default_free_buffers(p->avctx);
  540. pthread_mutex_destroy(&p->mutex);
  541. pthread_mutex_destroy(&p->progress_mutex);
  542. pthread_cond_destroy(&p->input_cond);
  543. pthread_cond_destroy(&p->progress_cond);
  544. pthread_cond_destroy(&p->output_cond);
  545. av_freep(&p->avpkt.data);
  546. if (i) {
  547. av_freep(&p->avctx->priv_data);
  548. av_freep(&p->avctx->internal);
  549. }
  550. av_freep(&p->avctx);
  551. }
  552. av_freep(&fctx->threads);
  553. pthread_mutex_destroy(&fctx->buffer_mutex);
  554. av_freep(&avctx->thread_opaque);
  555. }
  556. static int frame_thread_init(AVCodecContext *avctx)
  557. {
  558. int thread_count = avctx->thread_count;
  559. AVCodec *codec = avctx->codec;
  560. AVCodecContext *src = avctx;
  561. FrameThreadContext *fctx;
  562. int i, err = 0;
  563. if (thread_count <= 1) {
  564. avctx->active_thread_type = 0;
  565. return 0;
  566. }
  567. avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
  568. fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
  569. pthread_mutex_init(&fctx->buffer_mutex, NULL);
  570. fctx->delaying = 1;
  571. for (i = 0; i < thread_count; i++) {
  572. AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
  573. PerThreadContext *p = &fctx->threads[i];
  574. pthread_mutex_init(&p->mutex, NULL);
  575. pthread_mutex_init(&p->progress_mutex, NULL);
  576. pthread_cond_init(&p->input_cond, NULL);
  577. pthread_cond_init(&p->progress_cond, NULL);
  578. pthread_cond_init(&p->output_cond, NULL);
  579. p->parent = fctx;
  580. p->avctx = copy;
  581. if (!copy) {
  582. err = AVERROR(ENOMEM);
  583. goto error;
  584. }
  585. *copy = *src;
  586. copy->thread_opaque = p;
  587. copy->pkt = &p->avpkt;
  588. if (!i) {
  589. src = copy;
  590. if (codec->init)
  591. err = codec->init(copy);
  592. update_context_from_thread(avctx, copy, 1);
  593. } else {
  594. copy->priv_data = av_malloc(codec->priv_data_size);
  595. if (!copy->priv_data) {
  596. err = AVERROR(ENOMEM);
  597. goto error;
  598. }
  599. memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
  600. copy->internal = av_malloc(sizeof(AVCodecInternal));
  601. if (!copy->internal) {
  602. err = AVERROR(ENOMEM);
  603. goto error;
  604. }
  605. *(copy->internal) = *(src->internal);
  606. copy->internal->is_copy = 1;
  607. if (codec->init_thread_copy)
  608. err = codec->init_thread_copy(copy);
  609. }
  610. if (err) goto error;
  611. p->thread_init= !pthread_create(&p->thread, NULL, frame_worker_thread, p);
  612. if(!p->thread_init)
  613. goto error;
  614. }
  615. return 0;
  616. error:
  617. frame_thread_free(avctx, i+1);
  618. return err;
  619. }
  620. void ff_thread_flush(AVCodecContext *avctx)
  621. {
  622. FrameThreadContext *fctx = avctx->thread_opaque;
  623. if (!avctx->thread_opaque) return;
  624. park_frame_worker_threads(fctx, avctx->thread_count);
  625. if (fctx->prev_thread) {
  626. if (fctx->prev_thread != &fctx->threads[0])
  627. update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
  628. if (avctx->codec->flush)
  629. avctx->codec->flush(fctx->threads[0].avctx);
  630. }
  631. fctx->next_decoding = fctx->next_finished = 0;
  632. fctx->delaying = 1;
  633. fctx->prev_thread = NULL;
  634. }
  635. static int *allocate_progress(PerThreadContext *p)
  636. {
  637. int i;
  638. for (i = 0; i < MAX_BUFFERS; i++)
  639. if (!p->progress_used[i]) break;
  640. if (i == MAX_BUFFERS) {
  641. av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
  642. return NULL;
  643. }
  644. p->progress_used[i] = 1;
  645. return p->progress[i];
  646. }
  647. int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
  648. {
  649. PerThreadContext *p = avctx->thread_opaque;
  650. int *progress, err;
  651. f->owner = avctx;
  652. ff_init_buffer_info(avctx, f);
  653. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
  654. f->thread_opaque = NULL;
  655. return avctx->get_buffer(avctx, f);
  656. }
  657. if (p->state != STATE_SETTING_UP &&
  658. (avctx->codec->update_thread_context || (!avctx->thread_safe_callbacks &&
  659. avctx->get_buffer != avcodec_default_get_buffer))) {
  660. av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
  661. return -1;
  662. }
  663. pthread_mutex_lock(&p->parent->buffer_mutex);
  664. f->thread_opaque = progress = allocate_progress(p);
  665. if (!progress) {
  666. pthread_mutex_unlock(&p->parent->buffer_mutex);
  667. return -1;
  668. }
  669. progress[0] =
  670. progress[1] = -1;
  671. if (avctx->thread_safe_callbacks ||
  672. avctx->get_buffer == avcodec_default_get_buffer) {
  673. err = avctx->get_buffer(avctx, f);
  674. } else {
  675. p->requested_frame = f;
  676. p->state = STATE_GET_BUFFER;
  677. pthread_mutex_lock(&p->progress_mutex);
  678. pthread_cond_signal(&p->progress_cond);
  679. while (p->state != STATE_SETTING_UP)
  680. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  681. err = p->result;
  682. pthread_mutex_unlock(&p->progress_mutex);
  683. if (!avctx->codec->update_thread_context)
  684. ff_thread_finish_setup(avctx);
  685. }
  686. pthread_mutex_unlock(&p->parent->buffer_mutex);
  687. /*
  688. * Buffer age is difficult to keep track of between
  689. * multiple threads, and the optimizations it allows
  690. * are not worth the effort. It is disabled for now.
  691. */
  692. f->age = INT_MAX;
  693. return err;
  694. }
  695. void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
  696. {
  697. PerThreadContext *p = avctx->thread_opaque;
  698. FrameThreadContext *fctx;
  699. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
  700. avctx->release_buffer(avctx, f);
  701. return;
  702. }
  703. if (p->num_released_buffers >= MAX_BUFFERS) {
  704. av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
  705. return;
  706. }
  707. if(avctx->debug & FF_DEBUG_BUFFERS)
  708. av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
  709. fctx = p->parent;
  710. pthread_mutex_lock(&fctx->buffer_mutex);
  711. p->released_buffers[p->num_released_buffers++] = *f;
  712. pthread_mutex_unlock(&fctx->buffer_mutex);
  713. memset(f->data, 0, sizeof(f->data));
  714. }
  715. /**
  716. * Set the threading algorithms used.
  717. *
  718. * Threading requires more than one thread.
  719. * Frame threading requires entire frames to be passed to the codec,
  720. * and introduces extra decoding delay, so is incompatible with low_delay.
  721. *
  722. * @param avctx The context.
  723. */
  724. static void validate_thread_parameters(AVCodecContext *avctx)
  725. {
  726. int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
  727. && !(avctx->flags & CODEC_FLAG_TRUNCATED)
  728. && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
  729. && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
  730. if (avctx->thread_count == 1) {
  731. avctx->active_thread_type = 0;
  732. } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
  733. avctx->active_thread_type = FF_THREAD_FRAME;
  734. } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
  735. avctx->thread_type & FF_THREAD_SLICE) {
  736. avctx->active_thread_type = FF_THREAD_SLICE;
  737. }
  738. }
  739. int ff_thread_init(AVCodecContext *avctx)
  740. {
  741. if (avctx->thread_opaque) {
  742. av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
  743. return -1;
  744. }
  745. #if HAVE_W32THREADS
  746. w32thread_init();
  747. #endif
  748. if (avctx->codec) {
  749. validate_thread_parameters(avctx);
  750. if (avctx->active_thread_type&FF_THREAD_SLICE)
  751. return thread_init(avctx);
  752. else if (avctx->active_thread_type&FF_THREAD_FRAME)
  753. return frame_thread_init(avctx);
  754. }
  755. return 0;
  756. }
  757. void ff_thread_free(AVCodecContext *avctx)
  758. {
  759. if (avctx->active_thread_type&FF_THREAD_FRAME)
  760. frame_thread_free(avctx, avctx->thread_count);
  761. else
  762. thread_free(avctx);
  763. }