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.

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