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.

923 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 "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+1)
  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. ff_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 && avctx->thread_safe_callbacks)
  244. ff_thread_finish_setup(avctx);
  245. pthread_mutex_lock(&p->mutex);
  246. avcodec_get_frame_defaults(&p->frame);
  247. p->got_frame = 0;
  248. p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
  249. if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
  250. p->state = STATE_INPUT_READY;
  251. pthread_mutex_lock(&p->progress_mutex);
  252. pthread_cond_signal(&p->output_cond);
  253. pthread_mutex_unlock(&p->progress_mutex);
  254. pthread_mutex_unlock(&p->mutex);
  255. }
  256. return NULL;
  257. }
  258. /**
  259. * Updates the next thread's AVCodecContext with values from the reference thread's context.
  260. *
  261. * @param dst The destination context.
  262. * @param src The source context.
  263. * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
  264. */
  265. static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
  266. {
  267. int err = 0;
  268. if (dst != src) {
  269. dst->sub_id = src->sub_id;
  270. dst->time_base = src->time_base;
  271. dst->width = src->width;
  272. dst->height = src->height;
  273. dst->pix_fmt = src->pix_fmt;
  274. dst->coded_width = src->coded_width;
  275. dst->coded_height = src->coded_height;
  276. dst->has_b_frames = src->has_b_frames;
  277. dst->idct_algo = src->idct_algo;
  278. dst->slice_count = src->slice_count;
  279. dst->bits_per_coded_sample = src->bits_per_coded_sample;
  280. dst->sample_aspect_ratio = src->sample_aspect_ratio;
  281. dst->dtg_active_format = src->dtg_active_format;
  282. dst->profile = src->profile;
  283. dst->level = src->level;
  284. dst->bits_per_raw_sample = src->bits_per_raw_sample;
  285. dst->ticks_per_frame = src->ticks_per_frame;
  286. dst->color_primaries = src->color_primaries;
  287. dst->color_trc = src->color_trc;
  288. dst->colorspace = src->colorspace;
  289. dst->color_range = src->color_range;
  290. dst->chroma_sample_location = src->chroma_sample_location;
  291. }
  292. if (for_user) {
  293. dst->coded_frame = src->coded_frame;
  294. dst->has_b_frames += src->thread_count - 1;
  295. } else {
  296. if (dst->codec->update_thread_context)
  297. err = dst->codec->update_thread_context(dst, src);
  298. }
  299. return err;
  300. }
  301. /**
  302. * Update the next thread's AVCodecContext with values set by the user.
  303. *
  304. * @param dst The destination context.
  305. * @param src The source context.
  306. */
  307. static void update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
  308. {
  309. #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
  310. dst->flags = src->flags;
  311. dst->draw_horiz_band= src->draw_horiz_band;
  312. dst->get_buffer = src->get_buffer;
  313. dst->release_buffer = src->release_buffer;
  314. dst->opaque = src->opaque;
  315. #if FF_API_HURRY_UP
  316. dst->hurry_up = src->hurry_up;
  317. #endif
  318. dst->dsp_mask = src->dsp_mask;
  319. dst->debug = src->debug;
  320. dst->debug_mv = src->debug_mv;
  321. dst->slice_flags = src->slice_flags;
  322. dst->flags2 = src->flags2;
  323. copy_fields(skip_loop_filter, bidir_refine);
  324. dst->frame_number = src->frame_number;
  325. dst->reordered_opaque = src->reordered_opaque;
  326. #undef copy_fields
  327. }
  328. static void free_progress(AVFrame *f)
  329. {
  330. PerThreadContext *p = f->owner->thread_opaque;
  331. int *progress = f->thread_opaque;
  332. p->progress_used[(progress - p->progress[0]) / 2] = 0;
  333. }
  334. /// Releases the buffers that this decoding thread was the last user of.
  335. static void release_delayed_buffers(PerThreadContext *p)
  336. {
  337. FrameThreadContext *fctx = p->parent;
  338. while (p->num_released_buffers > 0) {
  339. AVFrame *f;
  340. pthread_mutex_lock(&fctx->buffer_mutex);
  341. f = &p->released_buffers[--p->num_released_buffers];
  342. free_progress(f);
  343. f->thread_opaque = NULL;
  344. f->owner->release_buffer(f->owner, f);
  345. pthread_mutex_unlock(&fctx->buffer_mutex);
  346. }
  347. }
  348. static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
  349. {
  350. FrameThreadContext *fctx = p->parent;
  351. PerThreadContext *prev_thread = fctx->prev_thread;
  352. AVCodec *codec = p->avctx->codec;
  353. uint8_t *buf = p->avpkt.data;
  354. if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
  355. pthread_mutex_lock(&p->mutex);
  356. release_delayed_buffers(p);
  357. if (prev_thread) {
  358. int err;
  359. if (prev_thread->state == STATE_SETTING_UP) {
  360. pthread_mutex_lock(&prev_thread->progress_mutex);
  361. while (prev_thread->state == STATE_SETTING_UP)
  362. pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
  363. pthread_mutex_unlock(&prev_thread->progress_mutex);
  364. }
  365. err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
  366. if (err) {
  367. pthread_mutex_unlock(&p->mutex);
  368. return err;
  369. }
  370. }
  371. av_fast_malloc(&buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
  372. p->avpkt = *avpkt;
  373. p->avpkt.data = buf;
  374. memcpy(buf, avpkt->data, avpkt->size);
  375. memset(buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  376. p->state = STATE_SETTING_UP;
  377. pthread_cond_signal(&p->input_cond);
  378. pthread_mutex_unlock(&p->mutex);
  379. /*
  380. * If the client doesn't have a thread-safe get_buffer(),
  381. * then decoding threads call back to the main thread,
  382. * and it calls back to the client here.
  383. */
  384. if (!p->avctx->thread_safe_callbacks &&
  385. p->avctx->get_buffer != avcodec_default_get_buffer) {
  386. while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
  387. pthread_mutex_lock(&p->progress_mutex);
  388. while (p->state == STATE_SETTING_UP)
  389. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  390. if (p->state == STATE_GET_BUFFER) {
  391. p->result = p->avctx->get_buffer(p->avctx, p->requested_frame);
  392. p->state = STATE_SETTING_UP;
  393. pthread_cond_signal(&p->progress_cond);
  394. }
  395. pthread_mutex_unlock(&p->progress_mutex);
  396. }
  397. }
  398. fctx->prev_thread = p;
  399. return 0;
  400. }
  401. int ff_thread_decode_frame(AVCodecContext *avctx,
  402. AVFrame *picture, int *got_picture_ptr,
  403. AVPacket *avpkt)
  404. {
  405. FrameThreadContext *fctx = avctx->thread_opaque;
  406. int finished = fctx->next_finished;
  407. PerThreadContext *p;
  408. int err;
  409. /*
  410. * Submit a packet to the next decoding thread.
  411. */
  412. p = &fctx->threads[fctx->next_decoding];
  413. update_context_from_user(p->avctx, avctx);
  414. err = submit_packet(p, avpkt);
  415. if (err) return err;
  416. fctx->next_decoding++;
  417. /*
  418. * If we're still receiving the initial packets, don't return a frame.
  419. */
  420. if (fctx->delaying && avpkt->size) {
  421. if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
  422. *got_picture_ptr=0;
  423. return 0;
  424. }
  425. /*
  426. * Return the next available frame from the oldest thread.
  427. * If we're at the end of the stream, then we have to skip threads that
  428. * didn't output a frame, because we don't want to accidentally signal
  429. * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
  430. */
  431. do {
  432. p = &fctx->threads[finished++];
  433. if (p->state != STATE_INPUT_READY) {
  434. pthread_mutex_lock(&p->progress_mutex);
  435. while (p->state != STATE_INPUT_READY)
  436. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  437. pthread_mutex_unlock(&p->progress_mutex);
  438. }
  439. *picture = p->frame;
  440. *got_picture_ptr = p->got_frame;
  441. picture->pkt_dts = p->avpkt.dts;
  442. /*
  443. * A later call with avkpt->size == 0 may loop over all threads,
  444. * including this one, searching for a frame to return before being
  445. * stopped by the "finished != fctx->next_finished" condition.
  446. * Make sure we don't mistakenly return the same frame again.
  447. */
  448. p->got_frame = 0;
  449. if (finished >= avctx->thread_count) finished = 0;
  450. } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
  451. update_context_from_thread(avctx, p->avctx, 1);
  452. if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
  453. fctx->next_finished = finished;
  454. return p->result;
  455. }
  456. void ff_thread_report_progress(AVFrame *f, int n, int field)
  457. {
  458. PerThreadContext *p;
  459. int *progress = f->thread_opaque;
  460. if (!progress || progress[field] >= n) return;
  461. p = f->owner->thread_opaque;
  462. if (f->owner->debug&FF_DEBUG_THREADS)
  463. av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
  464. pthread_mutex_lock(&p->progress_mutex);
  465. progress[field] = n;
  466. pthread_cond_broadcast(&p->progress_cond);
  467. pthread_mutex_unlock(&p->progress_mutex);
  468. }
  469. void ff_thread_await_progress(AVFrame *f, int n, int field)
  470. {
  471. PerThreadContext *p;
  472. int *progress = f->thread_opaque;
  473. if (!progress || progress[field] >= n) return;
  474. p = f->owner->thread_opaque;
  475. if (f->owner->debug&FF_DEBUG_THREADS)
  476. av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
  477. pthread_mutex_lock(&p->progress_mutex);
  478. while (progress[field] < n)
  479. pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
  480. pthread_mutex_unlock(&p->progress_mutex);
  481. }
  482. void ff_thread_finish_setup(AVCodecContext *avctx) {
  483. PerThreadContext *p = avctx->thread_opaque;
  484. if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
  485. pthread_mutex_lock(&p->progress_mutex);
  486. p->state = STATE_SETUP_FINISHED;
  487. pthread_cond_broadcast(&p->progress_cond);
  488. pthread_mutex_unlock(&p->progress_mutex);
  489. }
  490. /// Waits for all threads to finish.
  491. static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
  492. {
  493. int i;
  494. for (i = 0; i < thread_count; i++) {
  495. PerThreadContext *p = &fctx->threads[i];
  496. if (p->state != STATE_INPUT_READY) {
  497. pthread_mutex_lock(&p->progress_mutex);
  498. while (p->state != STATE_INPUT_READY)
  499. pthread_cond_wait(&p->output_cond, &p->progress_mutex);
  500. pthread_mutex_unlock(&p->progress_mutex);
  501. }
  502. }
  503. }
  504. static void frame_thread_free(AVCodecContext *avctx, int thread_count)
  505. {
  506. FrameThreadContext *fctx = avctx->thread_opaque;
  507. AVCodec *codec = avctx->codec;
  508. int i;
  509. park_frame_worker_threads(fctx, thread_count);
  510. if (fctx->prev_thread)
  511. update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
  512. fctx->die = 1;
  513. for (i = 0; i < thread_count; i++) {
  514. PerThreadContext *p = &fctx->threads[i];
  515. pthread_mutex_lock(&p->mutex);
  516. pthread_cond_signal(&p->input_cond);
  517. pthread_mutex_unlock(&p->mutex);
  518. pthread_join(p->thread, NULL);
  519. if (codec->close)
  520. codec->close(p->avctx);
  521. avctx->codec = NULL;
  522. release_delayed_buffers(p);
  523. }
  524. for (i = 0; i < thread_count; i++) {
  525. PerThreadContext *p = &fctx->threads[i];
  526. avcodec_default_free_buffers(p->avctx);
  527. pthread_mutex_destroy(&p->mutex);
  528. pthread_mutex_destroy(&p->progress_mutex);
  529. pthread_cond_destroy(&p->input_cond);
  530. pthread_cond_destroy(&p->progress_cond);
  531. pthread_cond_destroy(&p->output_cond);
  532. av_freep(&p->avpkt.data);
  533. if (i)
  534. av_freep(&p->avctx->priv_data);
  535. av_freep(&p->avctx);
  536. }
  537. av_freep(&fctx->threads);
  538. pthread_mutex_destroy(&fctx->buffer_mutex);
  539. av_freep(&avctx->thread_opaque);
  540. }
  541. static int frame_thread_init(AVCodecContext *avctx)
  542. {
  543. int thread_count = avctx->thread_count;
  544. AVCodec *codec = avctx->codec;
  545. AVCodecContext *src = avctx;
  546. FrameThreadContext *fctx;
  547. int i, err = 0;
  548. if (thread_count <= 1) {
  549. avctx->active_thread_type = 0;
  550. return 0;
  551. }
  552. avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
  553. fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
  554. pthread_mutex_init(&fctx->buffer_mutex, NULL);
  555. fctx->delaying = 1;
  556. for (i = 0; i < thread_count; i++) {
  557. AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
  558. PerThreadContext *p = &fctx->threads[i];
  559. pthread_mutex_init(&p->mutex, NULL);
  560. pthread_mutex_init(&p->progress_mutex, NULL);
  561. pthread_cond_init(&p->input_cond, NULL);
  562. pthread_cond_init(&p->progress_cond, NULL);
  563. pthread_cond_init(&p->output_cond, NULL);
  564. p->parent = fctx;
  565. p->avctx = copy;
  566. *copy = *src;
  567. copy->thread_opaque = p;
  568. copy->pkt = &p->avpkt;
  569. if (!i) {
  570. src = copy;
  571. if (codec->init)
  572. err = codec->init(copy);
  573. update_context_from_thread(avctx, copy, 1);
  574. } else {
  575. copy->is_copy = 1;
  576. copy->priv_data = av_malloc(codec->priv_data_size);
  577. memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
  578. if (codec->init_thread_copy)
  579. err = codec->init_thread_copy(copy);
  580. }
  581. if (err) goto error;
  582. pthread_create(&p->thread, NULL, frame_worker_thread, p);
  583. }
  584. return 0;
  585. error:
  586. frame_thread_free(avctx, i+1);
  587. return err;
  588. }
  589. void ff_thread_flush(AVCodecContext *avctx)
  590. {
  591. FrameThreadContext *fctx = avctx->thread_opaque;
  592. if (!avctx->thread_opaque) return;
  593. park_frame_worker_threads(fctx, avctx->thread_count);
  594. if (fctx->prev_thread) {
  595. if (fctx->prev_thread != &fctx->threads[0])
  596. update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
  597. if (avctx->codec->flush)
  598. avctx->codec->flush(fctx->threads[0].avctx);
  599. }
  600. fctx->next_decoding = fctx->next_finished = 0;
  601. fctx->delaying = 1;
  602. fctx->prev_thread = NULL;
  603. }
  604. static int *allocate_progress(PerThreadContext *p)
  605. {
  606. int i;
  607. for (i = 0; i < MAX_BUFFERS; i++)
  608. if (!p->progress_used[i]) break;
  609. if (i == MAX_BUFFERS) {
  610. av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
  611. return NULL;
  612. }
  613. p->progress_used[i] = 1;
  614. return p->progress[i];
  615. }
  616. int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
  617. {
  618. PerThreadContext *p = avctx->thread_opaque;
  619. int *progress, err;
  620. f->owner = avctx;
  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. }