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.

924 lines
28KB

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