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.

901 lines
27KB

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