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 <stdint.h>
28 
29 #include "avcodec.h"
30 #include "internal.h"
31 #include "pthread_internal.h"
32 #include "thread.h"
33 #include "version.h"
34 
35 #include "libavutil/avassert.h"
36 #include "libavutil/buffer.h"
37 #include "libavutil/common.h"
38 #include "libavutil/cpu.h"
39 #include "libavutil/frame.h"
40 #include "libavutil/internal.h"
41 #include "libavutil/log.h"
42 #include "libavutil/mem.h"
43 #include "libavutil/opt.h"
44 #include "libavutil/thread.h"
45 
46 /**
47  * Context used by codec threads and stored in their AVCodecInternal thread_ctx.
48  */
49 typedef struct PerThreadContext {
51 
54  pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
55  pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
56  pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
57 
58  pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
59  pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
60 
61  AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
62 
63  AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
64 
65  AVFrame *frame; ///< Output frame (for decoding) or input (for encoding).
66  int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
67  int result; ///< The result of the last codec decode/encode() call.
68 
69  enum {
70  STATE_INPUT_READY, ///< Set when the thread is awaiting a packet.
71  STATE_SETTING_UP, ///< Set before the codec has called ff_thread_finish_setup().
73  * Set when the codec calls get_buffer().
74  * State is returned to STATE_SETTING_UP afterwards.
75  */
77  * Set when the codec calls get_format().
78  * State is returned to STATE_SETTING_UP afterwards.
79  */
80  STATE_SETUP_FINISHED ///< Set after the codec has called ff_thread_finish_setup().
81  } state;
82 
83  /**
84  * Array of frames passed to ff_thread_release_buffer().
85  * Frames are released after all threads referencing them are finished.
86  */
90 
91  AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
92  int requested_flags; ///< flags passed to get_buffer() for requested_frame
93 
94  const enum AVPixelFormat *available_formats; ///< Format array for get_format()
95  enum AVPixelFormat result_format; ///< get_format() result
96 
97  int die; ///< Set when the thread should exit.
99 
100 /**
101  * Context stored in the client AVCodecInternal thread_ctx.
102  */
103 typedef struct FrameThreadContext {
104  PerThreadContext *threads; ///< The contexts for each thread.
105  PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
106 
107  pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
108 
109  int next_decoding; ///< The next context to submit a packet to.
110  int next_finished; ///< The next context to return output from.
111 
112  int delaying; /**<
113  * Set for the first N packets, where N is the number of threads.
114  * While it is set, ff_thread_en/decode_frame won't return any results.
115  */
117 
118 #define THREAD_SAFE_CALLBACKS(avctx) \
119 ((avctx)->thread_safe_callbacks || (avctx)->get_buffer2 == avcodec_default_get_buffer2)
120 
121 /**
122  * Codec worker thread.
123  *
124  * Automatically calls ff_thread_finish_setup() if the codec does
125  * not provide an update_thread_context method, or if the codec returns
126  * before calling it.
127  */
128 static attribute_align_arg void *frame_worker_thread(void *arg)
129 {
130  PerThreadContext *p = arg;
131  AVCodecContext *avctx = p->avctx;
132  const AVCodec *codec = avctx->codec;
133 
135  while (1) {
136  while (p->state == STATE_INPUT_READY && !p->die)
138 
139  if (p->die) break;
140 
141  if (!codec->update_thread_context && THREAD_SAFE_CALLBACKS(avctx))
142  ff_thread_finish_setup(avctx);
143 
144  av_frame_unref(p->frame);
145  p->got_frame = 0;
146  p->result = codec->decode(avctx, p->frame, &p->got_frame, &p->avpkt);
147 
148  if ((p->result < 0 || !p->got_frame) && p->frame->buf[0]) {
149  if (avctx->internal->allocate_progress)
150  av_log(avctx, AV_LOG_ERROR, "A frame threaded decoder did not "
151  "free the frame on failure. This is a bug, please report it.\n");
152  av_frame_unref(p->frame);
153  }
154 
155  if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
156 
158 #if 0 //BUFREF-FIXME
159  for (i = 0; i < MAX_BUFFERS; i++)
160  if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != AV_CODEC_ID_H264)) {
161  p->progress[i][0] = INT_MAX;
162  p->progress[i][1] = INT_MAX;
163  }
164 #endif
165  p->state = STATE_INPUT_READY;
166 
170  }
172 
173  return NULL;
174 }
175 
176 /**
177  * Update the next thread's AVCodecContext with values from the reference thread's context.
178  *
179  * @param dst The destination context.
180  * @param src The source context.
181  * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
182  * @return 0 on success, negative error code on failure
183  */
185 {
186  int err = 0;
187 
188  if (dst != src) {
189  dst->time_base = src->time_base;
190  dst->framerate = src->framerate;
191  dst->width = src->width;
192  dst->height = src->height;
193  dst->pix_fmt = src->pix_fmt;
194 
195  dst->coded_width = src->coded_width;
196  dst->coded_height = src->coded_height;
197 
198  dst->has_b_frames = src->has_b_frames;
199  dst->idct_algo = src->idct_algo;
200 
203 #if FF_API_AFD
207 #endif /* FF_API_AFD */
208 
209  dst->profile = src->profile;
210  dst->level = src->level;
211 
213  dst->ticks_per_frame = src->ticks_per_frame;
214  dst->color_primaries = src->color_primaries;
215 
216  dst->color_trc = src->color_trc;
217  dst->colorspace = src->colorspace;
218  dst->color_range = src->color_range;
220 
221  dst->hwaccel = src->hwaccel;
222  dst->hwaccel_context = src->hwaccel_context;
223 
224  dst->channels = src->channels;
225  dst->sample_rate = src->sample_rate;
226  dst->sample_fmt = src->sample_fmt;
227  dst->channel_layout = src->channel_layout;
229  }
230 
231  if (for_user) {
232  dst->delay = src->thread_count - 1;
233 #if FF_API_CODED_FRAME
235  dst->coded_frame = src->coded_frame;
237 #endif
238  } else {
239  if (dst->codec->update_thread_context)
240  err = dst->codec->update_thread_context(dst, src);
241  }
242 
243  return err;
244 }
245 
246 /**
247  * Update the next thread's AVCodecContext with values set by the user.
248  *
249  * @param dst The destination context.
250  * @param src The source context.
251  * @return 0 on success, negative error code on failure
252  */
254 {
255 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
256  dst->flags = src->flags;
257 
258  dst->draw_horiz_band= src->draw_horiz_band;
259  dst->get_buffer2 = src->get_buffer2;
260 
261  dst->opaque = src->opaque;
262  dst->debug = src->debug;
263  dst->debug_mv = src->debug_mv;
264 
265  dst->slice_flags = src->slice_flags;
266  dst->flags2 = src->flags2;
267 
268  copy_fields(skip_loop_filter, subtitle_header);
269 
270  dst->frame_number = src->frame_number;
273 
274  if (src->slice_count && src->slice_offset) {
275  if (dst->slice_count < src->slice_count) {
276  int err = av_reallocp_array(&dst->slice_offset, src->slice_count,
277  sizeof(*dst->slice_offset));
278  if (err < 0)
279  return err;
280  }
281  memcpy(dst->slice_offset, src->slice_offset,
282  src->slice_count * sizeof(*dst->slice_offset));
283  }
284  dst->slice_count = src->slice_count;
285  return 0;
286 #undef copy_fields
287 }
288 
289 /// Releases the buffers that this decoding thread was the last user of.
291 {
292  FrameThreadContext *fctx = p->parent;
293 
294  while (p->num_released_buffers > 0) {
295  AVFrame *f;
296 
298 
299  // fix extended data in case the caller screwed it up
303  f->extended_data = f->data;
304  av_frame_unref(f);
305 
307  }
308 }
309 
311 {
312  FrameThreadContext *fctx = p->parent;
313  PerThreadContext *prev_thread = fctx->prev_thread;
314  const AVCodec *codec = p->avctx->codec;
315  int ret;
316 
317  if (!avpkt->size && !(codec->capabilities & AV_CODEC_CAP_DELAY))
318  return 0;
319 
321 
323 
324  if (prev_thread) {
325  int err;
326  if (prev_thread->state == STATE_SETTING_UP) {
327  pthread_mutex_lock(&prev_thread->progress_mutex);
328  while (prev_thread->state == STATE_SETTING_UP)
329  pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
330  pthread_mutex_unlock(&prev_thread->progress_mutex);
331  }
332 
333  err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
334  if (err) {
336  return err;
337  }
338  }
339 
340  av_packet_unref(&p->avpkt);
341  ret = av_packet_ref(&p->avpkt, avpkt);
342  if (ret < 0) {
344  av_log(p->avctx, AV_LOG_ERROR, "av_packet_ref() failed in submit_packet()\n");
345  return ret;
346  }
347 
348  p->state = STATE_SETTING_UP;
351 
352  /*
353  * If the client doesn't have a thread-safe get_buffer(),
354  * then decoding threads call back to the main thread,
355  * and it calls back to the client here.
356  */
357 
358  if (!p->avctx->thread_safe_callbacks && (
361  while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
362  int call_done = 1;
364  while (p->state == STATE_SETTING_UP)
366 
367  switch (p->state) {
368  case STATE_GET_BUFFER:
370  break;
371  case STATE_GET_FORMAT:
373  break;
374  default:
375  call_done = 0;
376  break;
377  }
378  if (call_done) {
379  p->state = STATE_SETTING_UP;
381  }
383  }
384  }
385 
386  fctx->prev_thread = p;
387  fctx->next_decoding++;
388 
389  return 0;
390 }
391 
393  AVFrame *picture, int *got_picture_ptr,
394  AVPacket *avpkt)
395 {
396  FrameThreadContext *fctx = avctx->internal->thread_ctx;
397  int finished = fctx->next_finished;
398  PerThreadContext *p;
399  int err;
400 
401  /*
402  * Submit a packet to the next decoding thread.
403  */
404 
405  p = &fctx->threads[fctx->next_decoding];
406  err = update_context_from_user(p->avctx, avctx);
407  if (err) return err;
408  err = submit_packet(p, avpkt);
409  if (err) return err;
410 
411  /*
412  * If we're still receiving the initial packets, don't return a frame.
413  */
414 
415  if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
416  fctx->delaying = 0;
417 
418  if (fctx->delaying) {
419  *got_picture_ptr=0;
420  if (avpkt->size)
421  return avpkt->size;
422  }
423 
424  /*
425  * Return the next available frame from the oldest thread.
426  * If we're at the end of the stream, then we have to skip threads that
427  * didn't output a frame, because we don't want to accidentally signal
428  * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
429  */
430 
431  do {
432  p = &fctx->threads[finished++];
433 
434  if (p->state != STATE_INPUT_READY) {
436  while (p->state != STATE_INPUT_READY)
439  }
440 
441  av_frame_move_ref(picture, p->frame);
442  *got_picture_ptr = p->got_frame;
443  picture->pkt_dts = p->avpkt.dts;
444 
445  if (p->result < 0)
446  err = p->result;
447 
448  /*
449  * A later call with avkpt->size == 0 may loop over all threads,
450  * including this one, searching for a frame to return before being
451  * stopped by the "finished != fctx->next_finished" condition.
452  * Make sure we don't mistakenly return the same frame again.
453  */
454  p->got_frame = 0;
455 
456  if (finished >= avctx->thread_count) finished = 0;
457  } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
458 
459  update_context_from_thread(avctx, p->avctx, 1);
460 
461  if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
462 
463  fctx->next_finished = finished;
464 
465  /*
466  * When no frame was found while flushing, but an error occurred in
467  * any thread, return it instead of 0.
468  * Otherwise the error can get lost.
469  */
470  if (!avpkt->size && !*got_picture_ptr)
471  return err;
472 
473  /* return the size of the consumed packet if no error occurred */
474  return (p->result >= 0) ? avpkt->size : p->result;
475 }
476 
477 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
478 {
479  PerThreadContext *p;
480  volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
481 
482  if (!progress || progress[field] >= n) return;
483 
484  p = f->owner->internal->thread_ctx;
485 
486  if (f->owner->debug&FF_DEBUG_THREADS)
487  av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
488 
490  progress[field] = n;
493 }
494 
495 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
496 {
497  PerThreadContext *p;
498  volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
499 
500  if (!progress || progress[field] >= n) return;
501 
502  p = f->owner->internal->thread_ctx;
503 
504  if (f->owner->debug&FF_DEBUG_THREADS)
505  av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
506 
508  while (progress[field] < n)
511 }
512 
514  PerThreadContext *p = avctx->internal->thread_ctx;
515 
516  if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
517 
519  if(p->state == STATE_SETUP_FINISHED){
520  av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
521  }
522 
523  p->state = STATE_SETUP_FINISHED;
526 }
527 
528 /// Waits for all threads to finish.
529 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
530 {
531  int i;
532 
533  for (i = 0; i < thread_count; i++) {
534  PerThreadContext *p = &fctx->threads[i];
535 
536  if (p->state != STATE_INPUT_READY) {
538  while (p->state != STATE_INPUT_READY)
541  }
542  p->got_frame = 0;
543  }
544 }
545 
546 void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
547 {
548  FrameThreadContext *fctx = avctx->internal->thread_ctx;
549  const AVCodec *codec = avctx->codec;
550  int i;
551 
552  park_frame_worker_threads(fctx, thread_count);
553 
554  if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
555  if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
556  av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
558  fctx->threads->avctx->internal->is_copy = 1;
559  }
560 
561  for (i = 0; i < thread_count; i++) {
562  PerThreadContext *p = &fctx->threads[i];
563 
565  p->die = 1;
568 
569  if (p->thread_init)
570  pthread_join(p->thread, NULL);
571  p->thread_init=0;
572 
573  if (codec->close && p->avctx)
574  codec->close(p->avctx);
575 
577  av_frame_free(&p->frame);
578  }
579 
580  for (i = 0; i < thread_count; i++) {
581  PerThreadContext *p = &fctx->threads[i];
582 
588  av_packet_unref(&p->avpkt);
590 
591  if (i && p->avctx) {
592  av_freep(&p->avctx->priv_data);
594  }
595 
596  if (p->avctx)
597  av_freep(&p->avctx->internal);
598  av_freep(&p->avctx);
599  }
600 
601  av_freep(&fctx->threads);
603  av_freep(&avctx->internal->thread_ctx);
604 
605  if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
606  av_opt_free(avctx->priv_data);
607  avctx->codec = NULL;
608 }
609 
611 {
612  int thread_count = avctx->thread_count;
613  const AVCodec *codec = avctx->codec;
614  AVCodecContext *src = avctx;
615  FrameThreadContext *fctx;
616  int i, err = 0;
617 
618 #if HAVE_W32THREADS
619  w32thread_init();
620 #endif
621 
622  if (!thread_count) {
623  int nb_cpus = av_cpu_count();
624  if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
625  nb_cpus = 1;
626  // use number of cores + 1 as thread count if there is more than one
627  if (nb_cpus > 1)
628  thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
629  else
630  thread_count = avctx->thread_count = 1;
631  }
632 
633  if (thread_count <= 1) {
634  avctx->active_thread_type = 0;
635  return 0;
636  }
637 
638  avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
639  if (!fctx)
640  return AVERROR(ENOMEM);
641 
642  fctx->threads = av_mallocz_array(thread_count, sizeof(PerThreadContext));
643  if (!fctx->threads) {
644  av_freep(&avctx->internal->thread_ctx);
645  return AVERROR(ENOMEM);
646  }
647 
649  fctx->delaying = 1;
650 
651  for (i = 0; i < thread_count; i++) {
653  PerThreadContext *p = &fctx->threads[i];
654 
660 
661  p->frame = av_frame_alloc();
662  if (!p->frame) {
663  av_freep(&copy);
664  err = AVERROR(ENOMEM);
665  goto error;
666  }
667 
668  p->parent = fctx;
669  p->avctx = copy;
670 
671  if (!copy) {
672  err = AVERROR(ENOMEM);
673  goto error;
674  }
675 
676  *copy = *src;
677 
678  copy->internal = av_malloc(sizeof(AVCodecInternal));
679  if (!copy->internal) {
680  copy->priv_data = NULL;
681  err = AVERROR(ENOMEM);
682  goto error;
683  }
684  *copy->internal = *src->internal;
685  copy->internal->thread_ctx = p;
686  copy->internal->pkt = &p->avpkt;
687 
688  if (!i) {
689  src = copy;
690 
691  if (codec->init)
692  err = codec->init(copy);
693 
694  update_context_from_thread(avctx, copy, 1);
695  } else {
696  copy->priv_data = av_malloc(codec->priv_data_size);
697  if (!copy->priv_data) {
698  err = AVERROR(ENOMEM);
699  goto error;
700  }
701  memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
702  copy->internal->is_copy = 1;
703 
704  if (codec->init_thread_copy)
705  err = codec->init_thread_copy(copy);
706  }
707 
708  if (err) goto error;
709 
711  p->thread_init= !err;
712  if(!p->thread_init)
713  goto error;
714  }
715 
716  return 0;
717 
718 error:
719  ff_frame_thread_free(avctx, i+1);
720 
721  return err;
722 }
723 
725 {
726  int i;
727  FrameThreadContext *fctx = avctx->internal->thread_ctx;
728 
729  if (!fctx) return;
730 
732  if (fctx->prev_thread) {
733  if (fctx->prev_thread != &fctx->threads[0])
735  }
736 
737  fctx->next_decoding = fctx->next_finished = 0;
738  fctx->delaying = 1;
739  fctx->prev_thread = NULL;
740  for (i = 0; i < avctx->thread_count; i++) {
741  PerThreadContext *p = &fctx->threads[i];
742  // Make sure decode flush calls with size=0 won't return old frames
743  p->got_frame = 0;
744  av_frame_unref(p->frame);
745 
747 
748  if (avctx->codec->flush)
749  avctx->codec->flush(p->avctx);
750  }
751 }
752 
754 {
755  PerThreadContext *p = avctx->internal->thread_ctx;
756  if ((avctx->active_thread_type&FF_THREAD_FRAME) && p->state != STATE_SETTING_UP &&
757  (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
758  return 0;
759  }
760  return 1;
761 }
762 
764 {
765  PerThreadContext *p = avctx->internal->thread_ctx;
766  int err;
767 
768  f->owner = avctx;
769 
770  ff_init_buffer_info(avctx, f->f);
771 
772  if (!(avctx->active_thread_type & FF_THREAD_FRAME))
773  return ff_get_buffer(avctx, f->f, flags);
774 
775  if (p->state != STATE_SETTING_UP &&
776  (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
777  av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
778  return -1;
779  }
780 
781  if (avctx->internal->allocate_progress) {
782  int *progress;
783  f->progress = av_buffer_alloc(2 * sizeof(int));
784  if (!f->progress) {
785  return AVERROR(ENOMEM);
786  }
787  progress = (int*)f->progress->data;
788 
789  progress[0] = progress[1] = -1;
790  }
791 
793  if (avctx->thread_safe_callbacks ||
795  err = ff_get_buffer(avctx, f->f, flags);
796  } else {
798  p->requested_frame = f->f;
799  p->requested_flags = flags;
800  p->state = STATE_GET_BUFFER;
802 
803  while (p->state != STATE_SETTING_UP)
805 
806  err = p->result;
807 
809 
810  }
811  if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
812  ff_thread_finish_setup(avctx);
813  if (err)
815 
817 
818  return err;
819 }
820 
822 {
823  enum AVPixelFormat res;
824  PerThreadContext *p = avctx->internal->thread_ctx;
825  if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
827  return ff_get_format(avctx, fmt);
828  if (p->state != STATE_SETTING_UP) {
829  av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
830  return -1;
831  }
833  p->available_formats = fmt;
834  p->state = STATE_GET_FORMAT;
836 
837  while (p->state != STATE_SETTING_UP)
839 
840  res = p->result_format;
841 
843 
844  return res;
845 }
846 
848 {
849  int ret = thread_get_buffer_internal(avctx, f, flags);
850  if (ret < 0)
851  av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
852  return ret;
853 }
854 
856 {
857  PerThreadContext *p = avctx->internal->thread_ctx;
858  FrameThreadContext *fctx;
859  AVFrame *dst, *tmp;
860  int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
861  avctx->thread_safe_callbacks ||
863 
864  if (!f->f || !f->f->buf[0])
865  return;
866 
867  if (avctx->debug & FF_DEBUG_BUFFERS)
868  av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
869 
871  f->owner = NULL;
872 
873  if (can_direct_free) {
874  av_frame_unref(f->f);
875  return;
876  }
877 
878  fctx = p->parent;
880 
881  if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
882  goto fail;
884  (p->num_released_buffers + 1) *
885  sizeof(*p->released_buffers));
886  if (!tmp)
887  goto fail;
888  p->released_buffers = tmp;
889 
891  av_frame_move_ref(dst, f->f);
892 
894 
895 fail:
897 }
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
only access through AVOptions from outside libavcodec
Definition: avcodec.h:2955
pthread_cond_t progress_cond
Used by child threads to wait for progress to change.
Definition: pthread_frame.c:55
#define NULL
Definition: coverity.c:32
const struct AVCodec * codec
Definition: avcodec.h:1700
AVRational framerate
Definition: avcodec.h:3391
enum PerThreadContext::@102 state
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:124
#define copy_fields(s, e)
This structure describes decoded (raw) audio or video data.
Definition: frame.h:190
static av_always_inline int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
Definition: os2threads.h:164
Context used by codec threads and stored in their AVCodecInternal thread_ctx.
Definition: pthread_frame.c:49
int av_cpu_count(void)
Definition: cpu.c:260
AVFrame * requested_frame
AVFrame the codec passed to get_buffer()
Definition: pthread_frame.c:91
int coded_width
Bitstream width / height, may be different from width/height e.g.
Definition: avcodec.h:1893
const char * fmt
Definition: avisynth_c.h:769
void(* flush)(AVCodecContext *)
Flush buffers.
Definition: avcodec.h:3750
#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:373
enum AVColorRange color_range
MPEG vs JPEG YUV range.
Definition: avcodec.h:2428
int size
Definition: avcodec.h:1617
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:2102
AVPacket * pkt
Current packet as passed into the decoder, to avoid having to pass the packet into every function...
Definition: internal.h:144
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:1919
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:252
int(* decode)(AVCodecContext *, void *outdata, int *outdata_size, AVPacket *avpkt)
Definition: avcodec.h:3729
int bits_per_raw_sample
Bits per sample/pixel of internal libavcodec pixel/sample format.
Definition: avcodec.h:3093
pthread_cond_t input_cond
Used to wait for a new packet from the main thread.
Definition: pthread_frame.c:54
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:3197
enum AVPixelFormat * available_formats
Format array for get_format()
Definition: pthread_frame.c:94
AVCodec.
Definition: avcodec.h:3646
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:63
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avcodec.h:1828
struct AVHWAccel * hwaccel
Hardware accelerator in use.
Definition: avcodec.h:3012
#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:993
#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:3693
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:2461
#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:3024
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)
int requested_flags
flags passed to get_buffer() for requested_frame
Definition: pthread_frame.c:92
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:3086
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:2435
Context stored in the client AVCodecInternal thread_ctx.
AVCodecContext * avctx
Context used to decode packets passed to this thread.
Definition: pthread_frame.c:61
#define av_log(a,...)
AVCodecContext * owner
Definition: thread.h:37
Set when the codec calls get_buffer().
Definition: pthread_frame.c:72
int av_packet_ref(AVPacket *dst, const AVPacket *src)
Setup a new reference to the data described by a given packet.
Definition: avpacket.c:580
int die
Set when the thread should exit.
Definition: pthread_frame.c:97
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:2077
Libavcodec version macros.
int(* close)(AVCodecContext *)
Definition: avcodec.h:3730
#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:2013
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.
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:3142
int capabilities
Codec capabilities.
Definition: avcodec.h:3665
int result
The result of the last codec decode/encode() call.
Definition: pthread_frame.c:67
#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:1786
simple assert() macros that are a bit more flexible than ISO C assert().
Set when the thread is awaiting a packet.
Definition: pthread_frame.c:70
static void * av_mallocz_array(size_t nmemb, size_t size)
Definition: mem.h:226
#define fail()
Definition: checkasm.h:85
reference-counted frame API
uint64_t channel_layout
Audio channel layout.
Definition: avcodec.h:2504
int av_reallocp_array(void *ptr, size_t nmemb, size_t size)
Definition: mem.c:215
common internal API header
pthread_cond_t output_cond
Used by the main thread to wait for frames to finish.
Definition: pthread_frame.c:56
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:1952
#define FF_THREAD_FRAME
Decode more than one frame at once.
Definition: avcodec.h:3134
#define FFMIN(a, b)
Definition: common.h:96
Set before the codec has called ff_thread_finish_setup().
Definition: pthread_frame.c:71
int width
picture width / height.
Definition: avcodec.h:1878
int idct_algo
IDCT algorithm, see FF_IDCT_* below.
Definition: avcodec.h:3051
int priv_data_size
Definition: avcodec.h:3682
void ff_thread_report_progress(ThreadFrame *f, int n, int field)
Notify later decoding threads when part of their reference picture is ready.
enum AVColorPrimaries color_primaries
Chromaticity coordinates of the source primaries.
Definition: avcodec.h:2407
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:3295
#define FF_DEBUG_BUFFERS
Definition: avcodec.h:2957
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:480
int64_t reordered_opaque
opaque 64-bit number (generally a PTS) that will be reordered and output in AVFrame.reordered_opaque
Definition: avcodec.h:3005
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:1837
pthread_t thread
Definition: pthread_frame.c:52
#define FF_DEBUG_THREADS
Definition: avcodec.h:2958
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:3123
int got_frame
The output of got_picture_ptr from the last avcodec_decode_video() call.
Definition: pthread_frame.c:66
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:1117
pthread_mutex_t buffer_mutex
Mutex used to protect get/release_buffer().
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:59
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:1699
enum AVCodecID codec_id
Definition: avcodec.h:1708
AVBufferRef * av_buffer_alloc(int size)
Allocate an AVBuffer of the given size using av_malloc().
Definition: buffer.c:66
int sample_rate
samples per second
Definition: avcodec.h:2453
int debug
debug
Definition: avcodec.h:2932
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:1691
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:571
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:2234
int coded_height
Definition: avcodec.h:1893
enum AVPixelFormat(* get_format)(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
callback to negotiate the pixelFormat
Definition: avcodec.h:1969
enum AVColorSpace colorspace
YUV colorspace type.
Definition: avcodec.h:2421
enum AVColorTransferCharacteristic color_trc
Color Transfer Characteristic.
Definition: avcodec.h:2414
enum AVPixelFormat result_format
get_format() result
Definition: pthread_frame.c:95
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:2608
attribute_deprecated int dtg_active_format
DTG active format information (additional aspect ratio information only used in DVB MPEG-2 transport ...
Definition: avcodec.h:2197
PerThreadContext * threads
The contexts for each thread.
int allocate_progress
Whether to allocate progress for frame threading.
Definition: internal.h:126
Set when the codec calls get_format().
Definition: pthread_frame.c:76
#define MAX_AUTO_THREADS
AVFrame * released_buffers
Array of frames passed to ff_thread_release_buffer().
Definition: pthread_frame.c:87
struct FrameThreadContext * parent
Definition: pthread_frame.c:50
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:3672
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:204
int64_t pkt_dts
DTS copied from the AVPacket that triggered returning this frame.
Definition: frame.h:290
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:89
void * hwaccel_priv_data
hwaccel-specific private data
Definition: internal.h:162
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:3114
int thread_safe_callbacks
Set by the client if its custom get_buffer() callback can be called synchronously from another thread...
Definition: avcodec.h:3152
void * priv_data
Definition: avcodec.h:1733
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:3701
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:65
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:2454
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:1741
pthread_mutex_t mutex
Mutex used to protect the contents of the PerThreadContext.
Definition: pthread_frame.c:58
int flags2
AV_CODEC_FLAG2_*.
Definition: avcodec.h:1793
static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
Waits for all threads to finish.
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:1615
int * slice_offset
slice offsets in the frame in bytes
Definition: avcodec.h:2093
int frame_number
Frame counter, set by libavcodec.
Definition: avcodec.h:2484
static void release_delayed_buffers(PerThreadContext *p)
Releases the buffers that this decoding thread was the last user of.
#define av_freep(p)
#define FF_DEBUG_VIS_QP
only access through AVOptions from outside libavcodec
Definition: avcodec.h:2954
static av_always_inline int pthread_mutex_lock(pthread_mutex_t *mutex)
Definition: os2threads.h:113
int debug_mv
debug Code outside libavcodec should access this field using AVOptions
Definition: avcodec.h:2969
int next_finished
The next context to return output from.
int(* init)(AVCodecContext *)
Definition: avcodec.h:3714
uint8_t ** extended_data
pointers to the data planes/channels.
Definition: frame.h:237
Set after the codec has called ff_thread_finish_setup().
Definition: pthread_frame.c:80
AVPixelFormat
Pixel format.
Definition: pixfmt.h:60
This structure stores compressed data.
Definition: avcodec.h:1593
int delay
Codec delay.
Definition: avcodec.h:1861
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:1748
static uint8_t tmp[11]
Definition: aes_ctr.c:26