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 
56 #if HAVE_PTHREADS
57 #include <pthread.h>
58 #elif HAVE_W32THREADS
59 #include "w32pthreads.h"
60 #endif
61 
62 typedef int (action_func)(AVCodecContext *c, void *arg);
63 typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
64 
65 typedef struct ThreadContext {
69  void *args;
70  int *rets;
72  int job_count;
73  int job_size;
74 
78  unsigned current_execute;
80  int done;
82 
84 #define MAX_BUFFERS (32+1)
85 
89 typedef struct PerThreadContext {
91 
97 
100 
102 
105 
107  int got_frame;
108  int result;
109 
110  enum {
118  } state;
119 
126 
132 
135 
139 typedef struct FrameThreadContext {
142 
144 
147 
148  int delaying;
153  int die;
155 
156 
157 /* H264 slice threading seems to be buggy with more than 16 threads,
158  * limit the number of threads to 16 for automatic detection */
159 #define MAX_AUTO_THREADS 16
160 
162 {
163  int ret, nb_cpus = 1;
164 #if HAVE_SCHED_GETAFFINITY && defined(CPU_COUNT)
165  cpu_set_t cpuset;
166 
167  CPU_ZERO(&cpuset);
168 
169  ret = sched_getaffinity(0, sizeof(cpuset), &cpuset);
170  if (!ret) {
171  nb_cpus = CPU_COUNT(&cpuset);
172  }
173 #elif HAVE_GETPROCESSAFFINITYMASK
174  DWORD_PTR proc_aff, sys_aff;
175  ret = GetProcessAffinityMask(GetCurrentProcess(), &proc_aff, &sys_aff);
176  if (ret)
177  nb_cpus = av_popcount64(proc_aff);
178 #elif HAVE_SYSCTL && defined(HW_NCPU)
179  int mib[2] = { CTL_HW, HW_NCPU };
180  size_t len = sizeof(nb_cpus);
181 
182  ret = sysctl(mib, 2, &nb_cpus, &len, NULL, 0);
183  if (ret == -1)
184  nb_cpus = 0;
185 #elif HAVE_SYSCONF && defined(_SC_NPROC_ONLN)
186  nb_cpus = sysconf(_SC_NPROC_ONLN);
187 #elif HAVE_SYSCONF && defined(_SC_NPROCESSORS_ONLN)
188  nb_cpus = sysconf(_SC_NPROCESSORS_ONLN);
189 #endif
190  av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
191  return nb_cpus;
192 }
193 
194 
195 static void* attribute_align_arg worker(void *v)
196 {
197  AVCodecContext *avctx = v;
198  ThreadContext *c = avctx->thread_opaque;
199  unsigned last_execute = 0;
200  int our_job = c->job_count;
201  int thread_count = avctx->thread_count;
202  int self_id;
203 
205  self_id = c->current_job++;
206  for (;;){
207  while (our_job >= c->job_count) {
208  if (c->current_job == thread_count + c->job_count)
210 
211  while (last_execute == c->current_execute && !c->done)
213  last_execute = c->current_execute;
214  our_job = self_id;
215 
216  if (c->done) {
218  return NULL;
219  }
220  }
222 
223  c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
224  c->func2(avctx, c->args, our_job, self_id);
225 
227  our_job = c->current_job++;
228  }
229 }
230 
232 {
233  while (c->current_job != thread_count + c->job_count)
236 }
237 
238 static void thread_free(AVCodecContext *avctx)
239 {
240  ThreadContext *c = avctx->thread_opaque;
241  int i;
242 
244  c->done = 1;
247 
248  for (i=0; i<avctx->thread_count; i++)
249  pthread_join(c->workers[i], NULL);
250 
254  av_free(c->workers);
255  av_freep(&avctx->thread_opaque);
256 }
257 
258 static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
259 {
260  ThreadContext *c= avctx->thread_opaque;
261  int dummy_ret;
262 
263  if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
264  return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
265 
266  if (job_count <= 0)
267  return 0;
268 
270 
271  c->current_job = avctx->thread_count;
272  c->job_count = job_count;
273  c->job_size = job_size;
274  c->args = arg;
275  c->func = func;
276  if (ret) {
277  c->rets = ret;
278  c->rets_count = job_count;
279  } else {
280  c->rets = &dummy_ret;
281  c->rets_count = 1;
282  }
283  c->current_execute++;
285 
287 
288  return 0;
289 }
290 
291 static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
292 {
293  ThreadContext *c= avctx->thread_opaque;
294  c->func2 = func2;
295  return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
296 }
297 
298 static int thread_init(AVCodecContext *avctx)
299 {
300  int i;
301  ThreadContext *c;
302  int thread_count = avctx->thread_count;
303 
304  if (!thread_count) {
305  int nb_cpus = get_logical_cpus(avctx);
306  // use number of cores + 1 as thread count if there is more than one
307  if (nb_cpus > 1)
308  thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
309  else
310  thread_count = avctx->thread_count = 1;
311  }
312 
313  if (thread_count <= 1) {
314  avctx->active_thread_type = 0;
315  return 0;
316  }
317 
318  c = av_mallocz(sizeof(ThreadContext));
319  if (!c)
320  return -1;
321 
322  c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
323  if (!c->workers) {
324  av_free(c);
325  return -1;
326  }
327 
328  avctx->thread_opaque = c;
329  c->current_job = 0;
330  c->job_count = 0;
331  c->job_size = 0;
332  c->done = 0;
337  for (i=0; i<thread_count; i++) {
338  if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
339  avctx->thread_count = i;
341  ff_thread_free(avctx);
342  return -1;
343  }
344  }
345 
346  avcodec_thread_park_workers(c, thread_count);
347 
350  return 0;
351 }
352 
361 {
362  PerThreadContext *p = arg;
363  FrameThreadContext *fctx = p->parent;
364  AVCodecContext *avctx = p->avctx;
365  AVCodec *codec = avctx->codec;
366 
367  while (1) {
368  if (p->state == STATE_INPUT_READY && !fctx->die) {
370  while (p->state == STATE_INPUT_READY && !fctx->die)
373  }
374 
375  if (fctx->die) break;
376 
377  if (!codec->update_thread_context && avctx->thread_safe_callbacks)
378  ff_thread_finish_setup(avctx);
379 
382  p->got_frame = 0;
383  p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
384 
385  if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
386 
387  p->state = STATE_INPUT_READY;
388 
392 
394  }
395 
396  return NULL;
397 }
398 
406 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
407 {
408  int err = 0;
409 
410  if (dst != src) {
411  dst->sub_id = src->sub_id;
412  dst->time_base = src->time_base;
413  dst->width = src->width;
414  dst->height = src->height;
415  dst->pix_fmt = src->pix_fmt;
416 
417  dst->coded_width = src->coded_width;
418  dst->coded_height = src->coded_height;
419 
420  dst->has_b_frames = src->has_b_frames;
421  dst->idct_algo = src->idct_algo;
422 
426 
427  dst->profile = src->profile;
428  dst->level = src->level;
429 
431  dst->ticks_per_frame = src->ticks_per_frame;
432  dst->color_primaries = src->color_primaries;
433 
434  dst->color_trc = src->color_trc;
435  dst->colorspace = src->colorspace;
436  dst->color_range = src->color_range;
438  }
439 
440  if (for_user) {
441  dst->coded_frame = src->coded_frame;
442  } else {
443  if (dst->codec->update_thread_context)
444  err = dst->codec->update_thread_context(dst, src);
445  }
446 
447  return err;
448 }
449 
458 {
459 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
460  dst->flags = src->flags;
461 
462  dst->draw_horiz_band= src->draw_horiz_band;
463  dst->get_buffer = src->get_buffer;
464  dst->release_buffer = src->release_buffer;
465 
466  dst->opaque = src->opaque;
467  dst->dsp_mask = src->dsp_mask;
468  dst->debug = src->debug;
469  dst->debug_mv = src->debug_mv;
470 
471  dst->slice_flags = src->slice_flags;
472  dst->flags2 = src->flags2;
473 
475 
476  dst->frame_number = src->frame_number;
478 
479  if (src->slice_count && src->slice_offset) {
480  if (dst->slice_count < src->slice_count) {
481  int *tmp = av_realloc(dst->slice_offset, src->slice_count *
482  sizeof(*dst->slice_offset));
483  if (!tmp) {
484  av_free(dst->slice_offset);
485  return AVERROR(ENOMEM);
486  }
487  dst->slice_offset = tmp;
488  }
489  memcpy(dst->slice_offset, src->slice_offset,
490  src->slice_count * sizeof(*dst->slice_offset));
491  }
492  dst->slice_count = src->slice_count;
493  return 0;
494 #undef copy_fields
495 }
496 
497 static void free_progress(AVFrame *f)
498 {
500  int *progress = f->thread_opaque;
501 
502  p->progress_used[(progress - p->progress[0]) / 2] = 0;
503 }
504 
507 {
508  FrameThreadContext *fctx = p->parent;
509 
510  while (p->num_released_buffers > 0) {
511  AVFrame *f;
512 
515  free_progress(f);
516  f->thread_opaque = NULL;
517 
518  f->owner->release_buffer(f->owner, f);
520  }
521 }
522 
524 {
525  FrameThreadContext *fctx = p->parent;
526  PerThreadContext *prev_thread = fctx->prev_thread;
527  AVCodec *codec = p->avctx->codec;
528  uint8_t *buf = p->avpkt.data;
529 
530  if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
531 
533 
535 
536  if (prev_thread) {
537  int err;
538  if (prev_thread->state == STATE_SETTING_UP) {
539  pthread_mutex_lock(&prev_thread->progress_mutex);
540  while (prev_thread->state == STATE_SETTING_UP)
541  pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
542  pthread_mutex_unlock(&prev_thread->progress_mutex);
543  }
544 
545  err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
546  if (err) {
548  return err;
549  }
550  }
551 
553  p->avpkt = *avpkt;
554  p->avpkt.data = buf;
555  memcpy(buf, avpkt->data, avpkt->size);
556  memset(buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
557 
558  p->state = STATE_SETTING_UP;
561 
562  /*
563  * If the client doesn't have a thread-safe get_buffer(),
564  * then decoding threads call back to the main thread,
565  * and it calls back to the client here.
566  */
567 
568  if (!p->avctx->thread_safe_callbacks &&
570  while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
572  while (p->state == STATE_SETTING_UP)
574 
575  if (p->state == STATE_GET_BUFFER) {
577  p->state = STATE_SETTING_UP;
579  }
581  }
582  }
583 
584  fctx->prev_thread = p;
585  fctx->next_decoding++;
586 
587  return 0;
588 }
589 
591  AVFrame *picture, int *got_picture_ptr,
592  AVPacket *avpkt)
593 {
594  FrameThreadContext *fctx = avctx->thread_opaque;
595  int finished = fctx->next_finished;
596  PerThreadContext *p;
597  int err;
598 
599  /*
600  * Submit a packet to the next decoding thread.
601  */
602 
603  p = &fctx->threads[fctx->next_decoding];
604  err = update_context_from_user(p->avctx, avctx);
605  if (err) return err;
606  err = submit_packet(p, avpkt);
607  if (err) return err;
608 
609  /*
610  * If we're still receiving the initial packets, don't return a frame.
611  */
612 
613  if (fctx->delaying && avpkt->size) {
614  if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
615 
616  *got_picture_ptr=0;
617  return avpkt->size;
618  }
619 
620  /*
621  * Return the next available frame from the oldest thread.
622  * If we're at the end of the stream, then we have to skip threads that
623  * didn't output a frame, because we don't want to accidentally signal
624  * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
625  */
626 
627  do {
628  p = &fctx->threads[finished++];
629 
630  if (p->state != STATE_INPUT_READY) {
632  while (p->state != STATE_INPUT_READY)
635  }
636 
637  *picture = p->frame;
638  *got_picture_ptr = p->got_frame;
639  picture->pkt_dts = p->avpkt.dts;
641  picture->width = p->avctx->width;
642  picture->height = p->avctx->height;
643  picture->format = p->avctx->pix_fmt;
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 
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 
731 {
732  FrameThreadContext *fctx = avctx->thread_opaque;
733  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  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  FrameThreadContext *fctx = avctx->thread_opaque;
880 
881  if (!avctx->thread_opaque) return;
882 
884  if (fctx->prev_thread) {
885  if (fctx->prev_thread != &fctx->threads[0])
887  if (avctx->codec->flush)
888  avctx->codec->flush(fctx->threads[0].avctx);
889  }
890 
891  fctx->next_decoding = fctx->next_finished = 0;
892  fctx->delaying = 1;
893  fctx->prev_thread = NULL;
894 }
895 
897 {
898  int i;
899 
900  for (i = 0; i < MAX_BUFFERS; i++)
901  if (!p->progress_used[i]) break;
902 
903  if (i == MAX_BUFFERS) {
904  av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
905  return NULL;
906  }
907 
908  p->progress_used[i] = 1;
909 
910  return p->progress[i];
911 }
912 
914 {
915  PerThreadContext *p = avctx->thread_opaque;
916  int *progress, err;
917 
918  f->owner = avctx;
919 
920  if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
921  f->thread_opaque = NULL;
922  return ff_get_buffer(avctx, f);
923  }
924 
925  if (p->state != STATE_SETTING_UP &&
926  (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
927  av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
928  return -1;
929  }
930 
932  f->thread_opaque = progress = allocate_progress(p);
933 
934  if (!progress) {
936  return -1;
937  }
938 
939  progress[0] =
940  progress[1] = -1;
941 
942  if (avctx->thread_safe_callbacks ||
944  err = ff_get_buffer(avctx, f);
945  } else {
946  p->requested_frame = f;
947  p->state = STATE_GET_BUFFER;
950 
951  while (p->state != STATE_SETTING_UP)
953 
954  err = p->result;
955 
957 
958  if (!avctx->codec->update_thread_context)
959  ff_thread_finish_setup(avctx);
960  }
961 
963 
964  return err;
965 }
966 
968 {
969  PerThreadContext *p = avctx->thread_opaque;
970  FrameThreadContext *fctx;
971 
972  if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
973  avctx->release_buffer(avctx, f);
974  return;
975  }
976 
977  if (p->num_released_buffers >= MAX_BUFFERS) {
978  av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
979  return;
980  }
981 
982  if(avctx->debug & FF_DEBUG_BUFFERS)
983  av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
984 
985  fctx = p->parent;
989  memset(f->data, 0, sizeof(f->data));
990 }
991 
1002 {
1003  int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
1004  && !(avctx->flags & CODEC_FLAG_TRUNCATED)
1005  && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
1006  && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
1007  if (avctx->thread_count == 1) {
1008  avctx->active_thread_type = 0;
1009  } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
1011  } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
1012  avctx->thread_type & FF_THREAD_SLICE) {
1014  } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
1015  avctx->thread_count = 1;
1016  avctx->active_thread_type = 0;
1017  }
1018 }
1019 
1021 {
1022  if (avctx->thread_opaque) {
1023  av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
1024  return -1;
1025  }
1026 
1027 #if HAVE_W32THREADS
1028  w32thread_init();
1029 #endif
1030 
1031  if (avctx->codec) {
1033 
1035  return thread_init(avctx);
1036  else if (avctx->active_thread_type&FF_THREAD_FRAME)
1037  return frame_thread_init(avctx);
1038  }
1039 
1040  return 0;
1041 }
1042 
1044 {
1046  frame_thread_free(avctx, avctx->thread_count);
1047  else
1048  thread_free(avctx);
1049 }
#define CODEC_CAP_AUTO_THREADS
Codec supports avctx->thread_count == 0 (auto).
Definition: avcodec.h:800
pthread_cond_t progress_cond
Used by child threads to wait for progress to change.
Definition: pthread.c:95
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:154
int(* get_buffer)(struct AVCodecContext *c, AVFrame *pic)
Called at the beginning of each frame to get a buffer for it.
Definition: avcodec.h:1726
enum PixelFormat pix_fmt
Pixel format, see PIX_FMT_xxx.
Definition: avcodec.h:1426
struct ThreadContext ThreadContext
Audio Video Frame.
Definition: avcodec.h:985
static void pthread_join(pthread_t thread, void **value_ptr)
Definition: w32pthreads.h:84
pthread_t * workers
Definition: pthread.c:66
Context used by codec threads and stored in their AVCodecContext thread_opaque.
Definition: pthread.c:89
static attribute_align_arg void * frame_worker_thread(void *arg)
Codec worker thread.
Definition: pthread.c:360
AVFrame * requested_frame
AVFrame the codec passed to get_buffer()
Definition: pthread.c:133
int coded_width
Bitstream width / height, may be different from width/height if lowres enabled.
Definition: avcodec.h:2543
void(* flush)(AVCodecContext *)
Flush buffers.
Definition: avcodec.h:3214
void(* release_buffer)(struct AVCodecContext *c, AVFrame *pic)
Called to release buffers which were allocated with get_buffer.
Definition: avcodec.h:1737
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:406
static int avcodec_thread_execute(AVCodecContext *avctx, action_func *func, void *arg, int *ret, int job_count, int job_size)
Definition: pthread.c:258
static void pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
Definition: w32pthreads.h:197
#define CODEC_CAP_FRAME_THREADS
Codec supports frame-level multithreading.
Definition: avcodec.h:788
AVFrame * coded_frame
the picture in the bitstream
Definition: avcodec.h:2000
enum AVColorRange color_range
MPEG vs JPEG YUV range.
Definition: avcodec.h:2947
struct AVCodecContext * owner
the AVCodecContext which ff_thread_get_buffer() was last called on
Definition: avcodec.h:1251
int size
Definition: avcodec.h:909
void * thread_opaque
used by multithreading to store frame-specific info
Definition: avcodec.h:1258
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:1993
void ff_thread_free(AVCodecContext *avctx)
Definition: pthread.c:1043
static int bidir_refine(MpegEncContext *s, int mb_x, int mb_y)
Definition: motion_est.c:1405
void * av_realloc(void *ptr, size_t size)
Allocate or reallocate a block of memory.
Definition: mem.c:117
int(* decode)(AVCodecContext *, void *outdata, int *outdata_size, AVPacket *avpkt)
Definition: avcodec.h:3203
int bits_per_raw_sample
Bits per sample/pixel of internal libavcodec pixel/sample format.
Definition: avcodec.h:2863
pthread_cond_t last_job_cond
Definition: pthread.c:75
pthread_cond_t input_cond
Used to wait for a new packet from the main thread.
Definition: pthread.c:94
struct AVCodec * codec
Definition: avcodec.h:1529
Set before the codec has called ff_thread_finish_setup().
Definition: pthread.c:112
action_func2 * func2
Definition: pthread.c:68
int profile
profile
Definition: avcodec.h:2462
AVCodec.
Definition: avcodec.h:3189
static int * allocate_progress(PerThreadContext *p)
Definition: pthread.c:896
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:71
AVPacket avpkt
Input packet (for decoding) or output (for encoding).
Definition: pthread.c:103
#define v(n)
Definition: regs.h:34
#define MAX_BUFFERS
Max number of frame buffers that can be allocated when using frame threads.
Definition: pthread.c:84
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avcodec.h:1398
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:147
void * args
Definition: pthread.c:69
Set when the thread is awaiting a packet.
Definition: pthread.c:111
unsigned dsp_mask
dsp_mask could be add used to disable unwanted CPU features CPU features (i.e.
Definition: avcodec.h:1967
int job_count
Definition: pthread.c:72
int(* init_thread_copy)(AVCodecContext *)
If defined, called on thread contexts when they are created.
Definition: avcodec.h:3238
static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2 *func2, void *arg, int *ret, int job_count)
Definition: pthread.c:291
static int thread_count
Definition: ffmpeg.c:214
static void pthread_cond_init(pthread_cond_t *cond, const void *unused_attr)
Definition: w32pthreads.h:126
int( action_func)(AVCodecContext *c, void *arg)
Definition: pthread.c:62
CRITICAL_SECTION pthread_mutex_t
Definition: w32pthreads.h:51
action_func * func
Definition: pthread.c:67
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:590
uint8_t * data
Definition: avcodec.h:908
int next_decoding
The next context to submit a packet to.
Definition: pthread.c:145
AVFrame frame
Output frame (for decoding) or input (for encoding).
Definition: pthread.c:106
static int pthread_create(pthread_t *thread, const void *unused_attr, void *(*start_routine)(void *), void *arg)
Definition: w32pthreads.h:74
static void copy(LZOContext *c, int cnt)
Copies bytes from input to output buffer with checking.
Definition: lzo.c:88
static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
Definition: pthread.c:231
int bits_per_coded_sample
bits per sample/pixel from the demuxer (needed for huffyuv).
Definition: avcodec.h:1974
static void validate_thread_parameters(AVCodecContext *avctx)
Set the threading algorithms used.
Definition: pthread.c:1001
enum AVChromaLocation chroma_sample_location
This defines the location of chroma samples.
Definition: avcodec.h:2954
Context stored in the client AVCodecContext thread_opaque.
Definition: pthread.c:139
AVCodecContext * avctx
Context used to decode packets passed to this thread.
Definition: pthread.c:101
static void pthread_cond_signal(pthread_cond_t *cond)
Definition: w32pthreads.h:229
int slice_count
slice count
Definition: avcodec.h:1942
int(* close)(AVCodecContext *)
Definition: avcodec.h:3202
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 width
width and height of the video frame
Definition: avcodec.h:1299
int has_b_frames
Size of the frame reordering buffer in the decoder.
Definition: avcodec.h:1745
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:137
PerThreadContext * prev_thread
The last thread submit_packet() was called on.
Definition: pthread.c:141
int sub_id
Some codecs need additional format info.
Definition: avcodec.h:1365
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
#define AVERROR(e)
Definition: error.h:43
AVFrame released_buffers[MAX_BUFFERS]
Array of frames passed to ff_thread_release_buffer().
Definition: pthread.c:124
#define MAX_AUTO_THREADS
Definition: pthread.c:159
static int pthread_mutex_init(pthread_mutex_t *m, void *attr)
Definition: w32pthreads.h:94
int active_thread_type
Which multithreading methods are in use by the codec.
Definition: avcodec.h:3116
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:109
static int get_logical_cpus(AVCodecContext *avctx)
Definition: pthread.c:161
int capabilities
Codec capabilities.
Definition: avcodec.h:3208
int ff_thread_init(AVCodecContext *avctx)
Definition: pthread.c:1020
int result
The result of the last codec decode/encode() call.
Definition: pthread.c:108
int rets_count
Definition: pthread.c:71
int current_job
Definition: pthread.c:79
int flags
CODEC_FLAG_*.
Definition: avcodec.h:1355
enum PerThreadContext::@43 state
void av_log(void *avcl, int level, const char *fmt,...)
Definition: log.c:140
int die
Set when threads should exit.
Definition: pthread.c:153
#define CODEC_FLAG_TRUNCATED
Definition: avcodec.h:643
void * thread_opaque
thread opaque Can be used by execute() to store some per AVCodecContext stuff.
Definition: avcodec.h:2411
int progress[MAX_BUFFERS][2]
Array of progress values used by ff_thread_get_buffer().
Definition: pthread.c:130
void avcodec_default_free_buffers(AVCodecContext *s)
Definition: utils.c:1614
int dtg_active_format
DTG active format information (additional aspect ratio information only used in DVB MPEG-2 transport ...
Definition: avcodec.h:2145
static int pthread_mutex_destroy(pthread_mutex_t *m)
Definition: w32pthreads.h:99
pthread_cond_t output_cond
Used by the main thread to wait for frames to finish.
Definition: pthread.c:96
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:1451
static AVFrame * picture
int job_size
Definition: pthread.c:73
#define FF_THREAD_FRAME
Decode more than one frame at once.
Definition: avcodec.h:3108
#define FFMIN(a, b)
Definition: common.h:55
#define f(n)
Definition: regs.h:33
int width
picture width / height.
Definition: avcodec.h:1408
int idct_algo
IDCT algorithm, see FF_IDCT_* below.
Definition: avcodec.h:1910
pthread_mutex_t current_job_lock
Definition: pthread.c:77
int priv_data_size
Definition: avcodec.h:3199
int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame)
Definition: utils.c:1867
static void *attribute_align_arg worker(void *v)
Definition: pthread.c:195
enum AVColorPrimaries color_primaries
Chromaticity coordinates of the source primaries.
Definition: avcodec.h:2926
#define FF_THREAD_SLICE
Decode more than one part of a single frame at once.
Definition: avcodec.h:3109
int level
level
Definition: avcodec.h:2528
#define FF_DEBUG_BUFFERS
Definition: avcodec.h:2023
int num_released_buffers
Definition: pthread.c:125
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:457
int64_t reordered_opaque
opaque 64bit number (generally a PTS) that will be reordered and output in AVFrame.reordered_opaque
Definition: avcodec.h:2856
int ticks_per_frame
For some codecs, the time base is closer to the field rate than the frame rate.
Definition: avcodec.h:2907
pthread_t thread
Definition: pthread.c:92
#define FF_DEBUG_THREADS
Definition: avcodec.h:2024
int thread_count
thread count is used to decide how many independent tasks should be passed to execute() ...
Definition: avcodec.h:2392
int got_frame
The output of got_picture_ptr from the last avcodec_decode_video() call.
Definition: pthread.c:107
pthread_mutex_t buffer_mutex
Mutex used to protect get/release_buffer().
Definition: pthread.c:143
int format
format of the frame, -1 if unknown or unset Values correspond to enum PixelFormat for video frames...
Definition: avcodec.h:1308
pthread_cond_t current_job_cond
Definition: pthread.c:76
pthread_mutex_t progress_mutex
Mutex used to protect frame progress values and progress_cond.
Definition: pthread.c:99
#define attribute_align_arg
Definition: internal.h:51
#define CODEC_FLAG_LOW_DELAY
Force low delay.
Definition: avcodec.h:647
NULL
Definition: eval.c:50
static int pthread_mutex_lock(pthread_mutex_t *m)
Definition: w32pthreads.h:104
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:150
int debug
debug
Definition: avcodec.h:2007
main external API structure.
Definition: avcodec.h:1329
AVRational sample_aspect_ratio
sample aspect ratio for the video frame, 0/1 if unknown
Definition: avcodec.h:1292
int avcodec_default_execute(AVCodecContext *c, int(*func)(AVCodecContext *c2, void *arg2), void *arg, int *ret, int count, int size)
Definition: utils.c:583
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:111
int slice_flags
slice flags
Definition: avcodec.h:2242
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:64
int coded_height
Definition: avcodec.h:2543
static void thread_free(AVCodecContext *avctx)
Definition: pthread.c:238
enum AVColorSpace colorspace
YUV colorspace type.
Definition: avcodec.h:2940
enum AVColorTransferCharacteristic color_trc
Color Transfer Characteristic.
Definition: avcodec.h:2933
int delaying
Set for the first N packets, where N is the number of threads.
Definition: pthread.c:148
unsigned current_execute
Definition: pthread.c:78
#define copy_fields(s, e)
#define FF_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding...
Definition: avcodec.h:497
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:140
static void free_progress(AVFrame *f)
Definition: pthread.c:497
struct FrameThreadContext * parent
Definition: pthread.c:90
static void pthread_cond_broadcast(pthread_cond_t *cond)
Definition: w32pthreads.h:166
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: avcodec.h:997
int64_t pkt_dts
dts from the last AVPacket that has been input into the decoder
Definition: avcodec.h:1244
AVPacket * pkt
Current packet as passed into the decoder, to avoid having to pass the packet into every function...
Definition: avcodec.h:3084
common internal api header.
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:125
static int thread_init(AVCodecContext *avctx)
Definition: pthread.c:298
static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
Definition: pthread.c:523
int avcodec_default_get_buffer(AVCodecContext *s, AVFrame *pic)
Definition: utils.c:497
#define CODEC_FLAG2_CHUNKS
Input bitstream might be truncated at a packet boundaries instead of only at frame boundaries...
Definition: avcodec.h:662
int thread_safe_callbacks
Set by the client if its custom get_buffer() callback can be called from another thread, which allows faster multithreaded decoding.
Definition: avcodec.h:3126
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:1531
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:3246
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:2403
int len
static void w32thread_init(void)
Definition: w32pthreads.h:254
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:2974
struct AVCodecInternal * internal
Private context used for internal data.
Definition: avcodec.h:3167
Set after the codec has called ff_thread_finish_setup().
Definition: pthread.c:117
#define CODEC_CAP_SLICE_THREADS
Codec supports slice-based (or partition-based) multithreading.
Definition: avcodec.h:792
pthread_mutex_t mutex
Mutex used to protect the contents of the PerThreadContext.
Definition: pthread.c:98
w32threads to pthreads wrapper
int flags2
CODEC_FLAG2_*.
Definition: avcodec.h:2357
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:907
static void release_delayed_buffers(PerThreadContext *p)
Releases the buffers that this decoding thread was the last user of.
Definition: pthread.c:506
int * slice_offset
slice offsets in the frame in bytes
Definition: avcodec.h:1948
int frame_number
audio or video frame number
Definition: avcodec.h:1471
int * rets
Definition: pthread.c:70
int height
Definition: avcodec.h:1299
void avcodec_get_frame_defaults(AVFrame *pic)
Set the fields of the given AVFrame to default values.
Definition: utils.c:609
#define av_always_inline
Definition: attributes.h:39
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:913
#define CODEC_CAP_DELAY
Encoder or decoder requires flushing with NULL input at the end in order to give the complete and cor...
Definition: avcodec.h:750
int( action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr)
Definition: pthread.c:63
int debug_mv
debug
Definition: avcodec.h:2031
int next_finished
The next context to return output from.
Definition: pthread.c:146
static enum AVDiscard skip_loop_filter
Definition: avplay.c:252
int(* init)(AVCodecContext *)
Definition: avcodec.h:3200
int allocated_buf_size
Size allocated for avpkt.data.
Definition: pthread.c:104
void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
Wrapper around release_buffer() frame-for multithreaded codecs.
Definition: pthread.c:967
Set when the codec calls get_buffer().
Definition: pthread.c:113
void * opaque
Private data of the user, can be used to carry app specific stuff.
Definition: avcodec.h:1571
int thread_type
Which multithreading methods to use.
Definition: avcodec.h:3107
uint8_t progress_used[MAX_BUFFERS]
Definition: pthread.c:131