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 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 
32 #include "config.h"
33 
34 #if HAVE_SCHED_GETAFFINITY
35 #define _GNU_SOURCE
36 #include <sched.h>
37 #endif
38 #if HAVE_GETPROCESSAFFINITYMASK
39 #include <windows.h>
40 #endif
41 #if HAVE_SYSCTL
42 #if HAVE_SYS_PARAM_H
43 #include <sys/param.h>
44 #endif
45 #include <sys/types.h>
46 #include <sys/sysctl.h>
47 #endif
48 #if HAVE_SYSCONF
49 #include <unistd.h>
50 #endif
51 
52 #include "avcodec.h"
53 #include "internal.h"
54 #include "thread.h"
55 #include "libavutil/common.h"
56 
57 #if HAVE_PTHREADS
58 #include <pthread.h>
59 #elif HAVE_W32THREADS
60 #include "w32pthreads.h"
61 #endif
62 
63 typedef int (action_func)(AVCodecContext *c, void *arg);
64 typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
65 
66 typedef struct ThreadContext {
70  void *args;
71  int *rets;
73  int job_count;
74  int job_size;
75 
79  unsigned current_execute;
81  int done;
83 
85 #define MAX_BUFFERS (32+1)
86 
90 typedef struct PerThreadContext {
92 
98 
101 
103 
106 
108  int got_frame;
109  int result;
110 
111  enum {
119  } state;
120 
127 
133 
136 
140 typedef struct FrameThreadContext {
143 
145 
148 
149  int delaying;
154  int die;
156 
157 
158 /* H264 slice threading seems to be buggy with more than 16 threads,
159  * limit the number of threads to 16 for automatic detection */
160 #define MAX_AUTO_THREADS 16
161 
163 {
164  int ret, nb_cpus = 1;
165 #if HAVE_SCHED_GETAFFINITY && defined(CPU_COUNT)
166  cpu_set_t cpuset;
167 
168  CPU_ZERO(&cpuset);
169 
170  ret = sched_getaffinity(0, sizeof(cpuset), &cpuset);
171  if (!ret) {
172  nb_cpus = CPU_COUNT(&cpuset);
173  }
174 #elif HAVE_GETPROCESSAFFINITYMASK
175  DWORD_PTR proc_aff, sys_aff;
176  ret = GetProcessAffinityMask(GetCurrentProcess(), &proc_aff, &sys_aff);
177  if (ret)
178  nb_cpus = av_popcount64(proc_aff);
179 #elif HAVE_SYSCTL && defined(HW_NCPU)
180  int mib[2] = { CTL_HW, HW_NCPU };
181  size_t len = sizeof(nb_cpus);
182 
183  ret = sysctl(mib, 2, &nb_cpus, &len, NULL, 0);
184  if (ret == -1)
185  nb_cpus = 0;
186 #elif HAVE_SYSCONF && defined(_SC_NPROC_ONLN)
187  nb_cpus = sysconf(_SC_NPROC_ONLN);
188 #elif HAVE_SYSCONF && defined(_SC_NPROCESSORS_ONLN)
189  nb_cpus = sysconf(_SC_NPROCESSORS_ONLN);
190 #endif
191  av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
192  return nb_cpus;
193 }
194 
195 
196 static void* attribute_align_arg worker(void *v)
197 {
198  AVCodecContext *avctx = v;
199  ThreadContext *c = avctx->thread_opaque;
200  unsigned last_execute = 0;
201  int our_job = c->job_count;
202  int thread_count = avctx->thread_count;
203  int self_id;
204 
206  self_id = c->current_job++;
207  for (;;){
208  while (our_job >= c->job_count) {
209  if (c->current_job == thread_count + c->job_count)
211 
212  while (last_execute == c->current_execute && !c->done)
214  last_execute = c->current_execute;
215  our_job = self_id;
216 
217  if (c->done) {
219  return NULL;
220  }
221  }
223 
224  c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
225  c->func2(avctx, c->args, our_job, self_id);
226 
228  our_job = c->current_job++;
229  }
230 }
231 
233 {
234  while (c->current_job != thread_count + c->job_count)
237 }
238 
239 static void thread_free(AVCodecContext *avctx)
240 {
241  ThreadContext *c = avctx->thread_opaque;
242  int i;
243 
245  c->done = 1;
248 
249  for (i=0; i<avctx->thread_count; i++)
250  pthread_join(c->workers[i], NULL);
251 
255  av_free(c->workers);
256  av_freep(&avctx->thread_opaque);
257 }
258 
259 static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
260 {
261  ThreadContext *c= avctx->thread_opaque;
262  int dummy_ret;
263 
264  if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
265  return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
266 
267  if (job_count <= 0)
268  return 0;
269 
271 
272  c->current_job = avctx->thread_count;
273  c->job_count = job_count;
274  c->job_size = job_size;
275  c->args = arg;
276  c->func = func;
277  if (ret) {
278  c->rets = ret;
279  c->rets_count = job_count;
280  } else {
281  c->rets = &dummy_ret;
282  c->rets_count = 1;
283  }
284  c->current_execute++;
286 
288 
289  return 0;
290 }
291 
292 static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
293 {
294  ThreadContext *c= avctx->thread_opaque;
295  c->func2 = func2;
296  return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
297 }
298 
299 static int thread_init(AVCodecContext *avctx)
300 {
301  int i;
302  ThreadContext *c;
303  int thread_count = avctx->thread_count;
304 
305  if (!thread_count) {
306  int nb_cpus = get_logical_cpus(avctx);
307  // use number of cores + 1 as thread count if there is more than one
308  if (nb_cpus > 1)
309  thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
310  else
311  thread_count = avctx->thread_count = 1;
312  }
313 
314  if (thread_count <= 1) {
315  avctx->active_thread_type = 0;
316  return 0;
317  }
318 
319  c = av_mallocz(sizeof(ThreadContext));
320  if (!c)
321  return -1;
322 
323  c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
324  if (!c->workers) {
325  av_free(c);
326  return -1;
327  }
328 
329  avctx->thread_opaque = c;
330  c->current_job = 0;
331  c->job_count = 0;
332  c->job_size = 0;
333  c->done = 0;
338  for (i=0; i<thread_count; i++) {
339  if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
340  avctx->thread_count = i;
342  ff_thread_free(avctx);
343  return -1;
344  }
345  }
346 
347  avcodec_thread_park_workers(c, thread_count);
348 
351  return 0;
352 }
353 
362 {
363  PerThreadContext *p = arg;
364  FrameThreadContext *fctx = p->parent;
365  AVCodecContext *avctx = p->avctx;
366  const AVCodec *codec = avctx->codec;
367 
368  while (1) {
369  if (p->state == STATE_INPUT_READY && !fctx->die) {
371  while (p->state == STATE_INPUT_READY && !fctx->die)
374  }
375 
376  if (fctx->die) break;
377 
378  if (!codec->update_thread_context && avctx->thread_safe_callbacks)
379  ff_thread_finish_setup(avctx);
380 
383  p->got_frame = 0;
384  p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
385 
386  /* many decoders assign whole AVFrames, thus overwriting extended_data;
387  * make sure it's set correctly */
388  p->frame.extended_data = p->frame.data;
389 
390  if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
391 
392  p->state = STATE_INPUT_READY;
393 
397 
399  }
400 
401  return NULL;
402 }
403 
411 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
412 {
413  int err = 0;
414 
415  if (dst != src) {
416  dst->time_base = src->time_base;
417  dst->width = src->width;
418  dst->height = src->height;
419  dst->pix_fmt = src->pix_fmt;
420 
421  dst->coded_width = src->coded_width;
422  dst->coded_height = src->coded_height;
423 
424  dst->has_b_frames = src->has_b_frames;
425  dst->idct_algo = src->idct_algo;
426 
430 
431  dst->profile = src->profile;
432  dst->level = src->level;
433 
435  dst->ticks_per_frame = src->ticks_per_frame;
436  dst->color_primaries = src->color_primaries;
437 
438  dst->color_trc = src->color_trc;
439  dst->colorspace = src->colorspace;
440  dst->color_range = src->color_range;
442  }
443 
444  if (for_user) {
445  dst->coded_frame = src->coded_frame;
446  } else {
447  if (dst->codec->update_thread_context)
448  err = dst->codec->update_thread_context(dst, src);
449  }
450 
451  return err;
452 }
453 
462 {
463 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
464  dst->flags = src->flags;
465 
466  dst->draw_horiz_band= src->draw_horiz_band;
467  dst->get_buffer = src->get_buffer;
468  dst->release_buffer = src->release_buffer;
469 
470  dst->opaque = src->opaque;
471  dst->debug = src->debug;
472  dst->debug_mv = src->debug_mv;
473 
474  dst->slice_flags = src->slice_flags;
475  dst->flags2 = src->flags2;
476 
477  copy_fields(skip_loop_filter, subtitle_header);
478 
479  dst->frame_number = src->frame_number;
481 
482  if (src->slice_count && src->slice_offset) {
483  if (dst->slice_count < src->slice_count) {
484  int *tmp = av_realloc(dst->slice_offset, src->slice_count *
485  sizeof(*dst->slice_offset));
486  if (!tmp) {
487  av_free(dst->slice_offset);
488  return AVERROR(ENOMEM);
489  }
490  dst->slice_offset = tmp;
491  }
492  memcpy(dst->slice_offset, src->slice_offset,
493  src->slice_count * sizeof(*dst->slice_offset));
494  }
495  dst->slice_count = src->slice_count;
496  return 0;
497 #undef copy_fields
498 }
499 
500 static void free_progress(AVFrame *f)
501 {
503  int *progress = f->thread_opaque;
504 
505  p->progress_used[(progress - p->progress[0]) / 2] = 0;
506 }
507 
510 {
511  FrameThreadContext *fctx = p->parent;
512 
513  while (p->num_released_buffers > 0) {
514  AVFrame *f;
515 
518  free_progress(f);
519  f->thread_opaque = NULL;
520 
521  f->owner->release_buffer(f->owner, f);
523  }
524 }
525 
527 {
528  FrameThreadContext *fctx = p->parent;
529  PerThreadContext *prev_thread = fctx->prev_thread;
530  const AVCodec *codec = p->avctx->codec;
531  uint8_t *buf = p->avpkt.data;
532 
533  if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
534 
536 
538 
539  if (prev_thread) {
540  int err;
541  if (prev_thread->state == STATE_SETTING_UP) {
542  pthread_mutex_lock(&prev_thread->progress_mutex);
543  while (prev_thread->state == STATE_SETTING_UP)
544  pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
545  pthread_mutex_unlock(&prev_thread->progress_mutex);
546  }
547 
548  err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
549  if (err) {
551  return err;
552  }
553  }
554 
556  p->avpkt = *avpkt;
557  p->avpkt.data = buf;
558  memcpy(buf, avpkt->data, avpkt->size);
559  memset(buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
560 
561  p->state = STATE_SETTING_UP;
564 
565  /*
566  * If the client doesn't have a thread-safe get_buffer(),
567  * then decoding threads call back to the main thread,
568  * and it calls back to the client here.
569  */
570 
571  if (!p->avctx->thread_safe_callbacks &&
573  while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
575  while (p->state == STATE_SETTING_UP)
577 
578  if (p->state == STATE_GET_BUFFER) {
580  p->state = STATE_SETTING_UP;
582  }
584  }
585  }
586 
587  fctx->prev_thread = p;
588  fctx->next_decoding++;
589 
590  return 0;
591 }
592 
594  AVFrame *picture, int *got_picture_ptr,
595  AVPacket *avpkt)
596 {
597  FrameThreadContext *fctx = avctx->thread_opaque;
598  int finished = fctx->next_finished;
599  PerThreadContext *p;
600  int err;
601 
602  /*
603  * Submit a packet to the next decoding thread.
604  */
605 
606  p = &fctx->threads[fctx->next_decoding];
607  err = update_context_from_user(p->avctx, avctx);
608  if (err) return err;
609  err = submit_packet(p, avpkt);
610  if (err) return err;
611 
612  /*
613  * If we're still receiving the initial packets, don't return a frame.
614  */
615 
616  if (fctx->delaying) {
617  if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
618 
619  *got_picture_ptr=0;
620  if (avpkt->size)
621  return avpkt->size;
622  }
623 
624  /*
625  * Return the next available frame from the oldest thread.
626  * If we're at the end of the stream, then we have to skip threads that
627  * didn't output a frame, because we don't want to accidentally signal
628  * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
629  */
630 
631  do {
632  p = &fctx->threads[finished++];
633 
634  if (p->state != STATE_INPUT_READY) {
636  while (p->state != STATE_INPUT_READY)
639  }
640 
641  *picture = p->frame;
642  *got_picture_ptr = p->got_frame;
643  picture->pkt_dts = p->avpkt.dts;
644 
645  /*
646  * A later call with avkpt->size == 0 may loop over all threads,
647  * including this one, searching for a frame to return before being
648  * stopped by the "finished != fctx->next_finished" condition.
649  * Make sure we don't mistakenly return the same frame again.
650  */
651  p->got_frame = 0;
652 
653  if (finished >= avctx->thread_count) finished = 0;
654  } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
655 
656  update_context_from_thread(avctx, p->avctx, 1);
657 
658  if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
659 
660  fctx->next_finished = finished;
661 
662  /* return the size of the consumed packet if no error occurred */
663  return (p->result >= 0) ? avpkt->size : p->result;
664 }
665 
666 void ff_thread_report_progress(AVFrame *f, int n, int field)
667 {
668  PerThreadContext *p;
669  int *progress = f->thread_opaque;
670 
671  if (!progress || progress[field] >= n) return;
672 
673  p = f->owner->thread_opaque;
674 
675  if (f->owner->debug&FF_DEBUG_THREADS)
676  av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
677 
679  progress[field] = n;
682 }
683 
684 void ff_thread_await_progress(AVFrame *f, int n, int field)
685 {
686  PerThreadContext *p;
687  int *progress = f->thread_opaque;
688 
689  if (!progress || progress[field] >= n) return;
690 
691  p = f->owner->thread_opaque;
692 
693  if (f->owner->debug&FF_DEBUG_THREADS)
694  av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
695 
697  while (progress[field] < n)
700 }
701 
703  PerThreadContext *p = avctx->thread_opaque;
704 
705  if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
706 
708  p->state = STATE_SETUP_FINISHED;
711 }
712 
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  }
728 }
729 
730 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
731 {
732  FrameThreadContext *fctx = avctx->thread_opaque;
733  const AVCodec *codec = avctx->codec;
734  int i;
735 
736  park_frame_worker_threads(fctx, thread_count);
737 
738  if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
740 
741  fctx->die = 1;
742 
743  for (i = 0; i < thread_count; i++) {
744  PerThreadContext *p = &fctx->threads[i];
745 
749 
750  if (p->thread_init)
751  pthread_join(p->thread, NULL);
752 
753  if (codec->close)
754  codec->close(p->avctx);
755 
756  avctx->codec = NULL;
757 
759  }
760 
761  for (i = 0; i < thread_count; i++) {
762  PerThreadContext *p = &fctx->threads[i];
763 
765 
771  av_freep(&p->avpkt.data);
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 = get_logical_cpus(avctx);
797  // use number of cores + 1 as thread count if there is more than one
798  if (nb_cpus > 1)
799  thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
800  else
801  thread_count = avctx->thread_count = 1;
802  }
803 
804  if (thread_count <= 1) {
805  avctx->active_thread_type = 0;
806  return 0;
807  }
808 
809  avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
810 
811  fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
813  fctx->delaying = 1;
814 
815  for (i = 0; i < thread_count; i++) {
817  PerThreadContext *p = &fctx->threads[i];
818 
824 
825  p->parent = fctx;
826  p->avctx = copy;
827 
828  if (!copy) {
829  err = AVERROR(ENOMEM);
830  goto error;
831  }
832 
833  *copy = *src;
834  copy->thread_opaque = p;
835  copy->pkt = &p->avpkt;
836 
837  if (!i) {
838  src = copy;
839 
840  if (codec->init)
841  err = codec->init(copy);
842 
843  update_context_from_thread(avctx, copy, 1);
844  } else {
845  copy->priv_data = av_malloc(codec->priv_data_size);
846  if (!copy->priv_data) {
847  err = AVERROR(ENOMEM);
848  goto error;
849  }
850  memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
851  copy->internal = av_malloc(sizeof(AVCodecInternal));
852  if (!copy->internal) {
853  err = AVERROR(ENOMEM);
854  goto error;
855  }
856  *copy->internal = *src->internal;
857  copy->internal->is_copy = 1;
858 
859  if (codec->init_thread_copy)
860  err = codec->init_thread_copy(copy);
861  }
862 
863  if (err) goto error;
864 
866  p->thread_init = 1;
867  }
868 
869  return 0;
870 
871 error:
872  frame_thread_free(avctx, i+1);
873 
874  return err;
875 }
876 
878 {
879  int i;
880  FrameThreadContext *fctx = avctx->thread_opaque;
881 
882  if (!avctx->thread_opaque) return;
883 
885  if (fctx->prev_thread) {
886  if (fctx->prev_thread != &fctx->threads[0])
888  if (avctx->codec->flush)
889  avctx->codec->flush(fctx->threads[0].avctx);
890  }
891 
892  fctx->next_decoding = fctx->next_finished = 0;
893  fctx->delaying = 1;
894  fctx->prev_thread = NULL;
895  for (i = 0; i < avctx->thread_count; i++) {
896  PerThreadContext *p = &fctx->threads[i];
897  // Make sure decode flush calls with size=0 won't return old frames
898  p->got_frame = 0;
899 
901  }
902 }
903 
905 {
906  int i;
907 
908  for (i = 0; i < MAX_BUFFERS; i++)
909  if (!p->progress_used[i]) break;
910 
911  if (i == MAX_BUFFERS) {
912  av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
913  return NULL;
914  }
915 
916  p->progress_used[i] = 1;
917 
918  return p->progress[i];
919 }
920 
922 {
923  PerThreadContext *p = avctx->thread_opaque;
924  int *progress, err;
925 
926  f->owner = avctx;
927 
928  if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
929  f->thread_opaque = NULL;
930  return ff_get_buffer(avctx, f);
931  }
932 
933  if (p->state != STATE_SETTING_UP &&
934  (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
935  av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
936  return -1;
937  }
938 
940  f->thread_opaque = progress = allocate_progress(p);
941 
942  if (!progress) {
944  return -1;
945  }
946 
947  progress[0] =
948  progress[1] = -1;
949 
950  if (avctx->thread_safe_callbacks ||
952  err = ff_get_buffer(avctx, f);
953  } else {
954  p->requested_frame = f;
955  p->state = STATE_GET_BUFFER;
958 
959  while (p->state != STATE_SETTING_UP)
961 
962  err = p->result;
963 
965 
966  if (!avctx->codec->update_thread_context)
967  ff_thread_finish_setup(avctx);
968  }
969 
970  if (err) {
971  free_progress(f);
972  f->thread_opaque = NULL;
973  }
975 
976  return err;
977 }
978 
980 {
981  PerThreadContext *p = avctx->thread_opaque;
982  FrameThreadContext *fctx;
983 
984  if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
985  avctx->release_buffer(avctx, f);
986  return;
987  }
988 
989  if (p->num_released_buffers >= MAX_BUFFERS) {
990  av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
991  return;
992  }
993 
994  if(avctx->debug & FF_DEBUG_BUFFERS)
995  av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
996 
997  fctx = p->parent;
1001  memset(f->data, 0, sizeof(f->data));
1002 }
1003 
1014 {
1015  int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
1016  && !(avctx->flags & CODEC_FLAG_TRUNCATED)
1017  && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
1018  && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
1019  if (avctx->thread_count == 1) {
1020  avctx->active_thread_type = 0;
1021  } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
1023  } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
1024  avctx->thread_type & FF_THREAD_SLICE) {
1026  } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
1027  avctx->thread_count = 1;
1028  avctx->active_thread_type = 0;
1029  }
1030 
1031  if (avctx->thread_count > MAX_AUTO_THREADS)
1032  av_log(avctx, AV_LOG_WARNING,
1033  "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
1034  avctx->thread_count, MAX_AUTO_THREADS);
1035 }
1036 
1038 {
1039  if (avctx->thread_opaque) {
1040  av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
1041  return -1;
1042  }
1043 
1044 #if HAVE_W32THREADS
1045  w32thread_init();
1046 #endif
1047 
1048  if (avctx->codec) {
1050 
1052  return thread_init(avctx);
1053  else if (avctx->active_thread_type&FF_THREAD_FRAME)
1054  return frame_thread_init(avctx);
1055  }
1056 
1057  return 0;
1058 }
1059 
1061 {
1063  frame_thread_free(avctx, avctx->thread_count);
1064  else
1065  thread_free(avctx);
1066 }
pthread_cond_t progress_cond
Used by child threads to wait for progress to change.
Definition: pthread.c:96
int(* get_buffer)(struct AVCodecContext *c, AVFrame *pic)
Called at the beginning of each frame to get a buffer for it.
Definition: avcodec.h:2248
const struct AVCodec * codec
Definition: avcodec.h:1348
void * av_malloc(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:61
static int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
Definition: w32pthreads.h:200
struct ThreadContext ThreadContext
This structure describes decoded (raw) audio or video data.
Definition: avcodec.h:989
static void pthread_join(pthread_t thread, void **value_ptr)
Definition: w32pthreads.h:87
pthread_t * workers
Definition: pthread.c:67
Context used by codec threads and stored in their AVCodecContext thread_opaque.
Definition: pthread.c:90
static attribute_align_arg void * frame_worker_thread(void *arg)
Codec worker thread.
Definition: pthread.c:361
AVFrame * requested_frame
AVFrame the codec passed to get_buffer()
Definition: pthread.c:134
int coded_width
Bitstream width / height, may be different from width/height.
Definition: avcodec.h:1515
void(* flush)(AVCodecContext *)
Flush buffers.
Definition: avcodec.h:3049
void(* release_buffer)(struct AVCodecContext *c, AVFrame *pic)
Called to release buffers which were allocated with get_buffer.
Definition: avcodec.h:2259
static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
Update the next thread's AVCodecContext with values from the reference thread's context.
Definition: pthread.c:411
static int avcodec_thread_execute(AVCodecContext *avctx, action_func *func, void *arg, int *ret, int job_count, int job_size)
Definition: pthread.c:259
AVFrame * coded_frame
the picture in the bitstream
Definition: avcodec.h:2725
enum AVColorRange color_range
MPEG vs JPEG YUV range.
Definition: avcodec.h:2079
struct AVCodecContext * owner
the AVCodecContext which ff_thread_get_buffer() was last called on
Definition: avcodec.h:1287
int size
Definition: avcodec.h:916
void * thread_opaque
used by multithreading to store frame-specific info
Definition: avcodec.h:1294
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown) That is the width of a pixel divided by the height of the pixel...
Definition: avcodec.h:1724
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:1533
void ff_thread_free(AVCodecContext *avctx)
Definition: pthread.c:1060
int(* decode)(AVCodecContext *, void *outdata, int *outdata_size, AVPacket *avpkt)
Definition: avcodec.h:3043
int bits_per_raw_sample
Bits per sample/pixel of internal libavcodec pixel/sample format.
Definition: avcodec.h:2711
pthread_cond_t last_job_cond
Definition: pthread.c:76
pthread_cond_t input_cond
Used to wait for a new packet from the main thread.
Definition: pthread.c:95
action_func2 * func2
Definition: pthread.c:69
int profile
profile
Definition: avcodec.h:2815
AVCodec.
Definition: avcodec.h:2960
static int * allocate_progress(PerThreadContext *p)
Definition: pthread.c:904
AVPacket avpkt
Input packet (for decoding) or output (for encoding).
Definition: pthread.c:104
#define MAX_BUFFERS
Max number of frame buffers that can be allocated when using frame threads.
Definition: pthread.c:85
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avcodec.h:1465
void av_freep(void *arg)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc() and set the pointer ...
Definition: mem.c:151
void * args
Definition: pthread.c:70
int job_count
Definition: pthread.c:73
void av_fast_malloc(void *ptr, unsigned int *size, size_t min_size)
Allocate a buffer, reusing the given one if large enough.
Definition: utils.c:72
int(* init_thread_copy)(AVCodecContext *)
If defined, called on thread contexts when they are created.
Definition: avcodec.h:3007
static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2 *func2, void *arg, int *ret, int job_count)
Definition: pthread.c:292
uint8_t
static void pthread_cond_init(pthread_cond_t *cond, const void *unused_attr)
Definition: w32pthreads.h:129
int( action_func)(AVCodecContext *c, void *arg)
Definition: pthread.c:63
CRITICAL_SECTION pthread_mutex_t
Definition: w32pthreads.h:54
action_func * func
Definition: pthread.c:68
int ff_thread_decode_frame(AVCodecContext *avctx, AVFrame *picture, int *got_picture_ptr, AVPacket *avpkt)
Submit a new frame to a decoding thread.
Definition: pthread.c:593
uint8_t * data
Definition: avcodec.h:915
int next_decoding
The next context to submit a packet to.
Definition: pthread.c:146
AVFrame frame
Output frame (for decoding) or input (for encoding).
Definition: pthread.c:107
static int pthread_create(pthread_t *thread, const void *unused_attr, void *(*start_routine)(void *), void *arg)
Definition: w32pthreads.h:77
static void copy(LZOContext *c, int cnt)
Copies bytes from input to output buffer with checking.
Definition: lzo.c:79
static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
Definition: pthread.c:232
int bits_per_coded_sample
bits per sample/pixel from the demuxer (needed for huffyuv).
Definition: avcodec.h:2704
static void validate_thread_parameters(AVCodecContext *avctx)
Set the threading algorithms used.
Definition: pthread.c:1013
enum AVChromaLocation chroma_sample_location
This defines the location of chroma samples.
Definition: avcodec.h:2086
Context stored in the client AVCodecContext thread_opaque.
Definition: pthread.c:140
AVCodecContext * avctx
Context used to decode packets passed to this thread.
Definition: pthread.c:102
static void pthread_cond_signal(pthread_cond_t *cond)
Definition: w32pthreads.h:232
int slice_count
slice count
Definition: avcodec.h:1699
int(* close)(AVCodecContext *)
Definition: avcodec.h:3044
void ff_thread_finish_setup(AVCodecContext *avctx)
If the codec defines update_thread_context(), call this when they are ready for the next thread to st...
Definition: pthread.c:702
int has_b_frames
Size of the frame reordering buffer in the decoder.
Definition: avcodec.h:1634
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:139
PerThreadContext * prev_thread
The last thread submit_packet() was called on.
Definition: pthread.c:142
Multithreading support functions.
int is_copy
Whether the parent AVCodecContext is a copy of the context which had init() called on it...
Definition: internal.h:63
static void frame_thread_free(AVCodecContext *avctx, int thread_count)
Definition: pthread.c:730
AVFrame released_buffers[MAX_BUFFERS]
Array of frames passed to ff_thread_release_buffer().
Definition: pthread.c:125
#define MAX_AUTO_THREADS
Definition: pthread.c:160
static int pthread_mutex_init(pthread_mutex_t *m, void *attr)
Definition: w32pthreads.h:97
int active_thread_type
Which multithreading methods are in use by the codec.
Definition: avcodec.h:2752
static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
Waits for all threads to finish.
Definition: pthread.c:714
static int pthread_mutex_unlock(pthread_mutex_t *m)
Definition: w32pthreads.h:112
static int get_logical_cpus(AVCodecContext *avctx)
Definition: pthread.c:162
int capabilities
Codec capabilities.
Definition: avcodec.h:2979
int ff_thread_init(AVCodecContext *avctx)
Definition: pthread.c:1037
int result
The result of the last codec decode/encode() call.
Definition: pthread.c:109
int rets_count
Definition: pthread.c:72
int current_job
Definition: pthread.c:80
int flags
CODEC_FLAG_*.
Definition: avcodec.h:1434
void av_log(void *avcl, int level, const char *fmt,...)
Definition: log.c:146
int die
Set when threads should exit.
Definition: pthread.c:154
void * thread_opaque
thread opaque Can be used by execute() to store some per AVCodecContext stuff.
Definition: avcodec.h:2801
int progress[MAX_BUFFERS][2]
Array of progress values used by ff_thread_get_buffer().
Definition: pthread.c:131
int dtg_active_format
DTG active format information (additional aspect ratio information only used in DVB MPEG-2 transport ...
Definition: avcodec.h:1817
static int pthread_mutex_destroy(pthread_mutex_t *m)
Definition: w32pthreads.h:102
pthread_cond_t output_cond
Used by the main thread to wait for frames to finish.
Definition: pthread.c:97
void(* draw_horiz_band)(struct AVCodecContext *s, const AVFrame *src, int offset[AV_NUM_DATA_POINTERS], int y, int type, int height)
If non NULL, 'draw_horiz_band' is called by the libavcodec decoder to draw a horizontal band...
Definition: avcodec.h:1567
static AVFrame * picture
int job_size
Definition: pthread.c:74
int width
picture width / height.
Definition: avcodec.h:1508
int idct_algo
IDCT algorithm, see FF_IDCT_* below.
Definition: avcodec.h:2661
pthread_mutex_t current_job_lock
Definition: pthread.c:78
int priv_data_size
Definition: avcodec.h:2996
int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame)
Get a buffer for a frame.
Definition: utils.c:464
static void *attribute_align_arg worker(void *v)
Definition: pthread.c:196
enum AVColorPrimaries color_primaries
Chromaticity coordinates of the source primaries.
Definition: avcodec.h:2058
int level
level
Definition: avcodec.h:2885
int num_released_buffers
Definition: pthread.c:126
static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
Update the next thread's AVCodecContext with values set by the user.
Definition: pthread.c:461
int64_t reordered_opaque
opaque 64bit number (generally a PTS) that will be reordered and output in AVFrame.reordered_opaque
Definition: avcodec.h:2615
int ticks_per_frame
For some codecs, the time base is closer to the field rate than the frame rate.
Definition: avcodec.h:1474
pthread_t thread
Definition: pthread.c:93
int thread_count
thread count is used to decide how many independent tasks should be passed to execute() ...
Definition: avcodec.h:2733
int got_frame
The output of got_picture_ptr from the last avcodec_decode_video() call.
Definition: pthread.c:108
pthread_mutex_t buffer_mutex
Mutex used to protect get/release_buffer().
Definition: pthread.c:144
Set when the codec calls get_buffer().
Definition: pthread.c:114
Set after the codec has called ff_thread_finish_setup().
Definition: pthread.c:118
pthread_cond_t current_job_cond
Definition: pthread.c:77
pthread_mutex_t progress_mutex
Mutex used to protect frame progress values and progress_cond.
Definition: pthread.c:100
#define attribute_align_arg
Definition: internal.h:46
NULL
Definition: eval.c:52
static int pthread_mutex_lock(pthread_mutex_t *m)
Definition: w32pthreads.h:107
struct PerThreadContext PerThreadContext
Context used by codec threads and stored in their AVCodecContext thread_opaque.
external API header
void ff_thread_await_progress(AVFrame *f, int n, int field)
Wait for earlier decoding threads to finish reference pictures.
Definition: pthread.c:684
static void pthread_cond_destroy(pthread_cond_t *cond)
Definition: w32pthreads.h:153
int debug
debug
Definition: avcodec.h:2568
main external API structure.
Definition: avcodec.h:1339
enum PerThreadContext::@52 state
void avcodec_default_free_buffers(AVCodecContext *s)
Definition: utils.c:1754
int slice_flags
slice flags
Definition: avcodec.h:1865
int coded_height
Definition: avcodec.h:1515
void avcodec_get_frame_defaults(AVFrame *frame)
Set the fields of the given AVFrame to default values.
Definition: utils.c:602
static void thread_free(AVCodecContext *avctx)
Definition: pthread.c:239
Set before the codec has called ff_thread_finish_setup().
Definition: pthread.c:113
enum AVColorSpace colorspace
YUV colorspace type.
Definition: avcodec.h:2072
enum AVColorTransferCharacteristic color_trc
Color Transfer Characteristic.
Definition: avcodec.h:2065
int delaying
Set for the first N packets, where N is the number of threads.
Definition: pthread.c:149
unsigned current_execute
Definition: pthread.c:79
#define copy_fields(s, e)
Set when the thread is awaiting a packet.
Definition: pthread.c:112
void ff_thread_flush(AVCodecContext *avctx)
Wait for decoding threads to finish and reset internal state.
Definition: pthread.c:877
PerThreadContext * threads
The contexts for each thread.
Definition: pthread.c:141
static void free_progress(AVFrame *f)
Definition: pthread.c:500
struct FrameThreadContext * parent
Definition: pthread.c:91
static void pthread_cond_broadcast(pthread_cond_t *cond)
Definition: w32pthreads.h:169
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: avcodec.h:997
int64_t pkt_dts
dts copied from the AVPacket that triggered returning this frame
Definition: avcodec.h:1102
AVPacket * pkt
Current packet as passed into the decoder, to avoid having to pass the packet into every function...
Definition: avcodec.h:2934
common internal api header.
common internal and external API header
static int thread_init(AVCodecContext *avctx)
Definition: pthread.c:299
void * av_realloc(void *ptr, size_t size)
Allocate or reallocate a block of memory.
Definition: mem.c:116
static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
Definition: pthread.c:526
int thread_safe_callbacks
Set by the client if its custom get_buffer() callback can be called synchronously from another thread...
Definition: avcodec.h:2762
static int frame_thread_init(AVCodecContext *avctx)
Definition: pthread.c:787
struct FrameThreadContext FrameThreadContext
Context stored in the client AVCodecContext thread_opaque.
void * priv_data
Definition: avcodec.h:1382
int(* update_thread_context)(AVCodecContext *dst, const AVCodecContext *src)
Copy necessary context variables from a previous thread context to the current one.
Definition: avcodec.h:3015
int(* execute)(struct AVCodecContext *c, int(*func)(struct AVCodecContext *c2, void *arg), void *arg2, int *ret, int count, int size)
The codec may call this to execute several independent things.
Definition: avcodec.h:2773
int len
static void w32thread_init(void)
Definition: w32pthreads.h:257
int(* execute2)(struct AVCodecContext *c, int(*func)(struct AVCodecContext *c2, void *arg, int jobnr, int threadnr), void *arg2, int *ret, int count)
The codec may call this to execute several independent things.
Definition: avcodec.h:2793
struct AVCodecInternal * internal
Private context used for internal data.
Definition: avcodec.h:1390
pthread_mutex_t mutex
Mutex used to protect the contents of the PerThreadContext.
Definition: pthread.c:99
w32threads to pthreads wrapper
int flags2
CODEC_FLAG2_*.
Definition: avcodec.h:1441
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:914
static void release_delayed_buffers(PerThreadContext *p)
Releases the buffers that this decoding thread was the last user of.
Definition: pthread.c:509
int * slice_offset
slice offsets in the frame in bytes
Definition: avcodec.h:1715
int frame_number
Frame counter, set by libavcodec.
Definition: avcodec.h:2135
int * rets
Definition: pthread.c:71
int avcodec_default_get_buffer(AVCodecContext *s, AVFrame *pic)
Definition: utils.c:451
void ff_thread_report_progress(AVFrame *f, int n, int field)
Notify later decoding threads when part of their reference picture is ready.
Definition: pthread.c:666
int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
Wrapper around get_buffer() for frame-multithreaded codecs.
Definition: pthread.c:921
int( action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr)
Definition: pthread.c:64
int debug_mv
debug
Definition: avcodec.h:2592
int next_finished
The next context to return output from.
Definition: pthread.c:147
static enum AVDiscard skip_loop_filter
Definition: avplay.c:259
int(* init)(AVCodecContext *)
Definition: avcodec.h:3028
uint8_t ** extended_data
pointers to the data planes/channels.
Definition: avcodec.h:1028
This structure stores compressed data.
Definition: avcodec.h:898
int allocated_buf_size
Size allocated for avpkt.data.
Definition: pthread.c:105
void * av_mallocz(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:158
void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
Wrapper around release_buffer() frame-for multithreaded codecs.
Definition: pthread.c:979
void * opaque
Private data of the user, can be used to carry app specific stuff.
Definition: avcodec.h:1397
int thread_type
Which multithreading methods to use.
Definition: avcodec.h:2743
int avcodec_default_execute(AVCodecContext *c, int(*func)(AVCodecContext *c2, void *arg2), void *arg, int *ret, int count, int size)
Definition: utils.c:565
uint8_t progress_used[MAX_BUFFERS]
Definition: pthread.c:132