FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
pthread_frame.c
Go to the documentation of this file.
1 /*
2  * This file is part of FFmpeg.
3  *
4  * FFmpeg is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * FFmpeg is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with FFmpeg; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18 
19 /**
20  * @file
21  * Frame multithreading support functions
22  * @see doc/multithreading.txt
23  */
24 
25 #include "config.h"
26 
27 #include <stdatomic.h>
28 #include <stdint.h>
29 
30 #include "avcodec.h"
31 #include "hwaccel.h"
32 #include "internal.h"
33 #include "pthread_internal.h"
34 #include "thread.h"
35 #include "version.h"
36 
37 #include "libavutil/avassert.h"
38 #include "libavutil/buffer.h"
39 #include "libavutil/common.h"
40 #include "libavutil/cpu.h"
41 #include "libavutil/frame.h"
42 #include "libavutil/internal.h"
43 #include "libavutil/log.h"
44 #include "libavutil/mem.h"
45 #include "libavutil/opt.h"
46 #include "libavutil/thread.h"
47 
48 enum {
49  ///< Set when the thread is awaiting a packet.
51  ///< Set before the codec has called ff_thread_finish_setup().
53  /**
54  * Set when the codec calls get_buffer().
55  * State is returned to STATE_SETTING_UP afterwards.
56  */
58  /**
59  * Set when the codec calls get_format().
60  * State is returned to STATE_SETTING_UP afterwards.
61  */
63  ///< Set after the codec has called ff_thread_finish_setup().
65 };
66 
67 /**
68  * Context used by codec threads and stored in their AVCodecInternal thread_ctx.
69  */
70 typedef struct PerThreadContext {
72 
75  pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
76  pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
77  pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
78 
79  pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
80  pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
81 
82  AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
83 
84  AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
85 
86  AVFrame *frame; ///< Output frame (for decoding) or input (for encoding).
87  int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
88  int result; ///< The result of the last codec decode/encode() call.
89 
91 
92  /**
93  * Array of frames passed to ff_thread_release_buffer().
94  * Frames are released after all threads referencing them are finished.
95  */
99 
100  AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
101  int requested_flags; ///< flags passed to get_buffer() for requested_frame
102 
103  const enum AVPixelFormat *available_formats; ///< Format array for get_format()
104  enum AVPixelFormat result_format; ///< get_format() result
105 
106  int die; ///< Set when the thread should exit.
107 
111 
112 /**
113  * Context stored in the client AVCodecInternal thread_ctx.
114  */
115 typedef struct FrameThreadContext {
116  PerThreadContext *threads; ///< The contexts for each thread.
117  PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
118 
119  pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
120  /**
121  * This lock is used for ensuring threads run in serial when hwaccel
122  * is used.
123  */
126 
127  int next_decoding; ///< The next context to submit a packet to.
128  int next_finished; ///< The next context to return output from.
129 
130  int delaying; /**<
131  * Set for the first N packets, where N is the number of threads.
132  * While it is set, ff_thread_en/decode_frame won't return any results.
133  */
135 
136 #define THREAD_SAFE_CALLBACKS(avctx) \
137 ((avctx)->thread_safe_callbacks || (avctx)->get_buffer2 == avcodec_default_get_buffer2)
138 
139 /**
140  * Codec worker thread.
141  *
142  * Automatically calls ff_thread_finish_setup() if the codec does
143  * not provide an update_thread_context method, or if the codec returns
144  * before calling it.
145  */
146 static attribute_align_arg void *frame_worker_thread(void *arg)
147 {
148  PerThreadContext *p = arg;
149  AVCodecContext *avctx = p->avctx;
150  const AVCodec *codec = avctx->codec;
151 
153  while (1) {
154  while (atomic_load(&p->state) == STATE_INPUT_READY && !p->die)
156 
157  if (p->die) break;
158 
159  if (!codec->update_thread_context && THREAD_SAFE_CALLBACKS(avctx))
160  ff_thread_finish_setup(avctx);
161 
162  /* If a decoder supports hwaccel, then it must call ff_get_format().
163  * Since that call must happen before ff_thread_finish_setup(), the
164  * decoder is required to implement update_thread_context() and call
165  * ff_thread_finish_setup() manually. Therefore the above
166  * ff_thread_finish_setup() call did not happen and hwaccel_serializing
167  * cannot be true here. */
169 
170  /* if the previous thread uses hwaccel then we take the lock to ensure
171  * the threads don't run concurrently */
172  if (avctx->hwaccel) {
174  p->hwaccel_serializing = 1;
175  }
176 
177  av_frame_unref(p->frame);
178  p->got_frame = 0;
179  p->result = codec->decode(avctx, p->frame, &p->got_frame, &p->avpkt);
180 
181  if ((p->result < 0 || !p->got_frame) && p->frame->buf[0]) {
182  if (avctx->internal->allocate_progress)
183  av_log(avctx, AV_LOG_ERROR, "A frame threaded decoder did not "
184  "free the frame on failure. This is a bug, please report it.\n");
185  av_frame_unref(p->frame);
186  }
187 
188  if (atomic_load(&p->state) == STATE_SETTING_UP)
189  ff_thread_finish_setup(avctx);
190 
191  if (p->hwaccel_serializing) {
192  p->hwaccel_serializing = 0;
194  }
195 
196  if (p->async_serializing) {
197  p->async_serializing = 0;
199  }
200 
202 
204 
208  }
210 
211  return NULL;
212 }
213 
214 /**
215  * Update the next thread's AVCodecContext with values from the reference thread's context.
216  *
217  * @param dst The destination context.
218  * @param src The source context.
219  * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
220  * @return 0 on success, negative error code on failure
221  */
223 {
224  int err = 0;
225 
226  if (dst != src) {
227  dst->time_base = src->time_base;
228  dst->framerate = src->framerate;
229  dst->width = src->width;
230  dst->height = src->height;
231  dst->pix_fmt = src->pix_fmt;
232 
233  dst->coded_width = src->coded_width;
234  dst->coded_height = src->coded_height;
235 
236  dst->has_b_frames = src->has_b_frames;
237  dst->idct_algo = src->idct_algo;
238 
241 #if FF_API_AFD
245 #endif /* FF_API_AFD */
246 
247  dst->profile = src->profile;
248  dst->level = src->level;
249 
251  dst->ticks_per_frame = src->ticks_per_frame;
252  dst->color_primaries = src->color_primaries;
253 
254  dst->color_trc = src->color_trc;
255  dst->colorspace = src->colorspace;
256  dst->color_range = src->color_range;
258 
259  dst->hwaccel = src->hwaccel;
260  dst->hwaccel_context = src->hwaccel_context;
261 
262  dst->channels = src->channels;
263  dst->sample_rate = src->sample_rate;
264  dst->sample_fmt = src->sample_fmt;
265  dst->channel_layout = src->channel_layout;
267 
268  if (!!dst->hw_frames_ctx != !!src->hw_frames_ctx ||
269  (dst->hw_frames_ctx && dst->hw_frames_ctx->data != src->hw_frames_ctx->data)) {
271 
272  if (src->hw_frames_ctx) {
274  if (!dst->hw_frames_ctx)
275  return AVERROR(ENOMEM);
276  }
277  }
278 
279  dst->hwaccel_flags = src->hwaccel_flags;
280  }
281 
282  if (for_user) {
283  dst->delay = src->thread_count - 1;
284 #if FF_API_CODED_FRAME
286  dst->coded_frame = src->coded_frame;
288 #endif
289  } else {
290  if (dst->codec->update_thread_context)
291  err = dst->codec->update_thread_context(dst, src);
292  }
293 
294  return err;
295 }
296 
297 /**
298  * Update the next thread's AVCodecContext with values set by the user.
299  *
300  * @param dst The destination context.
301  * @param src The source context.
302  * @return 0 on success, negative error code on failure
303  */
305 {
306 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
307  dst->flags = src->flags;
308 
309  dst->draw_horiz_band= src->draw_horiz_band;
310  dst->get_buffer2 = src->get_buffer2;
311 
312  dst->opaque = src->opaque;
313  dst->debug = src->debug;
314  dst->debug_mv = src->debug_mv;
315 
316  dst->slice_flags = src->slice_flags;
317  dst->flags2 = src->flags2;
318 
319  copy_fields(skip_loop_filter, subtitle_header);
320 
321  dst->frame_number = src->frame_number;
324 
325  if (src->slice_count && src->slice_offset) {
326  if (dst->slice_count < src->slice_count) {
327  int err = av_reallocp_array(&dst->slice_offset, src->slice_count,
328  sizeof(*dst->slice_offset));
329  if (err < 0)
330  return err;
331  }
332  memcpy(dst->slice_offset, src->slice_offset,
333  src->slice_count * sizeof(*dst->slice_offset));
334  }
335  dst->slice_count = src->slice_count;
336  return 0;
337 #undef copy_fields
338 }
339 
340 /// Releases the buffers that this decoding thread was the last user of.
342 {
343  FrameThreadContext *fctx = p->parent;
344 
345  while (p->num_released_buffers > 0) {
346  AVFrame *f;
347 
349 
350  // fix extended data in case the caller screwed it up
354  f->extended_data = f->data;
355  av_frame_unref(f);
356 
358  }
359 }
360 
362 {
363  FrameThreadContext *fctx = p->parent;
364  PerThreadContext *prev_thread = fctx->prev_thread;
365  const AVCodec *codec = p->avctx->codec;
366  int ret;
367 
368  if (!avpkt->size && !(codec->capabilities & AV_CODEC_CAP_DELAY))
369  return 0;
370 
372 
374 
375  if (prev_thread) {
376  int err;
377  if (atomic_load(&prev_thread->state) == STATE_SETTING_UP) {
378  pthread_mutex_lock(&prev_thread->progress_mutex);
379  while (atomic_load(&prev_thread->state) == STATE_SETTING_UP)
380  pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
381  pthread_mutex_unlock(&prev_thread->progress_mutex);
382  }
383 
384  err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
385  if (err) {
387  return err;
388  }
389  }
390 
391  av_packet_unref(&p->avpkt);
392  ret = av_packet_ref(&p->avpkt, avpkt);
393  if (ret < 0) {
395  av_log(p->avctx, AV_LOG_ERROR, "av_packet_ref() failed in submit_packet()\n");
396  return ret;
397  }
398 
402 
403  /*
404  * If the client doesn't have a thread-safe get_buffer(),
405  * then decoding threads call back to the main thread,
406  * and it calls back to the client here.
407  */
408 
409  if (!p->avctx->thread_safe_callbacks && (
413  int call_done = 1;
415  while (atomic_load(&p->state) == STATE_SETTING_UP)
417 
418  switch (atomic_load_explicit(&p->state, memory_order_acquire)) {
419  case STATE_GET_BUFFER:
421  break;
422  case STATE_GET_FORMAT:
424  break;
425  default:
426  call_done = 0;
427  break;
428  }
429  if (call_done) {
432  }
434  }
435  }
436 
437  fctx->prev_thread = p;
438  fctx->next_decoding++;
439 
440  return 0;
441 }
442 
444  AVFrame *picture, int *got_picture_ptr,
445  AVPacket *avpkt)
446 {
447  FrameThreadContext *fctx = avctx->internal->thread_ctx;
448  int finished = fctx->next_finished;
449  PerThreadContext *p;
450  int err, ret;
451 
452  /* release the async lock, permitting blocked hwaccel threads to
453  * go forward while we are in this function */
455 
456  /*
457  * Submit a packet to the next decoding thread.
458  */
459 
460  p = &fctx->threads[fctx->next_decoding];
461  err = update_context_from_user(p->avctx, avctx);
462  if (err)
463  goto finish;
464  err = submit_packet(p, avpkt);
465  if (err)
466  goto finish;
467 
468  /*
469  * If we're still receiving the initial packets, don't return a frame.
470  */
471 
472  if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
473  fctx->delaying = 0;
474 
475  if (fctx->delaying) {
476  *got_picture_ptr=0;
477  if (avpkt->size) {
478  ret = avpkt->size;
479  goto finish;
480  }
481  }
482 
483  /*
484  * Return the next available frame from the oldest thread.
485  * If we're at the end of the stream, then we have to skip threads that
486  * didn't output a frame, because we don't want to accidentally signal
487  * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
488  */
489 
490  do {
491  p = &fctx->threads[finished++];
492 
493  if (atomic_load(&p->state) != STATE_INPUT_READY) {
495  while (atomic_load_explicit(&p->state, memory_order_relaxed) != STATE_INPUT_READY)
498  }
499 
500  av_frame_move_ref(picture, p->frame);
501  *got_picture_ptr = p->got_frame;
502  picture->pkt_dts = p->avpkt.dts;
503 
504  if (p->result < 0)
505  err = p->result;
506 
507  /*
508  * A later call with avkpt->size == 0 may loop over all threads,
509  * including this one, searching for a frame to return before being
510  * stopped by the "finished != fctx->next_finished" condition.
511  * Make sure we don't mistakenly return the same frame again.
512  */
513  p->got_frame = 0;
514 
515  if (finished >= avctx->thread_count) finished = 0;
516  } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
517 
518  update_context_from_thread(avctx, p->avctx, 1);
519 
520  if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
521 
522  fctx->next_finished = finished;
523 
524  /*
525  * When no frame was found while flushing, but an error occurred in
526  * any thread, return it instead of 0.
527  * Otherwise the error can get lost.
528  */
529  if (!avpkt->size && !*got_picture_ptr)
530  goto finish;
531 
532  /* return the size of the consumed packet if no error occurred */
533  ret = (p->result >= 0) ? avpkt->size : p->result;
534 finish:
536  if (err < 0)
537  return err;
538  return ret;
539 }
540 
541 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
542 {
543  PerThreadContext *p;
544  atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
545 
546  if (!progress ||
547  atomic_load_explicit(&progress[field], memory_order_relaxed) >= n)
548  return;
549 
550  p = f->owner->internal->thread_ctx;
551 
552  if (f->owner->debug&FF_DEBUG_THREADS)
553  av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
554 
556 
557  atomic_store_explicit(&progress[field], n, memory_order_release);
558 
561 }
562 
563 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
564 {
565  PerThreadContext *p;
566  atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
567 
568  if (!progress ||
569  atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
570  return;
571 
572  p = f->owner->internal->thread_ctx;
573 
574  if (f->owner->debug&FF_DEBUG_THREADS)
575  av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
576 
578  while (atomic_load_explicit(&progress[field], memory_order_relaxed) < n)
581 }
582 
584  PerThreadContext *p = avctx->internal->thread_ctx;
585 
586  if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
587 
588  if (avctx->hwaccel && !p->hwaccel_serializing) {
590  p->hwaccel_serializing = 1;
591  }
592 
593  /* this assumes that no hwaccel calls happen before ff_thread_finish_setup() */
594  if (avctx->hwaccel &&
596  p->async_serializing = 1;
598  }
599 
602  av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
603  }
604 
606 
609 }
610 
611 /// Waits for all threads to finish.
612 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
613 {
614  int i;
615 
617 
618  for (i = 0; i < thread_count; i++) {
619  PerThreadContext *p = &fctx->threads[i];
620 
621  if (atomic_load(&p->state) != STATE_INPUT_READY) {
623  while (atomic_load(&p->state) != STATE_INPUT_READY)
626  }
627  p->got_frame = 0;
628  }
629 
631 }
632 
633 void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
634 {
635  FrameThreadContext *fctx = avctx->internal->thread_ctx;
636  const AVCodec *codec = avctx->codec;
637  int i;
638 
639  park_frame_worker_threads(fctx, thread_count);
640 
641  if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
642  if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
643  av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
645  fctx->threads->avctx->internal->is_copy = 1;
646  }
647 
648  for (i = 0; i < thread_count; i++) {
649  PerThreadContext *p = &fctx->threads[i];
650 
652  p->die = 1;
655 
656  if (p->thread_init)
657  pthread_join(p->thread, NULL);
658  p->thread_init=0;
659 
660  if (codec->close && p->avctx)
661  codec->close(p->avctx);
662 
664  av_frame_free(&p->frame);
665  }
666 
667  for (i = 0; i < thread_count; i++) {
668  PerThreadContext *p = &fctx->threads[i];
669 
675  av_packet_unref(&p->avpkt);
677 
678  if (i && p->avctx) {
679  av_freep(&p->avctx->priv_data);
681  }
682 
683  if (p->avctx) {
684  av_freep(&p->avctx->internal);
686  }
687 
688  av_freep(&p->avctx);
689  }
690 
691  av_freep(&fctx->threads);
694 
697 
698  av_freep(&avctx->internal->thread_ctx);
699 
700  if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
701  av_opt_free(avctx->priv_data);
702  avctx->codec = NULL;
703 }
704 
706 {
707  int thread_count = avctx->thread_count;
708  const AVCodec *codec = avctx->codec;
709  AVCodecContext *src = avctx;
710  FrameThreadContext *fctx;
711  int i, err = 0;
712 
713 #if HAVE_W32THREADS
714  w32thread_init();
715 #endif
716 
717  if (!thread_count) {
718  int nb_cpus = av_cpu_count();
719  if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
720  nb_cpus = 1;
721  // use number of cores + 1 as thread count if there is more than one
722  if (nb_cpus > 1)
723  thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
724  else
725  thread_count = avctx->thread_count = 1;
726  }
727 
728  if (thread_count <= 1) {
729  avctx->active_thread_type = 0;
730  return 0;
731  }
732 
733  avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
734  if (!fctx)
735  return AVERROR(ENOMEM);
736 
737  fctx->threads = av_mallocz_array(thread_count, sizeof(PerThreadContext));
738  if (!fctx->threads) {
739  av_freep(&avctx->internal->thread_ctx);
740  return AVERROR(ENOMEM);
741  }
742 
745 
748 
749  fctx->delaying = 1;
750 
751  for (i = 0; i < thread_count; i++) {
753  PerThreadContext *p = &fctx->threads[i];
754 
760 
761  p->frame = av_frame_alloc();
762  if (!p->frame) {
763  av_freep(&copy);
764  err = AVERROR(ENOMEM);
765  goto error;
766  }
767 
768  p->parent = fctx;
769  p->avctx = copy;
770 
771  if (!copy) {
772  err = AVERROR(ENOMEM);
773  goto error;
774  }
775 
776  *copy = *src;
777 
778  copy->internal = av_malloc(sizeof(AVCodecInternal));
779  if (!copy->internal) {
780  copy->priv_data = NULL;
781  err = AVERROR(ENOMEM);
782  goto error;
783  }
784  *copy->internal = *src->internal;
785  copy->internal->thread_ctx = p;
786  copy->internal->pkt = &p->avpkt;
787 
788  if (!i) {
789  src = copy;
790 
791  if (codec->init)
792  err = codec->init(copy);
793 
794  update_context_from_thread(avctx, copy, 1);
795  } else {
796  copy->priv_data = av_malloc(codec->priv_data_size);
797  if (!copy->priv_data) {
798  err = AVERROR(ENOMEM);
799  goto error;
800  }
801  memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
802  copy->internal->is_copy = 1;
803 
804  if (codec->init_thread_copy)
805  err = codec->init_thread_copy(copy);
806  }
807 
808  if (err) goto error;
809 
811  p->thread_init= !err;
812  if(!p->thread_init)
813  goto error;
814  }
815 
816  return 0;
817 
818 error:
819  ff_frame_thread_free(avctx, i+1);
820 
821  return err;
822 }
823 
825 {
826  int i;
827  FrameThreadContext *fctx = avctx->internal->thread_ctx;
828 
829  if (!fctx) return;
830 
832  if (fctx->prev_thread) {
833  if (fctx->prev_thread != &fctx->threads[0])
835  }
836 
837  fctx->next_decoding = fctx->next_finished = 0;
838  fctx->delaying = 1;
839  fctx->prev_thread = NULL;
840  for (i = 0; i < avctx->thread_count; i++) {
841  PerThreadContext *p = &fctx->threads[i];
842  // Make sure decode flush calls with size=0 won't return old frames
843  p->got_frame = 0;
844  av_frame_unref(p->frame);
845 
847 
848  if (avctx->codec->flush)
849  avctx->codec->flush(p->avctx);
850  }
851 }
852 
854 {
855  PerThreadContext *p = avctx->internal->thread_ctx;
857  (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
858  return 0;
859  }
860  return 1;
861 }
862 
864 {
865  PerThreadContext *p = avctx->internal->thread_ctx;
866  int err;
867 
868  f->owner = avctx;
869 
870  ff_init_buffer_info(avctx, f->f);
871 
872  if (!(avctx->active_thread_type & FF_THREAD_FRAME))
873  return ff_get_buffer(avctx, f->f, flags);
874 
875  if (atomic_load(&p->state) != STATE_SETTING_UP &&
876  (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
877  av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
878  return -1;
879  }
880 
881  if (avctx->internal->allocate_progress) {
882  atomic_int *progress;
883  f->progress = av_buffer_alloc(2 * sizeof(*progress));
884  if (!f->progress) {
885  return AVERROR(ENOMEM);
886  }
887  progress = (atomic_int*)f->progress->data;
888 
889  atomic_init(&progress[0], -1);
890  atomic_init(&progress[1], -1);
891  }
892 
894  if (avctx->thread_safe_callbacks ||
896  err = ff_get_buffer(avctx, f->f, flags);
897  } else {
899  p->requested_frame = f->f;
900  p->requested_flags = flags;
901  atomic_store_explicit(&p->state, STATE_GET_BUFFER, memory_order_release);
903 
904  while (atomic_load(&p->state) != STATE_SETTING_UP)
906 
907  err = p->result;
908 
910 
911  }
912  if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
913  ff_thread_finish_setup(avctx);
914  if (err)
916 
918 
919  return err;
920 }
921 
923 {
924  enum AVPixelFormat res;
925  PerThreadContext *p = avctx->internal->thread_ctx;
926  if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
928  return ff_get_format(avctx, fmt);
929  if (atomic_load(&p->state) != STATE_SETTING_UP) {
930  av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
931  return -1;
932  }
934  p->available_formats = fmt;
937 
938  while (atomic_load(&p->state) != STATE_SETTING_UP)
940 
941  res = p->result_format;
942 
944 
945  return res;
946 }
947 
949 {
950  int ret = thread_get_buffer_internal(avctx, f, flags);
951  if (ret < 0)
952  av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
953  return ret;
954 }
955 
957 {
958  PerThreadContext *p = avctx->internal->thread_ctx;
959  FrameThreadContext *fctx;
960  AVFrame *dst, *tmp;
961  int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
962  avctx->thread_safe_callbacks ||
964 
965  if (!f->f || !f->f->buf[0])
966  return;
967 
968  if (avctx->debug & FF_DEBUG_BUFFERS)
969  av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
970 
972  f->owner = NULL;
973 
974  if (can_direct_free) {
975  av_frame_unref(f->f);
976  return;
977  }
978 
979  fctx = p->parent;
981 
982  if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
983  goto fail;
985  (p->num_released_buffers + 1) *
986  sizeof(*p->released_buffers));
987  if (!tmp)
988  goto fail;
989  p->released_buffers = tmp;
990 
992  av_frame_move_ref(dst, f->f);
993 
995 
996 fail:
998 }
static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
static av_unused void w32thread_init(void)
Definition: w32pthreads.h:397
#define FF_DEBUG_VIS_MB_TYPE
Definition: avcodec.h:2986
int caps_internal
Internal hwaccel capabilities.
Definition: avcodec.h:3927
pthread_cond_t progress_cond
Used by child threads to wait for progress to change.
Definition: pthread_frame.c:76
#define NULL
Definition: coverity.c:32
const struct AVCodec * codec
Definition: avcodec.h:1731
AVRational framerate
Definition: avcodec.h:3419
static av_always_inline int pthread_mutex_destroy(pthread_mutex_t *mutex)
Definition: os2threads.h:106
static void copy(const float *p1, float *p2, const int length)
void av_buffer_unref(AVBufferRef **buf)
Free a given reference and automatically free the buffer if there are no more references to it...
Definition: buffer.c:125
#define copy_fields(s, e)
This structure describes decoded (raw) audio or video data.
Definition: frame.h:187
static av_always_inline int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
Definition: os2threads.h:164
#define atomic_store(object, desired)
Definition: stdatomic.h:85
Context used by codec threads and stored in their AVCodecInternal thread_ctx.
Definition: pthread_frame.c:70
int av_cpu_count(void)
Definition: cpu.c:260
AVFrame * requested_frame
AVFrame the codec passed to get_buffer()
int coded_width
Bitstream width / height, may be different from width/height e.g.
Definition: avcodec.h:1924
const char * fmt
Definition: avisynth_c.h:769
void(* flush)(AVCodecContext *)
Flush buffers.
Definition: avcodec.h:3775
atomic_int state
Definition: pthread_frame.c:90
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:182
AVFrame * f
Definition: thread.h:36
Memory handling functions.
AVBufferRef * buf[AV_NUM_DATA_POINTERS]
AVBuffer references backing the data for this frame.
Definition: frame.h:370
enum AVColorRange color_range
MPEG vs JPEG YUV range.
Definition: avcodec.h:2459
int size
Definition: avcodec.h:1648
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:2133
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:1950
void av_frame_move_ref(AVFrame *dst, AVFrame *src)
Move everything contained in src to dst and reset src.
Definition: frame.c:524
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:222
int(* decode)(AVCodecContext *, void *outdata, int *outdata_size, AVPacket *avpkt)
Definition: avcodec.h:3754
int bits_per_raw_sample
Bits per sample/pixel of internal libavcodec pixel/sample format.
Definition: avcodec.h:3123
pthread_cond_t input_cond
Used to wait for a new packet from the main thread.
Definition: pthread_frame.c:75
intptr_t atomic_int
Definition: stdatomic.h:55
void ff_thread_await_progress(ThreadFrame *f, int n, int field)
Wait for earlier decoding threads to finish reference pictures.
#define src
Definition: vp8dsp.c:254
int profile
profile
Definition: avcodec.h:3225
enum AVPixelFormat * available_formats
Format array for get_format()
AVCodec.
Definition: avcodec.h:3671
static av_always_inline int pthread_cond_destroy(pthread_cond_t *cond)
Definition: os2threads.h:138
AVPacket avpkt
Input packet (for decoding) or output (for encoding).
Definition: pthread_frame.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:1859
struct AVHWAccel * hwaccel
Hardware accelerator in use.
Definition: avcodec.h:3042
#define AV_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:1019
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
int(* init_thread_copy)(AVCodecContext *)
If defined, called on thread contexts when they are created.
Definition: avcodec.h:3718
HMTX pthread_mutex_t
Definition: os2threads.h:49
enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
Definition: utils.c:1053
enum AVSampleFormat sample_fmt
audio sample format
Definition: avcodec.h:2492
#define av_malloc(s)
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition: frame.c:150
void * hwaccel_context
Hardware accelerator context.
Definition: avcodec.h:3054
AVOptions.
static attribute_align_arg void * frame_worker_thread(void *arg)
Codec worker thread.
void * thread_ctx
Definition: internal.h:138
Multithreading support functions.
#define THREAD_SAFE_CALLBACKS(avctx)
static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
pthread_mutex_t hwaccel_mutex
This lock is used for ensuring threads run in serial when hwaccel is used.
const AVPacket * pkt
Current packet as passed into the decoder, to avoid having to pass the packet into every function...
Definition: internal.h:144
static void finish(void)
Definition: movenc.c:344
int requested_flags
flags passed to get_buffer() for requested_frame
int next_decoding
The next context to submit a packet to.
static int flags
Definition: log.c:57
static av_always_inline int pthread_cond_signal(pthread_cond_t *cond)
Definition: os2threads.h:146
int bits_per_coded_sample
bits per sample/pixel from the demuxer (needed for huffyuv).
Definition: avcodec.h:3116
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...
enum AVChromaLocation chroma_sample_location
This defines the location of chroma samples.
Definition: avcodec.h:2466
Context stored in the client AVCodecInternal thread_ctx.
AVCodecContext * avctx
Context used to decode packets passed to this thread.
Definition: pthread_frame.c:82
#define av_log(a,...)
AVCodecContext * owner
Definition: thread.h:37
int av_packet_ref(AVPacket *dst, const AVPacket *src)
Setup a new reference to the data described by a given packet.
Definition: avpacket.c:584
int die
Set when the thread should exit.
int ff_thread_decode_frame(AVCodecContext *avctx, AVFrame *picture, int *got_picture_ptr, AVPacket *avpkt)
Submit a new frame to a decoding thread.
int slice_count
slice count
Definition: avcodec.h:2108
Libavcodec version macros.
int(* close)(AVCodecContext *)
Definition: avcodec.h:3755
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
int has_b_frames
Size of the frame reordering buffer in the decoder.
Definition: avcodec.h:2044
PerThreadContext * prev_thread
The last thread submit_packet() was called on.
void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
Wrapper around release_buffer() frame-for multithreaded codecs.
#define atomic_load(object)
Definition: stdatomic.h:93
int is_copy
Whether the parent AVCodecContext is a copy of the context which had init() called on it...
Definition: internal.h:111
#define AVERROR(e)
Definition: error.h:43
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:163
int active_thread_type
Which multithreading methods are in use by the codec.
Definition: avcodec.h:3170
int capabilities
Codec capabilities.
Definition: avcodec.h:3690
int result
The result of the last codec decode/encode() call.
Definition: pthread_frame.c:88
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:197
const char * arg
Definition: jacosubdec.c:66
int flags
AV_CODEC_FLAG_*.
Definition: avcodec.h:1817
simple assert() macros that are a bit more flexible than ISO C assert().
static void * av_mallocz_array(size_t nmemb, size_t size)
Definition: mem.h:226
#define fail()
Definition: checkasm.h:89
reference-counted frame API
uint64_t channel_layout
Audio channel layout.
Definition: avcodec.h:2535
int av_reallocp_array(void *ptr, size_t nmemb, size_t size)
Definition: mem.c:191
common internal API header
pthread_cond_t output_cond
Used by the main thread to wait for frames to finish.
Definition: pthread_frame.c:77
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:1983
#define FF_THREAD_FRAME
Decode more than one frame at once.
Definition: avcodec.h:3162
#define FFMIN(a, b)
Definition: common.h:96
int width
picture width / height.
Definition: avcodec.h:1909
int idct_algo
IDCT algorithm, see FF_IDCT_* below.
Definition: avcodec.h:3081
AVBufferRef * hw_frames_ctx
A reference to the AVHWFramesContext describing the input (for encoding) or output (decoding) frames...
Definition: avcodec.h:3575
int priv_data_size
Definition: avcodec.h:3707
void ff_thread_report_progress(ThreadFrame *f, int n, int field)
Notify later decoding threads when part of their reference picture is ready.
#define atomic_load_explicit(object, order)
Definition: stdatomic.h:96
enum AVColorPrimaries color_primaries
Chromaticity coordinates of the source primaries.
Definition: avcodec.h:2438
static av_always_inline int pthread_join(pthread_t thread, void **value_ptr)
Definition: os2threads.h:88
static av_always_inline int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
Definition: os2threads.h:98
int level
level
Definition: avcodec.h:3323
#define FF_DEBUG_BUFFERS
Definition: avcodec.h:2988
void * av_fast_realloc(void *ptr, unsigned int *size, size_t min_size)
Reallocate the given buffer if it is not large enough, otherwise do nothing.
Definition: mem.c:450
int64_t reordered_opaque
opaque 64-bit number (generally a PTS) that will be reordered and output in AVFrame.reordered_opaque
Definition: avcodec.h:3035
int n
Definition: avisynth_c.h:684
int ticks_per_frame
For some codecs, the time base is closer to the field rate than the frame rate.
Definition: avcodec.h:1868
pthread_t thread
Definition: pthread_frame.c:73
#define FF_DEBUG_THREADS
Definition: avcodec.h:2989
static void error(const char *err)
int thread_count
thread count is used to decide how many independent tasks should be passed to execute() ...
Definition: avcodec.h:3151
int got_frame
The output of got_picture_ptr from the last avcodec_decode_video() call.
Definition: pthread_frame.c:87
static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
Update the next thread's AVCodecContext with values set by the user.
int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
Select the (possibly hardware accelerated) pixel format.
Definition: utils.c:1112
pthread_mutex_t buffer_mutex
Mutex used to protect get/release_buffer().
Set when the codec calls get_format().
Definition: pthread_frame.c:62
AVBufferRef * progress
Definition: thread.h:40
pthread_mutex_t progress_mutex
Mutex used to protect frame progress values and progress_cond.
Definition: pthread_frame.c:80
static av_always_inline int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
Definition: os2threads.h:74
int avcodec_default_get_buffer2(AVCodecContext *s, AVFrame *frame, int flags)
The default callback for AVCodecContext.get_buffer2().
Definition: utils.c:728
Libavcodec external API header.
enum AVMediaType codec_type
Definition: avcodec.h:1730
enum AVCodecID codec_id
Definition: avcodec.h:1739
AVBufferRef * av_buffer_alloc(int size)
Allocate an AVBuffer of the given size using av_malloc().
Definition: buffer.c:67
int sample_rate
samples per second
Definition: avcodec.h:2484
int debug
debug
Definition: avcodec.h:2963
int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
Wrapper around get_buffer() for frame-multithreaded codecs.
main external API structure.
Definition: avcodec.h:1722
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:575
uint8_t * data
The data buffer.
Definition: buffer.h:89
int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
Get a buffer for a frame.
Definition: utils.c:953
int ff_init_buffer_info(AVCodecContext *s, AVFrame *frame)
does needed setup of pkt_pts/pos and such for (re)get_buffer();
Definition: utils.c:760
int slice_flags
slice flags
Definition: avcodec.h:2265
int coded_height
Definition: avcodec.h:1924
enum AVPixelFormat(* get_format)(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
callback to negotiate the pixelFormat
Definition: avcodec.h:2000
enum AVColorSpace colorspace
YUV colorspace type.
Definition: avcodec.h:2452
enum AVColorTransferCharacteristic color_trc
Color Transfer Characteristic.
Definition: avcodec.h:2445
enum AVPixelFormat result_format
get_format() result
int delaying
Set for the first N packets, where N is the number of threads.
refcounted data buffer API
enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
Wrapper around get_format() for frame-multithreaded codecs.
int(* get_buffer2)(struct AVCodecContext *s, AVFrame *frame, int flags)
This callback is called at the beginning of each frame to get data buffer(s) for it.
Definition: avcodec.h:2639
#define atomic_store_explicit(object, desired, order)
Definition: stdatomic.h:90
attribute_deprecated int dtg_active_format
DTG active format information (additional aspect ratio information only used in DVB MPEG-2 transport ...
Definition: avcodec.h:2228
PerThreadContext * threads
The contexts for each thread.
int allocate_progress
Whether to allocate progress for frame threading.
Definition: internal.h:126
#define MAX_AUTO_THREADS
AVFrame * released_buffers
Array of frames passed to ff_thread_release_buffer().
Definition: pthread_frame.c:96
struct FrameThreadContext * parent
Definition: pthread_frame.c:71
void av_frame_unref(AVFrame *frame)
Unreference all the buffers referenced by frame and reset the frame fields.
Definition: frame.c:498
const AVClass * priv_class
AVClass for the private context.
Definition: avcodec.h:3697
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:201
int64_t pkt_dts
DTS copied from the AVPacket that triggered returning this frame.
Definition: frame.h:287
Set when the thread is awaiting a packet.
Definition: pthread_frame.c:50
Set when the codec calls get_buffer().
Definition: pthread_frame.c:57
void av_opt_free(void *obj)
Free all allocated objects in obj.
Definition: opt.c:1546
#define FF_DISABLE_DEPRECATION_WARNINGS
Definition: internal.h:84
common internal api header.
common internal and external API header
if(ret< 0)
Definition: vf_mcdeint.c:282
int released_buffers_allocated
Definition: pthread_frame.c:98
void * hwaccel_priv_data
hwaccel-specific private data
Definition: internal.h:162
AVBufferRef * av_buffer_ref(AVBufferRef *buf)
Create a new reference to an AVBuffer.
Definition: buffer.c:93
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.
static av_always_inline int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr)
Definition: os2threads.h:127
attribute_deprecated AVFrame * coded_frame
the picture in the bitstream
Definition: avcodec.h:3142
int thread_safe_callbacks
Set by the client if its custom get_buffer() callback can be called synchronously from another thread...
Definition: avcodec.h:3180
#define HWACCEL_CAP_ASYNC_SAFE
Definition: hwaccel.h:22
void * priv_data
Definition: avcodec.h:1764
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:3726
void ff_thread_flush(AVCodecContext *avctx)
Wait for decoding threads to finish and reset internal state.
AVFrame * frame
Output frame (for decoding) or input (for encoding).
Definition: pthread_frame.c:86
int ff_thread_can_start_frame(AVCodecContext *avctx)
#define FF_ENABLE_DEPRECATION_WARNINGS
Definition: internal.h:85
static av_always_inline int pthread_cond_broadcast(pthread_cond_t *cond)
Definition: os2threads.h:156
int channels
number of audio channels
Definition: avcodec.h:2485
static av_always_inline int pthread_mutex_unlock(pthread_mutex_t *mutex)
Definition: os2threads.h:120
struct AVCodecInternal * internal
Private context used for internal data.
Definition: avcodec.h:1772
pthread_mutex_t mutex
Mutex used to protect the contents of the PerThreadContext.
Definition: pthread_frame.c:79
int flags2
AV_CODEC_FLAG2_*.
Definition: avcodec.h:1824
static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
Waits for all threads to finish.
pthread_mutex_t async_mutex
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:1646
int * slice_offset
slice offsets in the frame in bytes
Definition: avcodec.h:2124
int frame_number
Frame counter, set by libavcodec.
Definition: avcodec.h:2515
static void release_delayed_buffers(PerThreadContext *p)
Releases the buffers that this decoding thread was the last user of.
#define atomic_init(obj, value)
Definition: stdatomic.h:33
#define av_freep(p)
int hwaccel_flags
Bit set of AV_HWACCEL_FLAG_* flags, which affect hardware accelerated decoding (if active)...
Definition: avcodec.h:3636
#define FF_DEBUG_VIS_QP
Definition: avcodec.h:2985
static av_always_inline int pthread_mutex_lock(pthread_mutex_t *mutex)
Definition: os2threads.h:113
int debug_mv
debug
Definition: avcodec.h:2999
int next_finished
The next context to return output from.
int(* init)(AVCodecContext *)
Definition: avcodec.h:3739
uint8_t ** extended_data
pointers to the data planes/channels.
Definition: frame.h:234
AVPixelFormat
Pixel format.
Definition: pixfmt.h:60
This structure stores compressed data.
Definition: avcodec.h:1624
int delay
Codec delay.
Definition: avcodec.h:1892
int ff_frame_thread_init(AVCodecContext *avctx)
void * opaque
Private data of the user, can be used to carry app specific stuff.
Definition: avcodec.h:1779
static uint8_t tmp[11]
Definition: aes_ctr.c:26