FFmpeg  2.7.2
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Modules 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 #if HAVE_PTHREADS
30 #include <pthread.h>
31 #elif HAVE_W32THREADS
32 #include "compat/w32pthreads.h"
33 #elif HAVE_OS2THREADS
34 #include "compat/os2threads.h"
35 #endif
36 
37 #include "avcodec.h"
38 #include "internal.h"
39 #include "pthread_internal.h"
40 #include "thread.h"
41 #include "version.h"
42 
43 #include "libavutil/avassert.h"
44 #include "libavutil/buffer.h"
45 #include "libavutil/common.h"
46 #include "libavutil/cpu.h"
47 #include "libavutil/frame.h"
48 #include "libavutil/internal.h"
49 #include "libavutil/log.h"
50 #include "libavutil/mem.h"
51 #include "libavutil/opt.h"
52 
53 /**
54  * Context used by codec threads and stored in their AVCodecInternal thread_ctx.
55  */
56 typedef struct PerThreadContext {
58 
61  pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
62  pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
63  pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
64 
65  pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
66  pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
67 
68  AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
69 
70  AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
71 
72  AVFrame *frame; ///< Output frame (for decoding) or input (for encoding).
73  int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
74  int result; ///< The result of the last codec decode/encode() call.
75 
76  enum {
77  STATE_INPUT_READY, ///< Set when the thread is awaiting a packet.
78  STATE_SETTING_UP, ///< Set before the codec has called ff_thread_finish_setup().
80  * Set when the codec calls get_buffer().
81  * State is returned to STATE_SETTING_UP afterwards.
82  */
84  * Set when the codec calls get_format().
85  * State is returned to STATE_SETTING_UP afterwards.
86  */
87  STATE_SETUP_FINISHED ///< Set after the codec has called ff_thread_finish_setup().
88  } state;
89 
90  /**
91  * Array of frames passed to ff_thread_release_buffer().
92  * Frames are released after all threads referencing them are finished.
93  */
97 
98  AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
99  int requested_flags; ///< flags passed to get_buffer() for requested_frame
100 
101  const enum AVPixelFormat *available_formats; ///< Format array for get_format()
102  enum AVPixelFormat result_format; ///< get_format() result
104 
105 /**
106  * Context stored in the client AVCodecInternal thread_ctx.
107  */
108 typedef struct FrameThreadContext {
109  PerThreadContext *threads; ///< The contexts for each thread.
110  PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
111 
112  pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
113 
114  int next_decoding; ///< The next context to submit a packet to.
115  int next_finished; ///< The next context to return output from.
116 
117  int delaying; /**<
118  * Set for the first N packets, where N is the number of threads.
119  * While it is set, ff_thread_en/decode_frame won't return any results.
120  */
121 
122  int die; ///< Set when threads should exit.
124 
125 #if FF_API_GET_BUFFER
126 #define THREAD_SAFE_CALLBACKS(avctx) \
127 ((avctx)->thread_safe_callbacks || (!(avctx)->get_buffer && (avctx)->get_buffer2 == avcodec_default_get_buffer2))
128 #else
129 #define THREAD_SAFE_CALLBACKS(avctx) \
130 ((avctx)->thread_safe_callbacks || (avctx)->get_buffer2 == avcodec_default_get_buffer2)
131 #endif
132 
133 /**
134  * Codec worker thread.
135  *
136  * Automatically calls ff_thread_finish_setup() if the codec does
137  * not provide an update_thread_context method, or if the codec returns
138  * before calling it.
139  */
141 {
142  PerThreadContext *p = arg;
143  FrameThreadContext *fctx = p->parent;
144  AVCodecContext *avctx = p->avctx;
145  const AVCodec *codec = avctx->codec;
146 
148  while (1) {
149  while (p->state == STATE_INPUT_READY && !fctx->die)
151 
152  if (fctx->die) break;
153 
154  if (!codec->update_thread_context && THREAD_SAFE_CALLBACKS(avctx))
155  ff_thread_finish_setup(avctx);
156 
157  av_frame_unref(p->frame);
158  p->got_frame = 0;
159  p->result = codec->decode(avctx, p->frame, &p->got_frame, &p->avpkt);
160 
161  if ((p->result < 0 || !p->got_frame) && p->frame->buf[0]) {
162  if (avctx->internal->allocate_progress)
163  av_log(avctx, AV_LOG_ERROR, "A frame threaded decoder did not "
164  "free the frame on failure. This is a bug, please report it.\n");
165  av_frame_unref(p->frame);
166  }
167 
168  if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
169 
171 #if 0 //BUFREF-FIXME
172  for (i = 0; i < MAX_BUFFERS; i++)
173  if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != AV_CODEC_ID_H264)) {
174  p->progress[i][0] = INT_MAX;
175  p->progress[i][1] = INT_MAX;
176  }
177 #endif
178  p->state = STATE_INPUT_READY;
179 
183  }
185 
186  return NULL;
187 }
188 
189 /**
190  * Update the next thread's AVCodecContext with values from the reference thread's context.
191  *
192  * @param dst The destination context.
193  * @param src The source context.
194  * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
195  */
197 {
198  int err = 0;
199 
200  if (dst != src) {
201  dst->time_base = src->time_base;
202  dst->framerate = src->framerate;
203  dst->width = src->width;
204  dst->height = src->height;
205  dst->pix_fmt = src->pix_fmt;
206 
207  dst->coded_width = src->coded_width;
208  dst->coded_height = src->coded_height;
209 
210  dst->has_b_frames = src->has_b_frames;
211  dst->idct_algo = src->idct_algo;
212 
215 #if FF_API_AFD
219 #endif /* FF_API_AFD */
220 
221  dst->profile = src->profile;
222  dst->level = src->level;
223 
225  dst->ticks_per_frame = src->ticks_per_frame;
226  dst->color_primaries = src->color_primaries;
227 
228  dst->color_trc = src->color_trc;
229  dst->colorspace = src->colorspace;
230  dst->color_range = src->color_range;
232 
233  dst->hwaccel = src->hwaccel;
234  dst->hwaccel_context = src->hwaccel_context;
235 
236  dst->channels = src->channels;
237  dst->sample_rate = src->sample_rate;
238  dst->sample_fmt = src->sample_fmt;
239  dst->channel_layout = src->channel_layout;
241  }
242 
243  if (for_user) {
244  dst->delay = src->thread_count - 1;
245  dst->coded_frame = src->coded_frame;
246  } else {
247  if (dst->codec->update_thread_context)
248  err = dst->codec->update_thread_context(dst, src);
249  }
250 
251  return err;
252 }
253 
254 /**
255  * Update the next thread's AVCodecContext with values set by the user.
256  *
257  * @param dst The destination context.
258  * @param src The source context.
259  * @return 0 on success, negative error code on failure
260  */
262 {
263 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
264  dst->flags = src->flags;
265 
266  dst->draw_horiz_band= src->draw_horiz_band;
267  dst->get_buffer2 = src->get_buffer2;
268 #if FF_API_GET_BUFFER
270  dst->get_buffer = src->get_buffer;
271  dst->release_buffer = src->release_buffer;
273 #endif
274 
275  dst->opaque = src->opaque;
276  dst->debug = src->debug;
277  dst->debug_mv = src->debug_mv;
278 
279  dst->slice_flags = src->slice_flags;
280  dst->flags2 = src->flags2;
281 
282  copy_fields(skip_loop_filter, subtitle_header);
283 
284  dst->frame_number = src->frame_number;
287 
288  if (src->slice_count && src->slice_offset) {
289  if (dst->slice_count < src->slice_count) {
290  int err = av_reallocp_array(&dst->slice_offset, src->slice_count,
291  sizeof(*dst->slice_offset));
292  if (err < 0)
293  return err;
294  }
295  memcpy(dst->slice_offset, src->slice_offset,
296  src->slice_count * sizeof(*dst->slice_offset));
297  }
298  dst->slice_count = src->slice_count;
299  return 0;
300 #undef copy_fields
301 }
302 
303 /// Releases the buffers that this decoding thread was the last user of.
305 {
306  FrameThreadContext *fctx = p->parent;
307 
308  while (p->num_released_buffers > 0) {
309  AVFrame *f;
310 
312 
313  // fix extended data in case the caller screwed it up
317  f->extended_data = f->data;
318  av_frame_unref(f);
319 
321  }
322 }
323 
325 {
326  FrameThreadContext *fctx = p->parent;
327  PerThreadContext *prev_thread = fctx->prev_thread;
328  const AVCodec *codec = p->avctx->codec;
329 
330  if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
331 
333 
335 
336  if (prev_thread) {
337  int err;
338  if (prev_thread->state == STATE_SETTING_UP) {
339  pthread_mutex_lock(&prev_thread->progress_mutex);
340  while (prev_thread->state == STATE_SETTING_UP)
341  pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
342  pthread_mutex_unlock(&prev_thread->progress_mutex);
343  }
344 
345  err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
346  if (err) {
348  return err;
349  }
350  }
351 
352  av_packet_unref(&p->avpkt);
353  av_packet_ref(&p->avpkt, avpkt);
354 
355  p->state = STATE_SETTING_UP;
358 
359  /*
360  * If the client doesn't have a thread-safe get_buffer(),
361  * then decoding threads call back to the main thread,
362  * and it calls back to the client here.
363  */
364 
366  if (!p->avctx->thread_safe_callbacks && (
369  p->avctx->get_buffer ||
370 #endif
373  while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
374  int call_done = 1;
376  while (p->state == STATE_SETTING_UP)
378 
379  switch (p->state) {
380  case STATE_GET_BUFFER:
382  break;
383  case STATE_GET_FORMAT:
385  break;
386  default:
387  call_done = 0;
388  break;
389  }
390  if (call_done) {
391  p->state = STATE_SETTING_UP;
393  }
395  }
396  }
397 
398  fctx->prev_thread = p;
399  fctx->next_decoding++;
400 
401  return 0;
402 }
403 
405  AVFrame *picture, int *got_picture_ptr,
406  AVPacket *avpkt)
407 {
408  FrameThreadContext *fctx = avctx->internal->thread_ctx;
409  int finished = fctx->next_finished;
410  PerThreadContext *p;
411  int err;
412 
413  /*
414  * Submit a packet to the next decoding thread.
415  */
416 
417  p = &fctx->threads[fctx->next_decoding];
418  err = update_context_from_user(p->avctx, avctx);
419  if (err) return err;
420  err = submit_packet(p, avpkt);
421  if (err) return err;
422 
423  /*
424  * If we're still receiving the initial packets, don't return a frame.
425  */
426 
427  if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
428  fctx->delaying = 0;
429 
430  if (fctx->delaying) {
431  *got_picture_ptr=0;
432  if (avpkt->size)
433  return avpkt->size;
434  }
435 
436  /*
437  * Return the next available frame from the oldest thread.
438  * If we're at the end of the stream, then we have to skip threads that
439  * didn't output a frame, because we don't want to accidentally signal
440  * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
441  */
442 
443  do {
444  p = &fctx->threads[finished++];
445 
446  if (p->state != STATE_INPUT_READY) {
448  while (p->state != STATE_INPUT_READY)
451  }
452 
453  av_frame_move_ref(picture, p->frame);
454  *got_picture_ptr = p->got_frame;
455  picture->pkt_dts = p->avpkt.dts;
456 
457  if (p->result < 0)
458  err = p->result;
459 
460  /*
461  * A later call with avkpt->size == 0 may loop over all threads,
462  * including this one, searching for a frame to return before being
463  * stopped by the "finished != fctx->next_finished" condition.
464  * Make sure we don't mistakenly return the same frame again.
465  */
466  p->got_frame = 0;
467 
468  if (finished >= avctx->thread_count) finished = 0;
469  } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
470 
471  update_context_from_thread(avctx, p->avctx, 1);
472 
473  if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
474 
475  fctx->next_finished = finished;
476 
477  /*
478  * When no frame was found while flushing, but an error occured in
479  * any thread, return it instead of 0.
480  * Otherwise the error can get lost.
481  */
482  if (!avpkt->size && !*got_picture_ptr)
483  return err;
484 
485  /* return the size of the consumed packet if no error occurred */
486  return (p->result >= 0) ? avpkt->size : p->result;
487 }
488 
489 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
490 {
491  PerThreadContext *p;
492  volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
493 
494  if (!progress || progress[field] >= n) return;
495 
496  p = f->owner->internal->thread_ctx;
497 
498  if (f->owner->debug&FF_DEBUG_THREADS)
499  av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
500 
502  progress[field] = n;
505 }
506 
507 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
508 {
509  PerThreadContext *p;
510  volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
511 
512  if (!progress || progress[field] >= n) return;
513 
514  p = f->owner->internal->thread_ctx;
515 
516  if (f->owner->debug&FF_DEBUG_THREADS)
517  av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
518 
520  while (progress[field] < n)
523 }
524 
526  PerThreadContext *p = avctx->internal->thread_ctx;
527 
528  if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
529 
530  if(p->state == STATE_SETUP_FINISHED){
531  av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
532  }
533 
535  p->state = STATE_SETUP_FINISHED;
538 }
539 
540 /// Waits for all threads to finish.
541 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
542 {
543  int i;
544 
545  for (i = 0; i < thread_count; i++) {
546  PerThreadContext *p = &fctx->threads[i];
547 
548  if (p->state != STATE_INPUT_READY) {
550  while (p->state != STATE_INPUT_READY)
553  }
554  p->got_frame = 0;
555  }
556 }
557 
558 void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
559 {
560  FrameThreadContext *fctx = avctx->internal->thread_ctx;
561  const AVCodec *codec = avctx->codec;
562  int i;
563 
564  park_frame_worker_threads(fctx, thread_count);
565 
566  if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
567  if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
568  av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
570  fctx->threads->avctx->internal->is_copy = 1;
571  }
572 
573  fctx->die = 1;
574 
575  for (i = 0; i < thread_count; i++) {
576  PerThreadContext *p = &fctx->threads[i];
577 
581 
582  if (p->thread_init)
583  pthread_join(p->thread, NULL);
584  p->thread_init=0;
585 
586  if (codec->close && p->avctx)
587  codec->close(p->avctx);
588 
590  av_frame_free(&p->frame);
591  }
592 
593  for (i = 0; i < thread_count; i++) {
594  PerThreadContext *p = &fctx->threads[i];
595 
601  av_packet_unref(&p->avpkt);
603 
604  if (i && p->avctx) {
605  av_freep(&p->avctx->priv_data);
607  }
608 
609  if (p->avctx)
610  av_freep(&p->avctx->internal);
611  av_freep(&p->avctx);
612  }
613 
614  av_freep(&fctx->threads);
616  av_freep(&avctx->internal->thread_ctx);
617 
618  if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
619  av_opt_free(avctx->priv_data);
620  avctx->codec = NULL;
621 }
622 
624 {
625  int thread_count = avctx->thread_count;
626  const AVCodec *codec = avctx->codec;
627  AVCodecContext *src = avctx;
628  FrameThreadContext *fctx;
629  int i, err = 0;
630 
631 #if HAVE_W32THREADS
632  w32thread_init();
633 #endif
634 
635  if (!thread_count) {
636  int nb_cpus = av_cpu_count();
637  if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
638  nb_cpus = 1;
639  // use number of cores + 1 as thread count if there is more than one
640  if (nb_cpus > 1)
641  thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
642  else
643  thread_count = avctx->thread_count = 1;
644  }
645 
646  if (thread_count <= 1) {
647  avctx->active_thread_type = 0;
648  return 0;
649  }
650 
651  avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
652  if (!fctx)
653  return AVERROR(ENOMEM);
654 
655  fctx->threads = av_mallocz_array(thread_count, sizeof(PerThreadContext));
656  if (!fctx->threads) {
657  av_freep(&avctx->internal->thread_ctx);
658  return AVERROR(ENOMEM);
659  }
660 
662  fctx->delaying = 1;
663 
664  for (i = 0; i < thread_count; i++) {
666  PerThreadContext *p = &fctx->threads[i];
667 
673 
674  p->frame = av_frame_alloc();
675  if (!p->frame) {
676  av_freep(&copy);
677  err = AVERROR(ENOMEM);
678  goto error;
679  }
680 
681  p->parent = fctx;
682  p->avctx = copy;
683 
684  if (!copy) {
685  err = AVERROR(ENOMEM);
686  goto error;
687  }
688 
689  *copy = *src;
690 
691  copy->internal = av_malloc(sizeof(AVCodecInternal));
692  if (!copy->internal) {
693  copy->priv_data = NULL;
694  err = AVERROR(ENOMEM);
695  goto error;
696  }
697  *copy->internal = *src->internal;
698  copy->internal->thread_ctx = p;
699  copy->internal->pkt = &p->avpkt;
700 
701  if (!i) {
702  src = copy;
703 
704  if (codec->init)
705  err = codec->init(copy);
706 
707  update_context_from_thread(avctx, copy, 1);
708  } else {
709  copy->priv_data = av_malloc(codec->priv_data_size);
710  if (!copy->priv_data) {
711  err = AVERROR(ENOMEM);
712  goto error;
713  }
714  memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
715  copy->internal->is_copy = 1;
716 
717  if (codec->init_thread_copy)
718  err = codec->init_thread_copy(copy);
719  }
720 
721  if (err) goto error;
722 
724  p->thread_init= !err;
725  if(!p->thread_init)
726  goto error;
727  }
728 
729  return 0;
730 
731 error:
732  ff_frame_thread_free(avctx, i+1);
733 
734  return err;
735 }
736 
738 {
739  int i;
740  FrameThreadContext *fctx = avctx->internal->thread_ctx;
741 
742  if (!fctx) return;
743 
745  if (fctx->prev_thread) {
746  if (fctx->prev_thread != &fctx->threads[0])
748  }
749 
750  fctx->next_decoding = fctx->next_finished = 0;
751  fctx->delaying = 1;
752  fctx->prev_thread = NULL;
753  for (i = 0; i < avctx->thread_count; i++) {
754  PerThreadContext *p = &fctx->threads[i];
755  // Make sure decode flush calls with size=0 won't return old frames
756  p->got_frame = 0;
757  av_frame_unref(p->frame);
758 
760 
761  if (avctx->codec->flush)
762  avctx->codec->flush(p->avctx);
763  }
764 }
765 
767 {
768  PerThreadContext *p = avctx->internal->thread_ctx;
769  if ((avctx->active_thread_type&FF_THREAD_FRAME) && p->state != STATE_SETTING_UP &&
770  (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
771  return 0;
772  }
773  return 1;
774 }
775 
777 {
778  PerThreadContext *p = avctx->internal->thread_ctx;
779  int err;
780 
781  f->owner = avctx;
782 
783  ff_init_buffer_info(avctx, f->f);
784 
785  if (!(avctx->active_thread_type & FF_THREAD_FRAME))
786  return ff_get_buffer(avctx, f->f, flags);
787 
788  if (p->state != STATE_SETTING_UP &&
789  (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
790  av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
791  return -1;
792  }
793 
794  if (avctx->internal->allocate_progress) {
795  int *progress;
796  f->progress = av_buffer_alloc(2 * sizeof(int));
797  if (!f->progress) {
798  return AVERROR(ENOMEM);
799  }
800  progress = (int*)f->progress->data;
801 
802  progress[0] = progress[1] = -1;
803  }
804 
807  if (avctx->thread_safe_callbacks || (
809  !avctx->get_buffer &&
810 #endif
813  err = ff_get_buffer(avctx, f->f, flags);
814  } else {
816  p->requested_frame = f->f;
817  p->requested_flags = flags;
818  p->state = STATE_GET_BUFFER;
820 
821  while (p->state != STATE_SETTING_UP)
823 
824  err = p->result;
825 
827 
828  }
829  if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
830  ff_thread_finish_setup(avctx);
831 
832  if (err)
834 
836 
837  return err;
838 }
839 
841 {
842  enum AVPixelFormat res;
843  PerThreadContext *p = avctx->internal->thread_ctx;
844  if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
846  return ff_get_format(avctx, fmt);
847  if (p->state != STATE_SETTING_UP) {
848  av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
849  return -1;
850  }
852  p->available_formats = fmt;
853  p->state = STATE_GET_FORMAT;
855 
856  while (p->state != STATE_SETTING_UP)
858 
859  res = p->result_format;
860 
862 
863  return res;
864 }
865 
867 {
868  int ret = thread_get_buffer_internal(avctx, f, flags);
869  if (ret < 0)
870  av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
871  return ret;
872 }
873 
875 {
876  PerThreadContext *p = avctx->internal->thread_ctx;
877  FrameThreadContext *fctx;
878  AVFrame *dst, *tmp;
880  int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
881  avctx->thread_safe_callbacks ||
882  (
884  !avctx->get_buffer &&
885 #endif
888 
889  if (!f->f || !f->f->buf[0])
890  return;
891 
892  if (avctx->debug & FF_DEBUG_BUFFERS)
893  av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
894 
896  f->owner = NULL;
897 
898  if (can_direct_free) {
899  av_frame_unref(f->f);
900  return;
901  }
902 
903  fctx = p->parent;
905 
906  if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
907  goto fail;
909  (p->num_released_buffers + 1) *
910  sizeof(*p->released_buffers));
911  if (!tmp)
912  goto fail;
913  p->released_buffers = tmp;
914 
916  av_frame_move_ref(dst, f->f);
917 
919 
920 fail:
922 }
static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
static av_unused void w32thread_init(void)
Definition: w32pthreads.h:299
pthread_cond_t progress_cond
Used by child threads to wait for progress to change.
Definition: pthread_frame.c:62
#define NULL
Definition: coverity.c:32
const struct AVCodec * codec
Definition: avcodec.h:1250
AVRational framerate
Definition: avcodec.h:3023
static av_always_inline int pthread_mutex_destroy(pthread_mutex_t *mutex)
Definition: os2threads.h:94
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:171
static av_always_inline int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
Definition: os2threads.h:153
#define FF_DEBUG_VIS_QP
only access through AVOptions from outside libavcodec
Definition: avcodec.h:2587
Context used by codec threads and stored in their AVCodecInternal thread_ctx.
Definition: pthread_frame.c:56
int av_cpu_count(void)
Definition: cpu.c:251
AVFrame * requested_frame
AVFrame the codec passed to get_buffer()
Definition: pthread_frame.c:98
int coded_width
Bitstream width / height, may be different from width/height e.g.
Definition: avcodec.h:1424
const char * fmt
Definition: avisynth_c.h:632
void(* flush)(AVCodecContext *)
Flush buffers.
Definition: avcodec.h:3272
#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:441
AVFrame * coded_frame
the picture in the bitstream
Definition: avcodec.h:2745
enum AVColorRange color_range
MPEG vs JPEG YUV range.
Definition: avcodec.h:1960
int size
Definition: avcodec.h:1163
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:1623
AVPacket * pkt
Current packet as passed into the decoder, to avoid having to pass the packet into every function...
Definition: internal.h:143
os2threads to pthreads wrapper
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:1444
void av_frame_move_ref(AVFrame *dst, AVFrame *src)
Move everything contained in src to dst and reset src.
Definition: frame.c:479
int(* decode)(AVCodecContext *, void *outdata, int *outdata_size, AVPacket *avpkt)
Definition: avcodec.h:3266
int bits_per_raw_sample
Bits per sample/pixel of internal libavcodec pixel/sample format.
Definition: avcodec.h:2727
#define FF_DEBUG_VIS_MB_TYPE
only access through AVOptions from outside libavcodec
Definition: avcodec.h:2588
pthread_cond_t input_cond
Used to wait for a new packet from the main thread.
Definition: pthread_frame.c:61
void ff_thread_await_progress(ThreadFrame *f, int n, int field)
Wait for earlier decoding threads to finish reference pictures.
attribute_deprecated int(* get_buffer)(struct AVCodecContext *c, AVFrame *pic)
Called at the beginning of each frame to get a buffer for it.
Definition: avcodec.h:2134
int profile
profile
Definition: avcodec.h:2835
enum AVPixelFormat * available_formats
Format array for get_format()
AVCodec.
Definition: avcodec.h:3181
static av_always_inline int pthread_cond_destroy(pthread_cond_t *cond)
Definition: os2threads.h:124
AVPacket avpkt
Input packet (for decoding) or output (for encoding).
Definition: pthread_frame.c:70
attribute_deprecated void(* release_buffer)(struct AVCodecContext *c, AVFrame *pic)
Called to release buffers which were allocated with get_buffer.
Definition: avcodec.h:2148
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avcodec.h:1369
struct AVHWAccel * hwaccel
Hardware accelerator in use.
Definition: avcodec.h:2644
#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:3230
Set when the thread is awaiting a packet.
Definition: pthread_frame.c:77
HMTX pthread_mutex_t
Definition: os2threads.h:40
enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
Definition: utils.c:1148
if()
Definition: avfilter.c:975
enum AVSampleFormat sample_fmt
audio sample format
Definition: avcodec.h:1993
#define av_malloc(s)
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition: frame.c:135
void * hwaccel_context
Hardware accelerator context.
Definition: avcodec.h:2656
#define FF_DEBUG_THREADS
Definition: avcodec.h:2591
AVOptions.
static attribute_align_arg void * frame_worker_thread(void *arg)
Codec worker thread.
void * thread_ctx
Definition: internal.h:137
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:99
int next_decoding
The next context to submit a packet to.
static av_always_inline int pthread_cond_signal(pthread_cond_t *cond)
Definition: os2threads.h:131
static void copy(LZOContext *c, int cnt)
Copies bytes from input to output buffer with checking.
Definition: lzo.c:85
int bits_per_coded_sample
bits per sample/pixel from the demuxer (needed for huffyuv).
Definition: avcodec.h:2720
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:1967
Context stored in the client AVCodecInternal thread_ctx.
AVCodecContext * avctx
Context used to decode packets passed to this thread.
Definition: pthread_frame.c:68
#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:559
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:1598
Libavcodec version macros.
int(* close)(AVCodecContext *)
Definition: avcodec.h:3267
int av_reallocp_array(void *ptr, size_t nmemb, size_t size)
Definition: mem.c:213
#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:1533
PerThreadContext * prev_thread
The last thread submit_packet() was called on.
void * av_fast_realloc(void *ptr, unsigned int *size, size_t min_size)
Reallocate the given block if it is not large enough, otherwise do nothing.
Definition: mem.c:478
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 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:824
int is_copy
Whether the parent AVCodecContext is a copy of the context which had init() called on it...
Definition: internal.h:102
#define AVERROR(e)
Definition: error.h:43
Set before the codec has called ff_thread_finish_setup().
Definition: pthread_frame.c:78
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:148
int active_thread_type
Which multithreading methods are in use by the codec.
Definition: avcodec.h:2772
int capabilities
Codec capabilities.
Definition: avcodec.h:3200
int result
The result of the last codec decode/encode() call.
Definition: pthread_frame.c:74
#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
CODEC_FLAG_*.
Definition: avcodec.h:1335
simple assert() macros that are a bit more flexible than ISO C assert().
enum PerThreadContext::@78 state
int die
Set when threads should exit.
Libavcodec external API header.
reference-counted frame API
uint64_t channel_layout
Audio channel layout.
Definition: avcodec.h:2046
common internal API header
pthread_cond_t output_cond
Used by the main thread to wait for frames to finish.
Definition: pthread_frame.c:63
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:1478
#define FF_API_GET_BUFFER
Definition: version.h:82
#define FFMIN(a, b)
Definition: common.h:66
ret
Definition: avfilter.c:974
int width
picture width / height.
Definition: avcodec.h:1414
Set after the codec has called ff_thread_finish_setup().
Definition: pthread_frame.c:87
int idct_algo
IDCT algorithm, see FF_IDCT_* below.
Definition: avcodec.h:2685
int priv_data_size
Definition: avcodec.h:3219
void ff_thread_report_progress(ThreadFrame *f, int n, int field)
Notify later decoding threads when part of their reference picture is ready.
#define FF_DEBUG_BUFFERS
Definition: avcodec.h:2590
enum AVColorPrimaries color_primaries
Chromaticity coordinates of the source primaries.
Definition: avcodec.h:1939
static av_always_inline int pthread_join(pthread_t thread, void **value_ptr)
Definition: os2threads.h:80
static av_always_inline int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
Definition: os2threads.h:87
int level
level
Definition: avcodec.h:2925
int64_t reordered_opaque
opaque 64bit number (generally a PTS) that will be reordered and output in AVFrame.reordered_opaque
Definition: avcodec.h:2637
int n
Definition: avisynth_c.h:547
int ticks_per_frame
For some codecs, the time base is closer to the field rate than the frame rate.
Definition: avcodec.h:1378
pthread_t thread
Definition: pthread_frame.c:59
int thread_count
thread count is used to decide how many independent tasks should be passed to execute() ...
Definition: avcodec.h:2753
Set when the codec calls get_format().
Definition: pthread_frame.c:83
int got_frame
The output of got_picture_ptr from the last avcodec_decode_video() call.
Definition: pthread_frame.c:73
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:1200
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:66
#define attribute_align_arg
Definition: internal.h:57
static av_always_inline int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
Definition: os2threads.h:64
AVS_Value src
Definition: avisynth_c.h:482
int avcodec_default_get_buffer2(AVCodecContext *s, AVFrame *frame, int flags)
The default callback for AVCodecContext.get_buffer2().
Definition: utils.c:721
enum AVMediaType codec_type
Definition: avcodec.h:1249
enum AVCodecID codec_id
Definition: avcodec.h:1258
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:1985
int debug
debug
Definition: avcodec.h:2565
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:1241
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:550
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:1037
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:744
#define FF_THREAD_FRAME
Decode more than one frame at once.
Definition: avcodec.h:2764
int slice_flags
slice flags
Definition: avcodec.h:1757
int coded_height
Definition: avcodec.h:1424
enum AVPixelFormat(* get_format)(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
callback to negotiate the pixelFormat
Definition: avcodec.h:1495
enum AVColorSpace colorspace
YUV colorspace type.
Definition: avcodec.h:1953
enum AVColorTransferCharacteristic color_trc
Color Transfer Characteristic.
Definition: avcodec.h:1946
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:2246
attribute_deprecated int dtg_active_format
DTG active format information (additional aspect ratio information only used in DVB MPEG-2 transport ...
Definition: avcodec.h:1718
PerThreadContext * threads
The contexts for each thread.
int allocate_progress
Whether to allocate progress for frame threading.
Definition: internal.h:117
#define MAX_AUTO_THREADS
AVFrame * released_buffers
Array of frames passed to ff_thread_release_buffer().
Definition: pthread_frame.c:94
struct FrameThreadContext * parent
Definition: pthread_frame.c:57
void av_frame_unref(AVFrame *frame)
Unreference all the buffers referenced by frame and reset the frame fields.
Definition: frame.c:462
static int flags
Definition: cpu.c:47
const AVClass * priv_class
AVClass for the private context.
Definition: avcodec.h:3209
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:182
int64_t pkt_dts
DTS copied from the AVPacket that triggered returning this frame.
Definition: frame.h:269
void av_opt_free(void *obj)
Free all allocated objects in obj.
Definition: opt.c:1435
#define FF_DISABLE_DEPRECATION_WARNINGS
Definition: internal.h:79
common internal api header.
common internal and external API header
int released_buffers_allocated
Definition: pthread_frame.c:96
void * hwaccel_priv_data
hwaccel-specific private data
Definition: internal.h:161
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:115
int thread_safe_callbacks
Set by the client if its custom get_buffer() callback can be called synchronously from another thread...
Definition: avcodec.h:2782
void * priv_data
Definition: avcodec.h:1283
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:3238
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:72
int ff_thread_can_start_frame(AVCodecContext *avctx)
#define FF_ENABLE_DEPRECATION_WARNINGS
Definition: internal.h:80
static av_always_inline int pthread_cond_broadcast(pthread_cond_t *cond)
Definition: os2threads.h:142
int channels
number of audio channels
Definition: avcodec.h:1986
static av_always_inline int pthread_mutex_unlock(pthread_mutex_t *mutex)
Definition: os2threads.h:108
struct AVCodecInternal * internal
Private context used for internal data.
Definition: avcodec.h:1291
pthread_mutex_t mutex
Mutex used to protect the contents of the PerThreadContext.
Definition: pthread_frame.c:65
w32threads to pthreads wrapper
int flags2
CODEC_FLAG2_*.
Definition: avcodec.h:1342
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:1161
static void * av_mallocz_array(size_t nmemb, size_t size)
Definition: mem.h:228
int * slice_offset
slice offsets in the frame in bytes
Definition: avcodec.h:1614
int frame_number
Frame counter, set by libavcodec.
Definition: avcodec.h:2016
static void release_delayed_buffers(PerThreadContext *p)
Releases the buffers that this decoding thread was the last user of.
#define av_freep(p)
static av_always_inline int pthread_mutex_lock(pthread_mutex_t *mutex)
Definition: os2threads.h:101
int debug_mv
debug Code outside libavcodec should access this field using AVOptions
Definition: avcodec.h:2601
int next_finished
The next context to return output from.
int(* init)(AVCodecContext *)
Definition: avcodec.h:3251
uint8_t ** extended_data
pointers to the data planes/channels.
Definition: frame.h:215
AVPixelFormat
Pixel format.
Definition: pixfmt.h:61
This structure stores compressed data.
Definition: avcodec.h:1139
Set when the codec calls get_buffer().
Definition: pthread_frame.c:79
int delay
Codec delay.
Definition: avcodec.h:1402
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:250
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:1298