FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
pthread.c
Go to the documentation of this file.
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 /**
27  * @file
28  * Multithreading support functions
29  * @see doc/multithreading.txt
30  */
31 
32 #include "config.h"
33 
34 #include "avcodec.h"
35 #include "internal.h"
36 #include "thread.h"
37 #include "libavutil/avassert.h"
38 #include "libavutil/common.h"
39 #include "libavutil/cpu.h"
40 #include "libavutil/internal.h"
41 
42 #if HAVE_PTHREADS
43 #include <pthread.h>
44 #elif HAVE_W32THREADS
45 #include "compat/w32pthreads.h"
46 #elif HAVE_OS2THREADS
47 #include "compat/os2threads.h"
48 #endif
49 
50 typedef int (action_func)(AVCodecContext *c, void *arg);
51 typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
52 
53 typedef struct ThreadContext {
57  void *args;
58  int *rets;
60  int job_count;
61  int job_size;
62 
66  unsigned current_execute;
68  int done;
69 
70  int *entries;
76 
77 /**
78  * Context used by codec threads and stored in their AVCodecContext thread_opaque.
79  */
80 typedef struct PerThreadContext {
82 
85  pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
86  pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
87  pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
88 
89  pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
90  pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
91 
92  AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
93 
94  AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
95  uint8_t *buf; ///< backup storage for packet data when the input packet is not refcounted
96  int allocated_buf_size; ///< Size allocated for buf
97 
98  AVFrame *frame; ///< Output frame (for decoding) or input (for encoding).
99  int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
100  int result; ///< The result of the last codec decode/encode() call.
101 
102  enum {
103  STATE_INPUT_READY, ///< Set when the thread is awaiting a packet.
104  STATE_SETTING_UP, ///< Set before the codec has called ff_thread_finish_setup().
106  * Set when the codec calls get_buffer().
107  * State is returned to STATE_SETTING_UP afterwards.
108  */
110  * Set when the codec calls get_format().
111  * State is returned to STATE_SETTING_UP afterwards.
112  */
113  STATE_SETUP_FINISHED ///< Set after the codec has called ff_thread_finish_setup().
114  } state;
115 
116  /**
117  * Array of frames passed to ff_thread_release_buffer().
118  * Frames are released after all threads referencing them are finished.
119  */
123 
124  AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
125  int requested_flags; ///< flags passed to get_buffer() for requested_frame
126 
127  const enum AVPixelFormat *available_formats; ///< Format array for get_format()
128  enum AVPixelFormat result_format; ///< get_format() result
130 
131 /**
132  * Context stored in the client AVCodecContext thread_opaque.
133  */
134 typedef struct FrameThreadContext {
135  PerThreadContext *threads; ///< The contexts for each thread.
136  PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
137 
138  pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
139 
140  int next_decoding; ///< The next context to submit a packet to.
141  int next_finished; ///< The next context to return output from.
142 
143  int delaying; /**<
144  * Set for the first N packets, where N is the number of threads.
145  * While it is set, ff_thread_en/decode_frame won't return any results.
146  */
147 
148  int die; ///< Set when threads should exit.
150 
151 
152 /* H264 slice threading seems to be buggy with more than 16 threads,
153  * limit the number of threads to 16 for automatic detection */
154 #define MAX_AUTO_THREADS 16
155 
156 static void* attribute_align_arg worker(void *v)
157 {
158  AVCodecContext *avctx = v;
159  ThreadContext *c = avctx->thread_opaque;
160  unsigned last_execute = 0;
161  int our_job = c->job_count;
162  int thread_count = avctx->thread_count;
163  int self_id;
164 
166  self_id = c->current_job++;
167  for (;;){
168  while (our_job >= c->job_count) {
169  if (c->current_job == thread_count + c->job_count)
171 
172  while (last_execute == c->current_execute && !c->done)
174  last_execute = c->current_execute;
175  our_job = self_id;
176 
177  if (c->done) {
179  return NULL;
180  }
181  }
183 
184  c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
185  c->func2(avctx, c->args, our_job, self_id);
186 
188  our_job = c->current_job++;
189  }
190 }
191 
193 {
194  while (c->current_job != thread_count + c->job_count)
197 }
198 
199 static void thread_free(AVCodecContext *avctx)
200 {
201  ThreadContext *c = avctx->thread_opaque;
202  int i;
203 
205  c->done = 1;
208 
209  for (i=0; i<avctx->thread_count; i++)
210  pthread_join(c->workers[i], NULL);
211 
215  av_free(c->workers);
216  av_freep(&avctx->thread_opaque);
217 }
218 
219 static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
220 {
221  ThreadContext *c= avctx->thread_opaque;
222  int dummy_ret;
223 
224  if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
225  return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
226 
227  if (job_count <= 0)
228  return 0;
229 
231 
232  c->current_job = avctx->thread_count;
233  c->job_count = job_count;
234  c->job_size = job_size;
235  c->args = arg;
236  c->func = func;
237  if (ret) {
238  c->rets = ret;
239  c->rets_count = job_count;
240  } else {
241  c->rets = &dummy_ret;
242  c->rets_count = 1;
243  }
244  c->current_execute++;
246 
248 
249  return 0;
250 }
251 
252 static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
253 {
254  ThreadContext *c= avctx->thread_opaque;
255  c->func2 = func2;
256  return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
257 }
258 
260 {
261  int i;
262  ThreadContext *c;
263  int thread_count = avctx->thread_count;
264 
265  if (!thread_count) {
266  int nb_cpus = av_cpu_count();
267  if (avctx->height)
268  nb_cpus = FFMIN(nb_cpus, (avctx->height+15)/16);
269  // use number of cores + 1 as thread count if there is more than one
270  if (nb_cpus > 1)
271  thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
272  else
273  thread_count = avctx->thread_count = 1;
274  }
275 
276  if (thread_count <= 1) {
277  avctx->active_thread_type = 0;
278  return 0;
279  }
280 
281  c = av_mallocz(sizeof(ThreadContext));
282  if (!c)
283  return -1;
284 
285  c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
286  if (!c->workers) {
287  av_free(c);
288  return -1;
289  }
290 
291  avctx->thread_opaque = c;
292  c->current_job = 0;
293  c->job_count = 0;
294  c->job_size = 0;
295  c->done = 0;
297  pthread_cond_init(&c->last_job_cond, NULL);
300  for (i=0; i<thread_count; i++) {
301  if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
302  avctx->thread_count = i;
304  ff_thread_free(avctx);
305  return -1;
306  }
307  }
308 
309  avcodec_thread_park_workers(c, thread_count);
310 
313  return 0;
314 }
315 
316 #define THREAD_SAFE_CALLBACKS(avctx) \
317 ((avctx)->thread_safe_callbacks || (!(avctx)->get_buffer && (avctx)->get_buffer2 == avcodec_default_get_buffer2))
318 
319 /**
320  * Codec worker thread.
321  *
322  * Automatically calls ff_thread_finish_setup() if the codec does
323  * not provide an update_thread_context method, or if the codec returns
324  * before calling it.
325  */
327 {
328  PerThreadContext *p = arg;
329  FrameThreadContext *fctx = p->parent;
330  AVCodecContext *avctx = p->avctx;
331  const AVCodec *codec = avctx->codec;
332 
334  while (1) {
335  while (p->state == STATE_INPUT_READY && !fctx->die)
337 
338  if (fctx->die) break;
339 
340  if (!codec->update_thread_context && THREAD_SAFE_CALLBACKS(avctx))
341  ff_thread_finish_setup(avctx);
342 
343  av_frame_unref(p->frame);
344  p->got_frame = 0;
345  p->result = codec->decode(avctx, p->frame, &p->got_frame, &p->avpkt);
346 
347  if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
348 
350 #if 0 //BUFREF-FIXME
351  for (i = 0; i < MAX_BUFFERS; i++)
352  if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != AV_CODEC_ID_H264)) {
353  p->progress[i][0] = INT_MAX;
354  p->progress[i][1] = INT_MAX;
355  }
356 #endif
357  p->state = STATE_INPUT_READY;
358 
362  }
364 
365  return NULL;
366 }
367 
368 /**
369  * Update the next thread's AVCodecContext with values from the reference thread's context.
370  *
371  * @param dst The destination context.
372  * @param src The source context.
373  * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
374  */
376 {
377  int err = 0;
378 
379  if (dst != src) {
380  dst->time_base = src->time_base;
381  dst->width = src->width;
382  dst->height = src->height;
383  dst->pix_fmt = src->pix_fmt;
384 
385  dst->coded_width = src->coded_width;
386  dst->coded_height = src->coded_height;
387 
388  dst->has_b_frames = src->has_b_frames;
389  dst->idct_algo = src->idct_algo;
390 
394 
395  dst->profile = src->profile;
396  dst->level = src->level;
397 
399  dst->ticks_per_frame = src->ticks_per_frame;
400  dst->color_primaries = src->color_primaries;
401 
402  dst->color_trc = src->color_trc;
403  dst->colorspace = src->colorspace;
404  dst->color_range = src->color_range;
406 
407  dst->hwaccel = src->hwaccel;
408  dst->hwaccel_context = src->hwaccel_context;
409 
410  dst->channels = src->channels;
411  dst->sample_rate = src->sample_rate;
412  dst->sample_fmt = src->sample_fmt;
413  dst->channel_layout = src->channel_layout;
414  }
415 
416  if (for_user) {
417  dst->delay = src->thread_count - 1;
418  dst->coded_frame = src->coded_frame;
419  } else {
420  if (dst->codec->update_thread_context)
421  err = dst->codec->update_thread_context(dst, src);
422  }
423 
424  return err;
425 }
426 
427 /**
428  * Update the next thread's AVCodecContext with values set by the user.
429  *
430  * @param dst The destination context.
431  * @param src The source context.
432  * @return 0 on success, negative error code on failure
433  */
435 {
436 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
437  dst->flags = src->flags;
438 
439  dst->draw_horiz_band= src->draw_horiz_band;
440  dst->get_buffer2 = src->get_buffer2;
441 #if FF_API_GET_BUFFER
443  dst->get_buffer = src->get_buffer;
444  dst->release_buffer = src->release_buffer;
446 #endif
447 
448  dst->opaque = src->opaque;
449  dst->debug = src->debug;
450  dst->debug_mv = src->debug_mv;
451 
452  dst->slice_flags = src->slice_flags;
453  dst->flags2 = src->flags2;
454 
455  copy_fields(skip_loop_filter, subtitle_header);
456 
457  dst->frame_number = src->frame_number;
460 
461  if (src->slice_count && src->slice_offset) {
462  if (dst->slice_count < src->slice_count) {
463  int *tmp = av_realloc(dst->slice_offset, src->slice_count *
464  sizeof(*dst->slice_offset));
465  if (!tmp) {
466  av_free(dst->slice_offset);
467  return AVERROR(ENOMEM);
468  }
469  dst->slice_offset = tmp;
470  }
471  memcpy(dst->slice_offset, src->slice_offset,
472  src->slice_count * sizeof(*dst->slice_offset));
473  }
474  dst->slice_count = src->slice_count;
475  return 0;
476 #undef copy_fields
477 }
478 
479 /// Releases the buffers that this decoding thread was the last user of.
481 {
482  FrameThreadContext *fctx = p->parent;
483 
484  while (p->num_released_buffers > 0) {
485  AVFrame *f;
486 
488 
489  // fix extended data in case the caller screwed it up
493  f->extended_data = f->data;
494  av_frame_unref(f);
495 
497  }
498 }
499 
501 {
502  FrameThreadContext *fctx = p->parent;
503  PerThreadContext *prev_thread = fctx->prev_thread;
504  const AVCodec *codec = p->avctx->codec;
505 
506  if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
507 
509 
511 
512  if (prev_thread) {
513  int err;
514  if (prev_thread->state == STATE_SETTING_UP) {
515  pthread_mutex_lock(&prev_thread->progress_mutex);
516  while (prev_thread->state == STATE_SETTING_UP)
517  pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
518  pthread_mutex_unlock(&prev_thread->progress_mutex);
519  }
520 
521  err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
522  if (err) {
524  return err;
525  }
526  }
527 
529  p->avpkt = *avpkt;
530  if (avpkt->buf)
531  p->avpkt.buf = av_buffer_ref(avpkt->buf);
532  else {
534  p->avpkt.data = p->buf;
535  memcpy(p->buf, avpkt->data, avpkt->size);
536  memset(p->buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
537  }
538 
539  p->state = STATE_SETTING_UP;
542 
543  /*
544  * If the client doesn't have a thread-safe get_buffer(),
545  * then decoding threads call back to the main thread,
546  * and it calls back to the client here.
547  */
548 
550  if (!p->avctx->thread_safe_callbacks && (
553  p->avctx->get_buffer ||
554 #endif
557  while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
558  int call_done = 1;
560  while (p->state == STATE_SETTING_UP)
562 
563  switch (p->state) {
564  case STATE_GET_BUFFER:
566  break;
567  case STATE_GET_FORMAT:
569  break;
570  default:
571  call_done = 0;
572  break;
573  }
574  if (call_done) {
575  p->state = STATE_SETTING_UP;
577  }
579  }
580  }
581 
582  fctx->prev_thread = p;
583  fctx->next_decoding++;
584 
585  return 0;
586 }
587 
589  AVFrame *picture, int *got_picture_ptr,
590  AVPacket *avpkt)
591 {
592  FrameThreadContext *fctx = avctx->thread_opaque;
593  int finished = fctx->next_finished;
594  PerThreadContext *p;
595  int err;
596 
597  /*
598  * Submit a packet to the next decoding thread.
599  */
600 
601  p = &fctx->threads[fctx->next_decoding];
602  err = update_context_from_user(p->avctx, avctx);
603  if (err) return err;
604  err = submit_packet(p, avpkt);
605  if (err) return err;
606 
607  /*
608  * If we're still receiving the initial packets, don't return a frame.
609  */
610 
611  if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
612  fctx->delaying = 0;
613 
614  if (fctx->delaying) {
615  *got_picture_ptr=0;
616  if (avpkt->size)
617  return avpkt->size;
618  }
619 
620  /*
621  * Return the next available frame from the oldest thread.
622  * If we're at the end of the stream, then we have to skip threads that
623  * didn't output a frame, because we don't want to accidentally signal
624  * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
625  */
626 
627  do {
628  p = &fctx->threads[finished++];
629 
630  if (p->state != STATE_INPUT_READY) {
632  while (p->state != STATE_INPUT_READY)
635  }
636 
637  av_frame_move_ref(picture, p->frame);
638  *got_picture_ptr = p->got_frame;
639  picture->pkt_dts = p->avpkt.dts;
640 
641  /*
642  * A later call with avkpt->size == 0 may loop over all threads,
643  * including this one, searching for a frame to return before being
644  * stopped by the "finished != fctx->next_finished" condition.
645  * Make sure we don't mistakenly return the same frame again.
646  */
647  p->got_frame = 0;
648 
649  if (finished >= avctx->thread_count) finished = 0;
650  } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
651 
652  update_context_from_thread(avctx, p->avctx, 1);
653 
654  if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
655 
656  fctx->next_finished = finished;
657 
658  /* return the size of the consumed packet if no error occurred */
659  return (p->result >= 0) ? avpkt->size : p->result;
660 }
661 
662 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
663 {
664  PerThreadContext *p;
665  volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
666 
667  if (!progress || progress[field] >= n) return;
668 
669  p = f->owner->thread_opaque;
670 
671  if (f->owner->debug&FF_DEBUG_THREADS)
672  av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
673 
675  progress[field] = n;
678 }
679 
680 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
681 {
682  PerThreadContext *p;
683  volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
684 
685  if (!progress || progress[field] >= n) return;
686 
687  p = f->owner->thread_opaque;
688 
689  if (f->owner->debug&FF_DEBUG_THREADS)
690  av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
691 
693  while (progress[field] < n)
696 }
697 
699  PerThreadContext *p = avctx->thread_opaque;
700 
701  if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
702 
703  if(p->state == STATE_SETUP_FINISHED){
704  av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
705  }
706 
708  p->state = STATE_SETUP_FINISHED;
711 }
712 
713 /// Waits for all threads to finish.
714 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
715 {
716  int i;
717 
718  for (i = 0; i < thread_count; i++) {
719  PerThreadContext *p = &fctx->threads[i];
720 
721  if (p->state != STATE_INPUT_READY) {
723  while (p->state != STATE_INPUT_READY)
726  }
727  p->got_frame = 0;
728  }
729 }
730 
731 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
732 {
733  FrameThreadContext *fctx = avctx->thread_opaque;
734  const AVCodec *codec = avctx->codec;
735  int i;
736 
737  park_frame_worker_threads(fctx, thread_count);
738 
739  if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
740  if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
741  av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
743  fctx->threads->avctx->internal->is_copy = 1;
744  }
745 
746  fctx->die = 1;
747 
748  for (i = 0; i < thread_count; i++) {
749  PerThreadContext *p = &fctx->threads[i];
750 
754 
755  if (p->thread_init)
756  pthread_join(p->thread, NULL);
757  p->thread_init=0;
758 
759  if (codec->close)
760  codec->close(p->avctx);
761 
762  avctx->codec = NULL;
763 
765  av_frame_free(&p->frame);
766  }
767 
768  for (i = 0; i < thread_count; i++) {
769  PerThreadContext *p = &fctx->threads[i];
770 
777  av_freep(&p->buf);
779 
780  if (i) {
781  av_freep(&p->avctx->priv_data);
782  av_freep(&p->avctx->internal);
784  }
785 
786  av_freep(&p->avctx);
787  }
788 
789  av_freep(&fctx->threads);
791  av_freep(&avctx->thread_opaque);
792 }
793 
795 {
796  int thread_count = avctx->thread_count;
797  const AVCodec *codec = avctx->codec;
798  AVCodecContext *src = avctx;
799  FrameThreadContext *fctx;
800  int i, err = 0;
801 
802  if (!thread_count) {
803  int nb_cpus = av_cpu_count();
804  if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
805  nb_cpus = 1;
806  // use number of cores + 1 as thread count if there is more than one
807  if (nb_cpus > 1)
808  thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
809  else
810  thread_count = avctx->thread_count = 1;
811  }
812 
813  if (thread_count <= 1) {
814  avctx->active_thread_type = 0;
815  return 0;
816  }
817 
818  avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
819 
820  fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
821  pthread_mutex_init(&fctx->buffer_mutex, NULL);
822  fctx->delaying = 1;
823 
824  for (i = 0; i < thread_count; i++) {
826  PerThreadContext *p = &fctx->threads[i];
827 
828  pthread_mutex_init(&p->mutex, NULL);
830  pthread_cond_init(&p->input_cond, NULL);
831  pthread_cond_init(&p->progress_cond, NULL);
832  pthread_cond_init(&p->output_cond, NULL);
833 
834  p->frame = av_frame_alloc();
835  if (!p->frame) {
836  err = AVERROR(ENOMEM);
837  goto error;
838  }
839 
840  p->parent = fctx;
841  p->avctx = copy;
842 
843  if (!copy) {
844  err = AVERROR(ENOMEM);
845  goto error;
846  }
847 
848  *copy = *src;
849  copy->thread_opaque = p;
850  copy->pkt = &p->avpkt;
851 
852  if (!i) {
853  src = copy;
854 
855  if (codec->init)
856  err = codec->init(copy);
857 
858  update_context_from_thread(avctx, copy, 1);
859  } else {
860  copy->priv_data = av_malloc(codec->priv_data_size);
861  if (!copy->priv_data) {
862  err = AVERROR(ENOMEM);
863  goto error;
864  }
865  memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
866  copy->internal = av_malloc(sizeof(AVCodecInternal));
867  if (!copy->internal) {
868  err = AVERROR(ENOMEM);
869  goto error;
870  }
871  *copy->internal = *src->internal;
872  copy->internal->is_copy = 1;
873 
874  if (codec->init_thread_copy)
875  err = codec->init_thread_copy(copy);
876  }
877 
878  if (err) goto error;
879 
880  err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
881  p->thread_init= !err;
882  if(!p->thread_init)
883  goto error;
884  }
885 
886  return 0;
887 
888 error:
889  frame_thread_free(avctx, i+1);
890 
891  return err;
892 }
893 
895 {
896  int i;
897  FrameThreadContext *fctx = avctx->thread_opaque;
898 
899  if (!avctx->thread_opaque) return;
900 
902  if (fctx->prev_thread) {
903  if (fctx->prev_thread != &fctx->threads[0])
905  if (avctx->codec->flush)
906  avctx->codec->flush(fctx->threads[0].avctx);
907  }
908 
909  fctx->next_decoding = fctx->next_finished = 0;
910  fctx->delaying = 1;
911  fctx->prev_thread = NULL;
912  for (i = 0; i < avctx->thread_count; i++) {
913  PerThreadContext *p = &fctx->threads[i];
914  // Make sure decode flush calls with size=0 won't return old frames
915  p->got_frame = 0;
916  av_frame_unref(p->frame);
917 
919  }
920 }
921 
923 {
924  PerThreadContext *p = avctx->thread_opaque;
925  if ((avctx->active_thread_type&FF_THREAD_FRAME) && p->state != STATE_SETTING_UP &&
926  (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
927  return 0;
928  }
929  return 1;
930 }
931 
933 {
934  PerThreadContext *p = avctx->thread_opaque;
935  int err;
936 
937  f->owner = avctx;
938 
939  ff_init_buffer_info(avctx, f->f);
940 
941  if (!(avctx->active_thread_type & FF_THREAD_FRAME))
942  return ff_get_buffer(avctx, f->f, flags);
943 
944  if (p->state != STATE_SETTING_UP &&
945  (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
946  av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
947  return -1;
948  }
949 
950  if (avctx->internal->allocate_progress) {
951  int *progress;
952  f->progress = av_buffer_alloc(2 * sizeof(int));
953  if (!f->progress) {
954  return AVERROR(ENOMEM);
955  }
956  progress = (int*)f->progress->data;
957 
958  progress[0] = progress[1] = -1;
959  }
960 
962 
964  if (avctx->thread_safe_callbacks || (
966  !avctx->get_buffer &&
967 #endif
970  err = ff_get_buffer(avctx, f->f, flags);
971  } else {
973  p->requested_frame = f->f;
974  p->requested_flags = flags;
975  p->state = STATE_GET_BUFFER;
977 
978  while (p->state != STATE_SETTING_UP)
980 
981  err = p->result;
982 
984 
985  }
986  if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
987  ff_thread_finish_setup(avctx);
988 
989  if (err)
991 
993 
994  return err;
995 }
996 
998 {
999  enum AVPixelFormat res;
1000  PerThreadContext *p = avctx->thread_opaque;
1001  if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
1003  return avctx->get_format(avctx, fmt);
1004  if (p->state != STATE_SETTING_UP) {
1005  av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
1006  return -1;
1007  }
1009  p->available_formats = fmt;
1010  p->state = STATE_GET_FORMAT;
1012 
1013  while (p->state != STATE_SETTING_UP)
1015 
1016  res = p->result_format;
1017 
1019 
1020  return res;
1021 }
1022 
1024 {
1025  int ret = thread_get_buffer_internal(avctx, f, flags);
1026  if (ret < 0)
1027  av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
1028  return ret;
1029 }
1030 
1032 {
1033  PerThreadContext *p = avctx->thread_opaque;
1034  FrameThreadContext *fctx;
1035  AVFrame *dst, *tmp;
1037  int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
1038  avctx->thread_safe_callbacks ||
1039  (
1041  !avctx->get_buffer &&
1042 #endif
1045 
1046  if (!f->f->data[0])
1047  return;
1048 
1049  if (avctx->debug & FF_DEBUG_BUFFERS)
1050  av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
1051 
1053  f->owner = NULL;
1054 
1055  if (can_direct_free) {
1056  av_frame_unref(f->f);
1057  return;
1058  }
1059 
1060  fctx = p->parent;
1062 
1063  if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
1064  goto fail;
1066  (p->num_released_buffers + 1) *
1067  sizeof(*p->released_buffers));
1068  if (!tmp)
1069  goto fail;
1070  p->released_buffers = tmp;
1071 
1072  dst = &p->released_buffers[p->num_released_buffers];
1073  av_frame_move_ref(dst, f->f);
1074 
1075  p->num_released_buffers++;
1076 
1077 fail:
1079 }
1080 
1081 /**
1082  * Set the threading algorithms used.
1083  *
1084  * Threading requires more than one thread.
1085  * Frame threading requires entire frames to be passed to the codec,
1086  * and introduces extra decoding delay, so is incompatible with low_delay.
1087  *
1088  * @param avctx The context.
1089  */
1091 {
1092  int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
1093  && !(avctx->flags & CODEC_FLAG_TRUNCATED)
1094  && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
1095  && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
1096  if (avctx->thread_count == 1) {
1097  avctx->active_thread_type = 0;
1098  } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
1100  } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
1101  avctx->thread_type & FF_THREAD_SLICE) {
1103  } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
1104  avctx->thread_count = 1;
1105  avctx->active_thread_type = 0;
1106  }
1107 
1108  if (avctx->thread_count > MAX_AUTO_THREADS)
1109  av_log(avctx, AV_LOG_WARNING,
1110  "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
1111  avctx->thread_count, MAX_AUTO_THREADS);
1112 }
1113 
1115 {
1116 #if HAVE_W32THREADS
1117  w32thread_init();
1118 #endif
1119 
1121 
1123  return thread_init_internal(avctx);
1124  else if (avctx->active_thread_type&FF_THREAD_FRAME)
1125  return frame_thread_init(avctx);
1126 
1127  return 0;
1128 }
1129 
1131 {
1133  frame_thread_free(avctx, avctx->thread_count);
1134  else
1135  thread_free(avctx);
1136 }
1137 
1138 void ff_thread_report_progress2(AVCodecContext *avctx, int field, int thread, int n)
1139 {
1140  ThreadContext *p = avctx->thread_opaque;
1141  int *entries = p->entries;
1142 
1143  pthread_mutex_lock(&p->progress_mutex[thread]);
1144  entries[field] +=n;
1145  pthread_cond_signal(&p->progress_cond[thread]);
1146  pthread_mutex_unlock(&p->progress_mutex[thread]);
1147 }
1148 
1149 void ff_thread_await_progress2(AVCodecContext *avctx, int field, int thread, int shift)
1150 {
1151  ThreadContext *p = avctx->thread_opaque;
1152  int *entries = p->entries;
1153 
1154  if (!entries || !field) return;
1155 
1156  thread = thread ? thread - 1 : p->thread_count - 1;
1157 
1158  pthread_mutex_lock(&p->progress_mutex[thread]);
1159  while ((entries[field - 1] - entries[field]) < shift){
1160  pthread_cond_wait(&p->progress_cond[thread], &p->progress_mutex[thread]);
1161  }
1162  pthread_mutex_unlock(&p->progress_mutex[thread]);
1163 }
1164 
1166 {
1167  int i;
1168 
1169  if (avctx->active_thread_type & FF_THREAD_SLICE) {
1170  ThreadContext *p = avctx->thread_opaque;
1171  p->thread_count = avctx->thread_count;
1172  p->entries = av_mallocz(count * sizeof(int));
1173 
1174  if (!p->entries) {
1175  return AVERROR(ENOMEM);
1176  }
1177 
1178  p->entries_count = count;
1181 
1182  for (i = 0; i < p->thread_count; i++) {
1183  pthread_mutex_init(&p->progress_mutex[i], NULL);
1184  pthread_cond_init(&p->progress_cond[i], NULL);
1185  }
1186  }
1187 
1188  return 0;
1189 }
1190 
1192 {
1193  ThreadContext *p = avctx->thread_opaque;
1194  memset(p->entries, 0, p->entries_count * sizeof(int));
1195 }