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 
41 #if HAVE_PTHREADS
42 #include <pthread.h>
43 #elif HAVE_W32THREADS
44 #include "compat/w32pthreads.h"
45 #elif HAVE_OS2THREADS
46 #include "compat/os2threads.h"
47 #endif
48 
49 typedef int (action_func)(AVCodecContext *c, void *arg);
50 typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
51 
52 typedef struct ThreadContext {
56  void *args;
57  int *rets;
59  int job_count;
60  int job_size;
61 
66  unsigned int current_execute;
67  int done;
69 
70 /**
71  * Context used by codec threads and stored in their AVCodecContext thread_opaque.
72  */
73 typedef struct PerThreadContext {
75 
78  pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
79  pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
80  pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
81 
82  pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
83  pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
84 
85  AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
86 
87  AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
88  uint8_t *buf; ///< backup storage for packet data when the input packet is not refcounted
89  int allocated_buf_size; ///< Size allocated for buf
90 
91  AVFrame frame; ///< Output frame (for decoding) or input (for encoding).
92  int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
93  int result; ///< The result of the last codec decode/encode() call.
94 
95  enum {
96  STATE_INPUT_READY, ///< Set when the thread is awaiting a packet.
97  STATE_SETTING_UP, ///< Set before the codec has called ff_thread_finish_setup().
99  * Set when the codec calls get_buffer().
100  * State is returned to STATE_SETTING_UP afterwards.
101  */
103  * Set when the codec calls get_format().
104  * State is returned to STATE_SETTING_UP afterwards.
105  */
106  STATE_SETUP_FINISHED ///< Set after the codec has called ff_thread_finish_setup().
107  } state;
108 
109  /**
110  * Array of frames passed to ff_thread_release_buffer().
111  * Frames are released after all threads referencing them are finished.
112  */
116 
117  AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
118  int requested_flags; ///< flags passed to get_buffer() for requested_frame
119 
120  const enum AVPixelFormat *available_formats; ///< Format array for get_format()
121  enum AVPixelFormat result_format; ///< get_format() result
123 
124 /**
125  * Context stored in the client AVCodecContext thread_opaque.
126  */
127 typedef struct FrameThreadContext {
128  PerThreadContext *threads; ///< The contexts for each thread.
129  PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
130 
131  pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
132 
133  int next_decoding; ///< The next context to submit a packet to.
134  int next_finished; ///< The next context to return output from.
135 
136  int delaying; /**<
137  * Set for the first N packets, where N is the number of threads.
138  * While it is set, ff_thread_en/decode_frame won't return any results.
139  */
140 
141  int die; ///< Set when threads should exit.
143 
144 
145 /* H264 slice threading seems to be buggy with more than 16 threads,
146  * limit the number of threads to 16 for automatic detection */
147 #define MAX_AUTO_THREADS 16
148 
149 static void* attribute_align_arg worker(void *v)
150 {
151  AVCodecContext *avctx = v;
152  ThreadContext *c = avctx->thread_opaque;
153  int our_job = c->job_count;
154  int last_execute = 0;
155  int thread_count = avctx->thread_count;
156  int self_id;
157 
159  self_id = c->current_job++;
160  for (;;){
161  while (our_job >= c->job_count) {
162  if (c->current_job == thread_count + c->job_count)
164 
165  while (last_execute == c->current_execute && !c->done)
167  last_execute = c->current_execute;
168  our_job = self_id;
169 
170  if (c->done) {
172  return NULL;
173  }
174  }
176 
177  c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
178  c->func2(avctx, c->args, our_job, self_id);
179 
181  our_job = c->current_job++;
182  }
183 }
184 
186 {
187  while (c->current_job != thread_count + c->job_count)
190 }
191 
192 static void thread_free(AVCodecContext *avctx)
193 {
194  ThreadContext *c = avctx->thread_opaque;
195  int i;
196 
198  c->done = 1;
201 
202  for (i=0; i<avctx->thread_count; i++)
203  pthread_join(c->workers[i], NULL);
204 
208  av_free(c->workers);
209  av_freep(&avctx->thread_opaque);
210 }
211 
212 static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
213 {
214  ThreadContext *c= avctx->thread_opaque;
215  int dummy_ret;
216 
217  if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
218  return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
219 
220  if (job_count <= 0)
221  return 0;
222 
224 
225  c->current_job = avctx->thread_count;
226  c->job_count = job_count;
227  c->job_size = job_size;
228  c->args = arg;
229  c->func = func;
230  if (ret) {
231  c->rets = ret;
232  c->rets_count = job_count;
233  } else {
234  c->rets = &dummy_ret;
235  c->rets_count = 1;
236  }
237  c->current_execute++;
239 
241 
242  return 0;
243 }
244 
245 static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
246 {
247  ThreadContext *c= avctx->thread_opaque;
248  c->func2 = func2;
249  return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
250 }
251 
253 {
254  int i;
255  ThreadContext *c;
256  int thread_count = avctx->thread_count;
257 
258  if (!thread_count) {
259  int nb_cpus = av_cpu_count();
260  if (avctx->height)
261  nb_cpus = FFMIN(nb_cpus, (avctx->height+15)/16);
262  // use number of cores + 1 as thread count if there is more than one
263  if (nb_cpus > 1)
264  thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
265  else
266  thread_count = avctx->thread_count = 1;
267  }
268 
269  if (thread_count <= 1) {
270  avctx->active_thread_type = 0;
271  return 0;
272  }
273 
274  c = av_mallocz(sizeof(ThreadContext));
275  if (!c)
276  return -1;
277 
278  c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
279  if (!c->workers) {
280  av_free(c);
281  return -1;
282  }
283 
284  avctx->thread_opaque = c;
285  c->current_job = 0;
286  c->job_count = 0;
287  c->job_size = 0;
288  c->done = 0;
290  pthread_cond_init(&c->last_job_cond, NULL);
293  for (i=0; i<thread_count; i++) {
294  if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
295  avctx->thread_count = i;
297  ff_thread_free(avctx);
298  return -1;
299  }
300  }
301 
302  avcodec_thread_park_workers(c, thread_count);
303 
306  return 0;
307 }
308 
309 #define THREAD_SAFE_CALLBACKS(avctx) \
310 ((avctx)->thread_safe_callbacks || (!(avctx)->get_buffer && (avctx)->get_buffer2 == avcodec_default_get_buffer2))
311 
312 /**
313  * Codec worker thread.
314  *
315  * Automatically calls ff_thread_finish_setup() if the codec does
316  * not provide an update_thread_context method, or if the codec returns
317  * before calling it.
318  */
320 {
321  PerThreadContext *p = arg;
322  FrameThreadContext *fctx = p->parent;
323  AVCodecContext *avctx = p->avctx;
324  const AVCodec *codec = avctx->codec;
325 
327  while (1) {
328  while (p->state == STATE_INPUT_READY && !fctx->die)
330 
331  if (fctx->die) break;
332 
333  if (!codec->update_thread_context && THREAD_SAFE_CALLBACKS(avctx))
334  ff_thread_finish_setup(avctx);
335 
337  p->got_frame = 0;
338  p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
339 
340  /* many decoders assign whole AVFrames, thus overwriting extended_data;
341  * make sure it's set correctly */
342  p->frame.extended_data = p->frame.data;
343 
344  if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
345 
347 #if 0 //BUFREF-FIXME
348  for (i = 0; i < MAX_BUFFERS; i++)
349  if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != AV_CODEC_ID_H264)) {
350  p->progress[i][0] = INT_MAX;
351  p->progress[i][1] = INT_MAX;
352  }
353 #endif
354  p->state = STATE_INPUT_READY;
355 
359  }
361 
362  return NULL;
363 }
364 
365 /**
366  * Update the next thread's AVCodecContext with values from the reference thread's context.
367  *
368  * @param dst The destination context.
369  * @param src The source context.
370  * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
371  */
373 {
374  int err = 0;
375 
376  if (dst != src) {
377  dst->time_base = src->time_base;
378  dst->width = src->width;
379  dst->height = src->height;
380  dst->pix_fmt = src->pix_fmt;
381 
382  dst->coded_width = src->coded_width;
383  dst->coded_height = src->coded_height;
384 
385  dst->has_b_frames = src->has_b_frames;
386  dst->idct_algo = src->idct_algo;
387 
391 
392  dst->profile = src->profile;
393  dst->level = src->level;
394 
396  dst->ticks_per_frame = src->ticks_per_frame;
397  dst->color_primaries = src->color_primaries;
398 
399  dst->color_trc = src->color_trc;
400  dst->colorspace = src->colorspace;
401  dst->color_range = src->color_range;
403 
404  dst->hwaccel = src->hwaccel;
405  dst->hwaccel_context = src->hwaccel_context;
406 
407  dst->channels = src->channels;
408  dst->sample_rate = src->sample_rate;
409  dst->sample_fmt = src->sample_fmt;
410  dst->channel_layout = src->channel_layout;
411  }
412 
413  if (for_user) {
414  dst->delay = src->thread_count - 1;
415  dst->coded_frame = src->coded_frame;
416  } else {
417  if (dst->codec->update_thread_context)
418  err = dst->codec->update_thread_context(dst, src);
419  }
420 
421  return err;
422 }
423 
424 /**
425  * Update the next thread's AVCodecContext with values set by the user.
426  *
427  * @param dst The destination context.
428  * @param src The source context.
429  * @return 0 on success, negative error code on failure
430  */
432 {
433 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
434  dst->flags = src->flags;
435 
436  dst->draw_horiz_band= src->draw_horiz_band;
437  dst->get_buffer2 = src->get_buffer2;
438 #if FF_API_GET_BUFFER
439  dst->get_buffer = src->get_buffer;
440  dst->release_buffer = src->release_buffer;
441 #endif
442 
443  dst->opaque = src->opaque;
444  dst->debug = src->debug;
445  dst->debug_mv = src->debug_mv;
446 
447  dst->slice_flags = src->slice_flags;
448  dst->flags2 = src->flags2;
449 
450  copy_fields(skip_loop_filter, subtitle_header);
451 
452  dst->frame_number = src->frame_number;
455 
456  if (src->slice_count && src->slice_offset) {
457  if (dst->slice_count < src->slice_count) {
458  int *tmp = av_realloc(dst->slice_offset, src->slice_count *
459  sizeof(*dst->slice_offset));
460  if (!tmp) {
461  av_free(dst->slice_offset);
462  return AVERROR(ENOMEM);
463  }
464  dst->slice_offset = tmp;
465  }
466  memcpy(dst->slice_offset, src->slice_offset,
467  src->slice_count * sizeof(*dst->slice_offset));
468  }
469  dst->slice_count = src->slice_count;
470  return 0;
471 #undef copy_fields
472 }
473 
474 /// Releases the buffers that this decoding thread was the last user of.
476 {
477  FrameThreadContext *fctx = p->parent;
478 
479  while (p->num_released_buffers > 0) {
480  AVFrame *f;
481 
483 
484  // fix extended data in case the caller screwed it up
488  f->extended_data = f->data;
489  av_frame_unref(f);
490 
492  }
493 }
494 
496 {
497  FrameThreadContext *fctx = p->parent;
498  PerThreadContext *prev_thread = fctx->prev_thread;
499  const AVCodec *codec = p->avctx->codec;
500 
501  if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
502 
504 
506 
507  if (prev_thread) {
508  int err;
509  if (prev_thread->state == STATE_SETTING_UP) {
510  pthread_mutex_lock(&prev_thread->progress_mutex);
511  while (prev_thread->state == STATE_SETTING_UP)
512  pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
513  pthread_mutex_unlock(&prev_thread->progress_mutex);
514  }
515 
516  err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
517  if (err) {
519  return err;
520  }
521  }
522 
524  p->avpkt = *avpkt;
525  if (avpkt->buf)
526  p->avpkt.buf = av_buffer_ref(avpkt->buf);
527  else {
529  p->avpkt.data = p->buf;
530  memcpy(p->buf, avpkt->data, avpkt->size);
531  memset(p->buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
532  }
533 
534  p->state = STATE_SETTING_UP;
537 
538  /*
539  * If the client doesn't have a thread-safe get_buffer(),
540  * then decoding threads call back to the main thread,
541  * and it calls back to the client here.
542  */
543 
544  if (!p->avctx->thread_safe_callbacks && (
547  p->avctx->get_buffer ||
548 #endif
550  while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
551  int call_done = 1;
553  while (p->state == STATE_SETTING_UP)
555 
556  switch (p->state) {
557  case STATE_GET_BUFFER:
559  break;
560  case STATE_GET_FORMAT:
562  break;
563  default:
564  call_done = 0;
565  break;
566  }
567  if (call_done) {
568  p->state = STATE_SETTING_UP;
570  }
572  }
573  }
574 
575  fctx->prev_thread = p;
576  fctx->next_decoding++;
577 
578  return 0;
579 }
580 
582  AVFrame *picture, int *got_picture_ptr,
583  AVPacket *avpkt)
584 {
585  FrameThreadContext *fctx = avctx->thread_opaque;
586  int finished = fctx->next_finished;
587  PerThreadContext *p;
588  int err;
589 
590  /*
591  * Submit a packet to the next decoding thread.
592  */
593 
594  p = &fctx->threads[fctx->next_decoding];
595  err = update_context_from_user(p->avctx, avctx);
596  if (err) return err;
597  err = submit_packet(p, avpkt);
598  if (err) return err;
599 
600  /*
601  * If we're still receiving the initial packets, don't return a frame.
602  */
603 
604  if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
605  fctx->delaying = 0;
606 
607  if (fctx->delaying) {
608  *got_picture_ptr=0;
609  if (avpkt->size)
610  return avpkt->size;
611  }
612 
613  /*
614  * Return the next available frame from the oldest thread.
615  * If we're at the end of the stream, then we have to skip threads that
616  * didn't output a frame, because we don't want to accidentally signal
617  * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
618  */
619 
620  do {
621  p = &fctx->threads[finished++];
622 
623  if (p->state != STATE_INPUT_READY) {
625  while (p->state != STATE_INPUT_READY)
628  }
629 
630  av_frame_move_ref(picture, &p->frame);
631  *got_picture_ptr = p->got_frame;
632  picture->pkt_dts = p->avpkt.dts;
633 
634  /*
635  * A later call with avkpt->size == 0 may loop over all threads,
636  * including this one, searching for a frame to return before being
637  * stopped by the "finished != fctx->next_finished" condition.
638  * Make sure we don't mistakenly return the same frame again.
639  */
640  p->got_frame = 0;
641 
642  if (finished >= avctx->thread_count) finished = 0;
643  } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
644 
645  update_context_from_thread(avctx, p->avctx, 1);
646 
647  if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
648 
649  fctx->next_finished = finished;
650 
651  /* return the size of the consumed packet if no error occurred */
652  return (p->result >= 0) ? avpkt->size : p->result;
653 }
654 
655 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
656 {
657  PerThreadContext *p;
658  volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
659 
660  if (!progress || progress[field] >= n) return;
661 
662  p = f->owner->thread_opaque;
663 
664  if (f->owner->debug&FF_DEBUG_THREADS)
665  av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
666 
668  progress[field] = n;
671 }
672 
673 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
674 {
675  PerThreadContext *p;
676  volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
677 
678  if (!progress || progress[field] >= n) return;
679 
680  p = f->owner->thread_opaque;
681 
682  if (f->owner->debug&FF_DEBUG_THREADS)
683  av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
684 
686  while (progress[field] < n)
689 }
690 
692  PerThreadContext *p = avctx->thread_opaque;
693 
694  if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
695 
696  if(p->state == STATE_SETUP_FINISHED){
697  av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
698  }
699 
701  p->state = STATE_SETUP_FINISHED;
704 }
705 
706 /// Waits for all threads to finish.
707 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
708 {
709  int i;
710 
711  for (i = 0; i < thread_count; i++) {
712  PerThreadContext *p = &fctx->threads[i];
713 
714  if (p->state != STATE_INPUT_READY) {
716  while (p->state != STATE_INPUT_READY)
719  }
720  p->got_frame = 0;
721  }
722 }
723 
724 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
725 {
726  FrameThreadContext *fctx = avctx->thread_opaque;
727  const AVCodec *codec = avctx->codec;
728  int i;
729 
730  park_frame_worker_threads(fctx, thread_count);
731 
732  if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
733  if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
734  av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
736  fctx->threads->avctx->internal->is_copy = 1;
737  }
738 
739  fctx->die = 1;
740 
741  for (i = 0; i < thread_count; i++) {
742  PerThreadContext *p = &fctx->threads[i];
743 
747 
748  if (p->thread_init)
749  pthread_join(p->thread, NULL);
750  p->thread_init=0;
751 
752  if (codec->close)
753  codec->close(p->avctx);
754 
755  avctx->codec = NULL;
756 
758  av_frame_unref(&p->frame);
759  }
760 
761  for (i = 0; i < thread_count; i++) {
762  PerThreadContext *p = &fctx->threads[i];
763 
770  av_freep(&p->buf);
772 
773  if (i) {
774  av_freep(&p->avctx->priv_data);
775  av_freep(&p->avctx->internal);
777  }
778 
779  av_freep(&p->avctx);
780  }
781 
782  av_freep(&fctx->threads);
784  av_freep(&avctx->thread_opaque);
785 }
786 
788 {
789  int thread_count = avctx->thread_count;
790  const AVCodec *codec = avctx->codec;
791  AVCodecContext *src = avctx;
792  FrameThreadContext *fctx;
793  int i, err = 0;
794 
795  if (!thread_count) {
796  int nb_cpus = av_cpu_count();
797  if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
798  nb_cpus = 1;
799  // use number of cores + 1 as thread count if there is more than one
800  if (nb_cpus > 1)
801  thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
802  else
803  thread_count = avctx->thread_count = 1;
804  }
805 
806  if (thread_count <= 1) {
807  avctx->active_thread_type = 0;
808  return 0;
809  }
810 
811  avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
812 
813  fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
814  pthread_mutex_init(&fctx->buffer_mutex, NULL);
815  fctx->delaying = 1;
816 
817  for (i = 0; i < thread_count; i++) {
819  PerThreadContext *p = &fctx->threads[i];
820 
821  pthread_mutex_init(&p->mutex, NULL);
823  pthread_cond_init(&p->input_cond, NULL);
824  pthread_cond_init(&p->progress_cond, NULL);
825  pthread_cond_init(&p->output_cond, NULL);
826 
827  p->parent = fctx;
828  p->avctx = copy;
829 
830  if (!copy) {
831  err = AVERROR(ENOMEM);
832  goto error;
833  }
834 
835  *copy = *src;
836  copy->thread_opaque = p;
837  copy->pkt = &p->avpkt;
838 
839  if (!i) {
840  src = copy;
841 
842  if (codec->init)
843  err = codec->init(copy);
844 
845  update_context_from_thread(avctx, copy, 1);
846  } else {
847  copy->priv_data = av_malloc(codec->priv_data_size);
848  if (!copy->priv_data) {
849  err = AVERROR(ENOMEM);
850  goto error;
851  }
852  memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
853  copy->internal = av_malloc(sizeof(AVCodecInternal));
854  if (!copy->internal) {
855  err = AVERROR(ENOMEM);
856  goto error;
857  }
858  *copy->internal = *src->internal;
859  copy->internal->is_copy = 1;
860 
861  if (codec->init_thread_copy)
862  err = codec->init_thread_copy(copy);
863  }
864 
865  if (err) goto error;
866 
867  err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
868  p->thread_init= !err;
869  if(!p->thread_init)
870  goto error;
871  }
872 
873  return 0;
874 
875 error:
876  frame_thread_free(avctx, i+1);
877 
878  return err;
879 }
880 
882 {
883  int i;
884  FrameThreadContext *fctx = avctx->thread_opaque;
885 
886  if (!avctx->thread_opaque) return;
887 
889  if (fctx->prev_thread) {
890  if (fctx->prev_thread != &fctx->threads[0])
892  if (avctx->codec->flush)
893  avctx->codec->flush(fctx->threads[0].avctx);
894  }
895 
896  fctx->next_decoding = fctx->next_finished = 0;
897  fctx->delaying = 1;
898  fctx->prev_thread = NULL;
899  for (i = 0; i < avctx->thread_count; i++) {
900  PerThreadContext *p = &fctx->threads[i];
901  // Make sure decode flush calls with size=0 won't return old frames
902  p->got_frame = 0;
903  av_frame_unref(&p->frame);
904 
906  }
907 }
908 
910 {
911  PerThreadContext *p = avctx->thread_opaque;
912  if ((avctx->active_thread_type&FF_THREAD_FRAME) && p->state != STATE_SETTING_UP &&
913  (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
914  return 0;
915  }
916  return 1;
917 }
918 
920 {
921  PerThreadContext *p = avctx->thread_opaque;
922  int err;
923 
924  f->owner = avctx;
925 
926  ff_init_buffer_info(avctx, f->f);
927 
928  if (!(avctx->active_thread_type & FF_THREAD_FRAME))
929  return ff_get_buffer(avctx, f->f, flags);
930 
931  if (p->state != STATE_SETTING_UP &&
932  (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
933  av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
934  return -1;
935  }
936 
937  if (avctx->internal->allocate_progress) {
938  int *progress;
939  f->progress = av_buffer_alloc(2 * sizeof(int));
940  if (!f->progress) {
941  return AVERROR(ENOMEM);
942  }
943  progress = (int*)f->progress->data;
944 
945  progress[0] = progress[1] = -1;
946  }
947 
949 
950  if (avctx->thread_safe_callbacks || (
952  !avctx->get_buffer &&
953 #endif
955  err = ff_get_buffer(avctx, f->f, flags);
956  } else {
958  p->requested_frame = f->f;
959  p->requested_flags = flags;
960  p->state = STATE_GET_BUFFER;
962 
963  while (p->state != STATE_SETTING_UP)
965 
966  err = p->result;
967 
969 
970  }
971  if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
972  ff_thread_finish_setup(avctx);
973 
974  if (err)
976 
978 
979  return err;
980 }
981 
983 {
984  enum AVPixelFormat res;
985  PerThreadContext *p = avctx->thread_opaque;
986  if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
988  return avctx->get_format(avctx, fmt);
989  if (p->state != STATE_SETTING_UP) {
990  av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
991  return -1;
992  }
994  p->available_formats = fmt;
995  p->state = STATE_GET_FORMAT;
997 
998  while (p->state != STATE_SETTING_UP)
1000 
1001  res = p->result_format;
1002 
1004 
1005  return res;
1006 }
1007 
1009 {
1010  int ret = thread_get_buffer_internal(avctx, f, flags);
1011  if (ret < 0)
1012  av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
1013  return ret;
1014 }
1015 
1017 {
1018  PerThreadContext *p = avctx->thread_opaque;
1019  FrameThreadContext *fctx;
1020  AVFrame *dst, *tmp;
1021  int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
1022  avctx->thread_safe_callbacks ||
1023  (
1025  !avctx->get_buffer &&
1026 #endif
1028 
1029  if (!f->f->data[0])
1030  return;
1031 
1032  if (avctx->debug & FF_DEBUG_BUFFERS)
1033  av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
1034 
1036  f->owner = NULL;
1037 
1038  if (can_direct_free) {
1039  av_frame_unref(f->f);
1040  return;
1041  }
1042 
1043  fctx = p->parent;
1045 
1046  if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
1047  goto fail;
1049  (p->num_released_buffers + 1) *
1050  sizeof(*p->released_buffers));
1051  if (!tmp)
1052  goto fail;
1053  p->released_buffers = tmp;
1054 
1055  dst = &p->released_buffers[p->num_released_buffers];
1056  av_frame_move_ref(dst, f->f);
1057 
1058  p->num_released_buffers++;
1059 
1060 fail:
1062 }
1063 
1064 /**
1065  * Set the threading algorithms used.
1066  *
1067  * Threading requires more than one thread.
1068  * Frame threading requires entire frames to be passed to the codec,
1069  * and introduces extra decoding delay, so is incompatible with low_delay.
1070  *
1071  * @param avctx The context.
1072  */
1074 {
1075  int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
1076  && !(avctx->flags & CODEC_FLAG_TRUNCATED)
1077  && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
1078  && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
1079  if (avctx->thread_count == 1) {
1080  avctx->active_thread_type = 0;
1081  } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
1083  } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
1084  avctx->thread_type & FF_THREAD_SLICE) {
1086  } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
1087  avctx->thread_count = 1;
1088  avctx->active_thread_type = 0;
1089  }
1090 
1091  if (avctx->thread_count > MAX_AUTO_THREADS)
1092  av_log(avctx, AV_LOG_WARNING,
1093  "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
1094  avctx->thread_count, MAX_AUTO_THREADS);
1095 }
1096 
1098 {
1099 #if HAVE_W32THREADS
1100  w32thread_init();
1101 #endif
1102 
1104 
1106  return avcodec_thread_init(avctx);
1107  else if (avctx->active_thread_type&FF_THREAD_FRAME)
1108  return frame_thread_init(avctx);
1109 
1110  return 0;
1111 }
1112 
1114 {
1116  frame_thread_free(avctx, avctx->thread_count);
1117  else
1118  thread_free(avctx);
1119 }