FFmpeg
 All Data Structures 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 #if HAVE_SCHED_GETAFFINITY
35 #ifndef _GNU_SOURCE
36 # define _GNU_SOURCE
37 #endif
38 #include <sched.h>
39 #endif
40 #if HAVE_GETPROCESSAFFINITYMASK
41 #include <windows.h>
42 #endif
43 #if HAVE_SYSCTL
44 #if HAVE_SYS_PARAM_H
45 #include <sys/param.h>
46 #endif
47 #include <sys/types.h>
48 #include <sys/param.h>
49 #include <sys/sysctl.h>
50 #endif
51 #if HAVE_SYSCONF
52 #include <unistd.h>
53 #endif
54 
55 #include "avcodec.h"
56 #include "internal.h"
57 #include "thread.h"
58 #include "libavutil/common.h"
59 
60 #if HAVE_PTHREADS
61 #include <pthread.h>
62 #elif HAVE_W32THREADS
63 #include "w32pthreads.h"
64 #elif HAVE_OS2THREADS
65 #include "os2threads.h"
66 #endif
67 
68 typedef int (action_func)(AVCodecContext *c, void *arg);
69 typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
70 
71 typedef struct ThreadContext {
75  void *args;
76  int *rets;
78  int job_count;
79  int job_size;
80 
85  unsigned int current_execute;
86  int done;
88 
89 /// Max number of frame buffers that can be allocated when using frame threads.
90 #define MAX_BUFFERS (34+1)
91 
92 /**
93  * Context used by codec threads and stored in their AVCodecContext thread_opaque.
94  */
95 typedef struct PerThreadContext {
97 
100  pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
101  pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
102  pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
103 
104  pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
105  pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
106 
107  AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
108 
109  AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
110  int allocated_buf_size; ///< Size allocated for avpkt.data
111 
112  AVFrame frame; ///< Output frame (for decoding) or input (for encoding).
113  int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
114  int result; ///< The result of the last codec decode/encode() call.
115 
116  enum {
117  STATE_INPUT_READY, ///< Set when the thread is awaiting a packet.
118  STATE_SETTING_UP, ///< Set before the codec has called ff_thread_finish_setup().
120  * Set when the codec calls get_buffer().
121  * State is returned to STATE_SETTING_UP afterwards.
122  */
123  STATE_SETUP_FINISHED ///< Set after the codec has called ff_thread_finish_setup().
124  } state;
125 
126  /**
127  * Array of frames passed to ff_thread_release_buffer().
128  * Frames are released after all threads referencing them are finished.
129  */
132 
133  /**
134  * Array of progress values used by ff_thread_get_buffer().
135  */
136  volatile int progress[MAX_BUFFERS][2];
138 
139  AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
141 
142 /**
143  * Context stored in the client AVCodecContext thread_opaque.
144  */
145 typedef struct FrameThreadContext {
146  PerThreadContext *threads; ///< The contexts for each thread.
147  PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
148 
149  pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
150 
151  int next_decoding; ///< The next context to submit a packet to.
152  int next_finished; ///< The next context to return output from.
153 
154  int delaying; /**<
155  * Set for the first N packets, where N is the number of threads.
156  * While it is set, ff_thread_en/decode_frame won't return any results.
157  */
158 
159  int die; ///< Set when threads should exit.
161 
162 
163 /* H264 slice threading seems to be buggy with more than 16 threads,
164  * limit the number of threads to 16 for automatic detection */
165 #define MAX_AUTO_THREADS 16
166 
168 {
169  int ret, nb_cpus = 1;
170 #if HAVE_SCHED_GETAFFINITY && defined(CPU_COUNT)
171  cpu_set_t cpuset;
172 
173  CPU_ZERO(&cpuset);
174 
175  ret = sched_getaffinity(0, sizeof(cpuset), &cpuset);
176  if (!ret) {
177  nb_cpus = CPU_COUNT(&cpuset);
178  }
179 #elif HAVE_GETPROCESSAFFINITYMASK
180  DWORD_PTR proc_aff, sys_aff;
181  ret = GetProcessAffinityMask(GetCurrentProcess(), &proc_aff, &sys_aff);
182  if (ret)
183  nb_cpus = av_popcount64(proc_aff);
184 #elif HAVE_SYSCTL && defined(HW_NCPU)
185  int mib[2] = { CTL_HW, HW_NCPU };
186  size_t len = sizeof(nb_cpus);
187 
188  ret = sysctl(mib, 2, &nb_cpus, &len, NULL, 0);
189  if (ret == -1)
190  nb_cpus = 0;
191 #elif HAVE_SYSCONF && defined(_SC_NPROC_ONLN)
192  nb_cpus = sysconf(_SC_NPROC_ONLN);
193 #elif HAVE_SYSCONF && defined(_SC_NPROCESSORS_ONLN)
194  nb_cpus = sysconf(_SC_NPROCESSORS_ONLN);
195 #endif
196  av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
197 
198  if (avctx->height)
199  nb_cpus = FFMIN(nb_cpus, (avctx->height+15)/16);
200 
201  return nb_cpus;
202 }
203 
204 
205 static void* attribute_align_arg worker(void *v)
206 {
207  AVCodecContext *avctx = v;
208  ThreadContext *c = avctx->thread_opaque;
209  int our_job = c->job_count;
210  int last_execute = 0;
211  int thread_count = avctx->thread_count;
212  int self_id;
213 
215  self_id = c->current_job++;
216  for (;;){
217  while (our_job >= c->job_count) {
218  if (c->current_job == thread_count + c->job_count)
220 
221  while (last_execute == c->current_execute && !c->done)
223  last_execute = c->current_execute;
224  our_job = self_id;
225 
226  if (c->done) {
228  return NULL;
229  }
230  }
232 
233  c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
234  c->func2(avctx, c->args, our_job, self_id);
235 
237  our_job = c->current_job++;
238  }
239 }
240 
242 {
243  while (c->current_job != thread_count + c->job_count)
246 }
247 
248 static void thread_free(AVCodecContext *avctx)
249 {
250  ThreadContext *c = avctx->thread_opaque;
251  int i;
252 
254  c->done = 1;
257 
258  for (i=0; i<avctx->thread_count; i++)
259  pthread_join(c->workers[i], NULL);
260 
264  av_free(c->workers);
265  av_freep(&avctx->thread_opaque);
266 }
267 
268 static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
269 {
270  ThreadContext *c= avctx->thread_opaque;
271  int dummy_ret;
272 
273  if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
274  return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
275 
276  if (job_count <= 0)
277  return 0;
278 
280 
281  c->current_job = avctx->thread_count;
282  c->job_count = job_count;
283  c->job_size = job_size;
284  c->args = arg;
285  c->func = func;
286  if (ret) {
287  c->rets = ret;
288  c->rets_count = job_count;
289  } else {
290  c->rets = &dummy_ret;
291  c->rets_count = 1;
292  }
293  c->current_execute++;
295 
297 
298  return 0;
299 }
300 
301 static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
302 {
303  ThreadContext *c= avctx->thread_opaque;
304  c->func2 = func2;
305  return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
306 }
307 
308 static int thread_init(AVCodecContext *avctx)
309 {
310  int i;
311  ThreadContext *c;
312  int thread_count = avctx->thread_count;
313 
314  if (!thread_count) {
315  int nb_cpus = ff_get_logical_cpus(avctx);
316  // use number of cores + 1 as thread count if there is more than one
317  if (nb_cpus > 1)
318  thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
319  else
320  thread_count = avctx->thread_count = 1;
321  }
322 
323  if (thread_count <= 1) {
324  avctx->active_thread_type = 0;
325  return 0;
326  }
327 
328  c = av_mallocz(sizeof(ThreadContext));
329  if (!c)
330  return -1;
331 
332  c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
333  if (!c->workers) {
334  av_free(c);
335  return -1;
336  }
337 
338  avctx->thread_opaque = c;
339  c->current_job = 0;
340  c->job_count = 0;
341  c->job_size = 0;
342  c->done = 0;
347  for (i=0; i<thread_count; i++) {
348  if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
349  avctx->thread_count = i;
351  ff_thread_free(avctx);
352  return -1;
353  }
354  }
355 
356  avcodec_thread_park_workers(c, thread_count);
357 
360  return 0;
361 }
362 
363 /**
364  * Codec worker thread.
365  *
366  * Automatically calls ff_thread_finish_setup() if the codec does
367  * not provide an update_thread_context method, or if the codec returns
368  * before calling it.
369  */
371 {
372  PerThreadContext *p = arg;
373  FrameThreadContext *fctx = p->parent;
374  AVCodecContext *avctx = p->avctx;
375  const AVCodec *codec = avctx->codec;
376 
378  while (1) {
379  int i;
380  while (p->state == STATE_INPUT_READY && !fctx->die)
382 
383  if (fctx->die) break;
384 
386  ff_thread_finish_setup(avctx);
387 
389  p->got_frame = 0;
390  p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
391 
392  /* many decoders assign whole AVFrames, thus overwriting extended_data;
393  * make sure it's set correctly */
394  p->frame.extended_data = p->frame.data;
395 
396  if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
397 
399  for (i = 0; i < MAX_BUFFERS; i++)
400  if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != AV_CODEC_ID_H264)) {
401  p->progress[i][0] = INT_MAX;
402  p->progress[i][1] = INT_MAX;
403  }
404  p->state = STATE_INPUT_READY;
405 
409  }
411 
412  return NULL;
413 }
414 
415 /**
416  * Update the next thread's AVCodecContext with values from the reference thread's context.
417  *
418  * @param dst The destination context.
419  * @param src The source context.
420  * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
421  */
423 {
424  int err = 0;
425 
426  if (dst != src) {
427  dst->time_base = src->time_base;
428  dst->width = src->width;
429  dst->height = src->height;
430  dst->pix_fmt = src->pix_fmt;
431 
432  dst->coded_width = src->coded_width;
433  dst->coded_height = src->coded_height;
434 
435  dst->has_b_frames = src->has_b_frames;
436  dst->idct_algo = src->idct_algo;
437 
441 
442  dst->profile = src->profile;
443  dst->level = src->level;
444 
446  dst->ticks_per_frame = src->ticks_per_frame;
447  dst->color_primaries = src->color_primaries;
448 
449  dst->color_trc = src->color_trc;
450  dst->colorspace = src->colorspace;
451  dst->color_range = src->color_range;
453  }
454 
455  if (for_user) {
456  dst->delay = src->thread_count - 1;
457  dst->coded_frame = src->coded_frame;
458  } else {
459  if (dst->codec->update_thread_context)
460  err = dst->codec->update_thread_context(dst, src);
461  }
462 
463  return err;
464 }
465 
466 /**
467  * Update the next thread's AVCodecContext with values set by the user.
468  *
469  * @param dst The destination context.
470  * @param src The source context.
471  * @return 0 on success, negative error code on failure
472  */
474 {
475 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
476  dst->flags = src->flags;
477 
478  dst->draw_horiz_band= src->draw_horiz_band;
479  dst->get_buffer = src->get_buffer;
480  dst->release_buffer = src->release_buffer;
481 
482  dst->opaque = src->opaque;
483  dst->debug = src->debug;
484  dst->debug_mv = src->debug_mv;
485 
486  dst->slice_flags = src->slice_flags;
487  dst->flags2 = src->flags2;
488 
489  copy_fields(skip_loop_filter, subtitle_header);
490 
491  dst->frame_number = src->frame_number;
494 
495  if (src->slice_count && src->slice_offset) {
496  if (dst->slice_count < src->slice_count) {
497  int *tmp = av_realloc(dst->slice_offset, src->slice_count *
498  sizeof(*dst->slice_offset));
499  if (!tmp) {
500  av_free(dst->slice_offset);
501  return AVERROR(ENOMEM);
502  }
503  dst->slice_offset = tmp;
504  }
505  memcpy(dst->slice_offset, src->slice_offset,
506  src->slice_count * sizeof(*dst->slice_offset));
507  }
508  dst->slice_count = src->slice_count;
509  return 0;
510 #undef copy_fields
511 }
512 
513 static void free_progress(AVFrame *f)
514 {
516  volatile int *progress = f->thread_opaque;
517 
518  p->progress_used[(progress - p->progress[0]) / 2] = 0;
519 }
520 
521 /// Releases the buffers that this decoding thread was the last user of.
523 {
524  FrameThreadContext *fctx = p->parent;
525 
526  while (p->num_released_buffers > 0) {
527  AVFrame *f;
528 
531  free_progress(f);
532  f->thread_opaque = NULL;
533 
534  f->owner->release_buffer(f->owner, f);
536  }
537 }
538 
540 {
541  FrameThreadContext *fctx = p->parent;
542  PerThreadContext *prev_thread = fctx->prev_thread;
543  const AVCodec *codec = p->avctx->codec;
544  uint8_t *buf = p->avpkt.data;
545 
546  if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
547 
549 
551 
552  if (prev_thread) {
553  int err;
554  if (prev_thread->state == STATE_SETTING_UP) {
555  pthread_mutex_lock(&prev_thread->progress_mutex);
556  while (prev_thread->state == STATE_SETTING_UP)
557  pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
558  pthread_mutex_unlock(&prev_thread->progress_mutex);
559  }
560 
561  err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
562  if (err) {
564  return err;
565  }
566  }
567 
569  p->avpkt = *avpkt;
570  p->avpkt.data = buf;
571  memcpy(buf, avpkt->data, avpkt->size);
572  memset(buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
573 
574  p->state = STATE_SETTING_UP;
577 
578  /*
579  * If the client doesn't have a thread-safe get_buffer(),
580  * then decoding threads call back to the main thread,
581  * and it calls back to the client here.
582  */
583 
584  if (!p->avctx->thread_safe_callbacks &&
586  while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
588  while (p->state == STATE_SETTING_UP)
590 
591  if (p->state == STATE_GET_BUFFER) {
593  p->state = STATE_SETTING_UP;
595  }
597  }
598  }
599 
600  fctx->prev_thread = p;
601  fctx->next_decoding++;
602 
603  return 0;
604 }
605 
607  AVFrame *picture, int *got_picture_ptr,
608  AVPacket *avpkt)
609 {
610  FrameThreadContext *fctx = avctx->thread_opaque;
611  int finished = fctx->next_finished;
612  PerThreadContext *p;
613  int err;
614 
615  /*
616  * Submit a packet to the next decoding thread.
617  */
618 
619  p = &fctx->threads[fctx->next_decoding];
620  err = update_context_from_user(p->avctx, avctx);
621  if (err) return err;
622  err = submit_packet(p, avpkt);
623  if (err) return err;
624 
625  /*
626  * If we're still receiving the initial packets, don't return a frame.
627  */
628 
629  if (fctx->delaying) {
630  if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
631 
632  *got_picture_ptr=0;
633  if (avpkt->size)
634  return avpkt->size;
635  }
636 
637  /*
638  * Return the next available frame from the oldest thread.
639  * If we're at the end of the stream, then we have to skip threads that
640  * didn't output a frame, because we don't want to accidentally signal
641  * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
642  */
643 
644  do {
645  p = &fctx->threads[finished++];
646 
647  if (p->state != STATE_INPUT_READY) {
649  while (p->state != STATE_INPUT_READY)
652  }
653 
654  *picture = p->frame;
655  *got_picture_ptr = p->got_frame;
656  picture->pkt_dts = p->avpkt.dts;
657 
658  /*
659  * A later call with avkpt->size == 0 may loop over all threads,
660  * including this one, searching for a frame to return before being
661  * stopped by the "finished != fctx->next_finished" condition.
662  * Make sure we don't mistakenly return the same frame again.
663  */
664  p->got_frame = 0;
665 
666  if (finished >= avctx->thread_count) finished = 0;
667  } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
668 
669  update_context_from_thread(avctx, p->avctx, 1);
670 
671  if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
672 
673  fctx->next_finished = finished;
674 
675  /* return the size of the consumed packet if no error occurred */
676  return (p->result >= 0) ? avpkt->size : p->result;
677 }
678 
679 void ff_thread_report_progress(AVFrame *f, int n, int field)
680 {
681  PerThreadContext *p;
682  volatile int *progress = f->thread_opaque;
683 
684  if (!progress || progress[field] >= n) return;
685 
686  p = f->owner->thread_opaque;
687 
688  if (f->owner->debug&FF_DEBUG_THREADS)
689  av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
690 
692  progress[field] = n;
695 }
696 
697 void ff_thread_await_progress(AVFrame *f, int n, int field)
698 {
699  PerThreadContext *p;
700  volatile int *progress = f->thread_opaque;
701 
702  if (!progress || progress[field] >= n) return;
703 
704  p = f->owner->thread_opaque;
705 
706  if (f->owner->debug&FF_DEBUG_THREADS)
707  av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
708 
710  while (progress[field] < n)
713 }
714 
716  PerThreadContext *p = avctx->thread_opaque;
717 
718  if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
719 
720  if(p->state == STATE_SETUP_FINISHED){
721  av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
722  }
723 
725  p->state = STATE_SETUP_FINISHED;
728 }
729 
730 /// Waits for all threads to finish.
731 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
732 {
733  int i;
734 
735  for (i = 0; i < thread_count; i++) {
736  PerThreadContext *p = &fctx->threads[i];
737 
738  if (p->state != STATE_INPUT_READY) {
740  while (p->state != STATE_INPUT_READY)
743  }
744  p->got_frame = 0;
745  }
746 }
747 
748 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
749 {
750  FrameThreadContext *fctx = avctx->thread_opaque;
751  const AVCodec *codec = avctx->codec;
752  int i;
753 
754  park_frame_worker_threads(fctx, thread_count);
755 
756  if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
758 
759  fctx->die = 1;
760 
761  for (i = 0; i < thread_count; i++) {
762  PerThreadContext *p = &fctx->threads[i];
763 
767 
768  if (p->thread_init)
769  pthread_join(p->thread, NULL);
770  p->thread_init=0;
771 
772  if (codec->close)
773  codec->close(p->avctx);
774 
775  avctx->codec = NULL;
776 
778  }
779 
780  for (i = 0; i < thread_count; i++) {
781  PerThreadContext *p = &fctx->threads[i];
782 
784 
790  av_freep(&p->avpkt.data);
791 
792  if (i) {
793  av_freep(&p->avctx->priv_data);
794  av_freep(&p->avctx->internal);
796  }
797 
798  av_freep(&p->avctx);
799  }
800 
801  av_freep(&fctx->threads);
803  av_freep(&avctx->thread_opaque);
804 }
805 
807 {
808  int thread_count = avctx->thread_count;
809  const AVCodec *codec = avctx->codec;
810  AVCodecContext *src = avctx;
811  FrameThreadContext *fctx;
812  int i, err = 0;
813 
814  if (!thread_count) {
815  int nb_cpus = ff_get_logical_cpus(avctx);
816  if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
817  nb_cpus = 1;
818  // use number of cores + 1 as thread count if there is more than one
819  if (nb_cpus > 1)
820  thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
821  else
822  thread_count = avctx->thread_count = 1;
823  }
824 
825  if (thread_count <= 1) {
826  avctx->active_thread_type = 0;
827  return 0;
828  }
829 
830  avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
831 
832  fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
834  fctx->delaying = 1;
835 
836  for (i = 0; i < thread_count; i++) {
838  PerThreadContext *p = &fctx->threads[i];
839 
845 
846  p->parent = fctx;
847  p->avctx = copy;
848 
849  if (!copy) {
850  err = AVERROR(ENOMEM);
851  goto error;
852  }
853 
854  *copy = *src;
855  copy->thread_opaque = p;
856  copy->pkt = &p->avpkt;
857 
858  if (!i) {
859  src = copy;
860 
861  if (codec->init)
862  err = codec->init(copy);
863 
864  update_context_from_thread(avctx, copy, 1);
865  } else {
866  copy->priv_data = av_malloc(codec->priv_data_size);
867  if (!copy->priv_data) {
868  err = AVERROR(ENOMEM);
869  goto error;
870  }
871  memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
872  copy->internal = av_malloc(sizeof(AVCodecInternal));
873  if (!copy->internal) {
874  err = AVERROR(ENOMEM);
875  goto error;
876  }
877  *copy->internal = *src->internal;
878  copy->internal->is_copy = 1;
879 
880  if (codec->init_thread_copy)
881  err = codec->init_thread_copy(copy);
882  }
883 
884  if (err) goto error;
885 
887  p->thread_init= !err;
888  if(!p->thread_init)
889  goto error;
890  }
891 
892  return 0;
893 
894 error:
895  frame_thread_free(avctx, i+1);
896 
897  return err;
898 }
899 
901 {
902  int i;
903  FrameThreadContext *fctx = avctx->thread_opaque;
904 
905  if (!avctx->thread_opaque) return;
906 
908  if (fctx->prev_thread) {
909  if (fctx->prev_thread != &fctx->threads[0])
911  if (avctx->codec->flush)
912  avctx->codec->flush(fctx->threads[0].avctx);
913  }
914 
915  fctx->next_decoding = fctx->next_finished = 0;
916  fctx->delaying = 1;
917  fctx->prev_thread = NULL;
918  for (i = 0; i < avctx->thread_count; i++) {
919  PerThreadContext *p = &fctx->threads[i];
920  // Make sure decode flush calls with size=0 won't return old frames
921  p->got_frame = 0;
922 
924  }
925 }
926 
927 static volatile int *allocate_progress(PerThreadContext *p)
928 {
929  int i;
930 
931  for (i = 0; i < MAX_BUFFERS; i++)
932  if (!p->progress_used[i]) break;
933 
934  if (i == MAX_BUFFERS) {
935  av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
936  return NULL;
937  }
938 
939  p->progress_used[i] = 1;
940 
941  return p->progress[i];
942 }
943 
945 {
946  PerThreadContext *p = avctx->thread_opaque;
947  if ((avctx->active_thread_type&FF_THREAD_FRAME) && p->state != STATE_SETTING_UP &&
948  (avctx->codec->update_thread_context || (!avctx->thread_safe_callbacks &&
950  return 0;
951  }
952  return 1;
953 }
954 
956 {
957  PerThreadContext *p = avctx->thread_opaque;
958  int err;
959  volatile int *progress;
960 
961  f->owner = avctx;
962 
963  ff_init_buffer_info(avctx, f);
964 
965  if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
966  f->thread_opaque = NULL;
967  return ff_get_buffer(avctx, f);
968  }
969 
970  if (p->state != STATE_SETTING_UP &&
971  (avctx->codec->update_thread_context || (!avctx->thread_safe_callbacks &&
973  av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
974  return -1;
975  }
976 
978  f->thread_opaque = (int*)(progress = allocate_progress(p));
979 
980  if (!progress) {
982  return -1;
983  }
984 
985  progress[0] =
986  progress[1] = -1;
987 
988  if (avctx->thread_safe_callbacks ||
990  err = ff_get_buffer(avctx, f);
991  } else {
993  p->requested_frame = f;
994  p->state = STATE_GET_BUFFER;
996 
997  while (p->state != STATE_SETTING_UP)
999 
1000  err = p->result;
1001 
1003 
1004  if (!avctx->codec->update_thread_context)
1005  ff_thread_finish_setup(avctx);
1006  }
1007 
1008  if (err) {
1009  free_progress(f);
1010  f->thread_opaque = NULL;
1011  }
1013 
1014  return err;
1015 }
1016 
1018 {
1019  PerThreadContext *p = avctx->thread_opaque;
1020  FrameThreadContext *fctx;
1021 
1022  if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
1023  avctx->release_buffer(avctx, f);
1024  return;
1025  }
1026 
1027  if (p->num_released_buffers >= MAX_BUFFERS) {
1028  av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
1029  return;
1030  }
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 
1035  fctx = p->parent;
1037  p->released_buffers[p->num_released_buffers++] = *f;
1039  memset(f->data, 0, sizeof(f->data));
1040 }
1041 
1042 /**
1043  * Set the threading algorithms used.
1044  *
1045  * Threading requires more than one thread.
1046  * Frame threading requires entire frames to be passed to the codec,
1047  * and introduces extra decoding delay, so is incompatible with low_delay.
1048  *
1049  * @param avctx The context.
1050  */
1052 {
1053  int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
1054  && !(avctx->flags & CODEC_FLAG_TRUNCATED)
1055  && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
1056  && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
1057  if (avctx->thread_count == 1) {
1058  avctx->active_thread_type = 0;
1059  } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
1061  } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
1062  avctx->thread_type & FF_THREAD_SLICE) {
1064  } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
1065  avctx->thread_count = 1;
1066  avctx->active_thread_type = 0;
1067  }
1068 
1069  if (avctx->thread_count > MAX_AUTO_THREADS)
1070  av_log(avctx, AV_LOG_WARNING,
1071  "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
1072  avctx->thread_count, MAX_AUTO_THREADS);
1073 }
1074 
1076 {
1077  if (avctx->thread_opaque) {
1078  av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
1079  return -1;
1080  }
1081 
1082 #if HAVE_W32THREADS
1083  w32thread_init();
1084 #endif
1085 
1086  if (avctx->codec) {
1088 
1090  return thread_init(avctx);
1091  else if (avctx->active_thread_type&FF_THREAD_FRAME)
1092  return frame_thread_init(avctx);
1093  }
1094 
1095  return 0;
1096 }
1097 
1099 {
1101  frame_thread_free(avctx, avctx->thread_count);
1102  else
1103  thread_free(avctx);
1104 }