codec: feed empty cc blocks when reordering
[vlc.git] / modules / codec / avcodec / video.c
blobe24319169e118cede814a9bc3e8aeea9cbbcea75
1 /*****************************************************************************
2 * video.c: video decoder using the libavcodec library
3 *****************************************************************************
4 * Copyright (C) 1999-2001 VLC authors and VideoLAN
5 * $Id$
7 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8 * Gildas Bazin <gbazin@videolan.org>
10 * This program is free software; you can redistribute it and/or modify it
11 * under the terms of the GNU Lesser General Public License as published by
12 * the Free Software Foundation; either version 2.1 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with this program; if not, write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23 *****************************************************************************/
25 /*****************************************************************************
26 * Preamble
27 *****************************************************************************/
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
32 #include <vlc_common.h>
33 #include <vlc_codec.h>
34 #include <vlc_avcodec.h>
35 #include <vlc_cpu.h>
36 #include <vlc_atomic.h>
37 #include <assert.h>
39 #include <libavcodec/avcodec.h>
40 #include <libavutil/mem.h>
41 #include <libavutil/pixdesc.h>
42 #if (LIBAVUTIL_VERSION_MICRO >= 100 && LIBAVUTIL_VERSION_INT >= AV_VERSION_INT( 55, 16, 101 ) )
43 #include <libavutil/mastering_display_metadata.h>
44 #endif
46 #include "avcodec.h"
47 #include "va.h"
49 #include "../codec/cc.h"
51 /*****************************************************************************
52 * decoder_sys_t : decoder descriptor
53 *****************************************************************************/
54 struct decoder_sys_t
56 AVCodecContext *p_context;
57 const AVCodec *p_codec;
59 /* Video decoder specific part */
60 date_t pts;
62 /* Closed captions for decoders */
63 cc_data_t cc;
65 /* for frame skipping algo */
66 bool b_hurry_up;
67 bool b_show_corrupted;
68 bool b_from_preroll;
69 enum AVDiscard i_skip_frame;
71 /* how many decoded frames are late */
72 int i_late_frames;
73 mtime_t i_late_frames_start;
74 mtime_t i_last_late_delay;
76 /* for direct rendering */
77 bool b_direct_rendering;
78 atomic_bool b_dr_failure;
80 /* Hack to force display of still pictures */
81 bool b_first_frame;
84 /* */
85 bool palette_sent;
87 /* VA API */
88 vlc_va_t *p_va;
89 enum PixelFormat pix_fmt;
90 int profile;
91 int level;
93 vlc_sem_t sem_mt;
96 static inline void wait_mt(decoder_sys_t *sys)
98 vlc_sem_wait(&sys->sem_mt);
101 static inline void post_mt(decoder_sys_t *sys)
103 vlc_sem_post(&sys->sem_mt);
106 /*****************************************************************************
107 * Local prototypes
108 *****************************************************************************/
109 static void ffmpeg_InitCodec ( decoder_t * );
110 static int lavc_GetFrame(struct AVCodecContext *, AVFrame *, int);
111 static enum PixelFormat ffmpeg_GetFormat( AVCodecContext *,
112 const enum PixelFormat * );
113 static int DecodeVideo( decoder_t *, block_t * );
114 static void Flush( decoder_t * );
116 static uint32_t ffmpeg_CodecTag( vlc_fourcc_t fcc )
118 uint8_t *p = (uint8_t*)&fcc;
119 return p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
122 /*****************************************************************************
123 * Local Functions
124 *****************************************************************************/
127 * Sets the decoder output format.
129 static int lavc_GetVideoFormat(decoder_t *dec, video_format_t *restrict fmt,
130 AVCodecContext *ctx, enum AVPixelFormat pix_fmt,
131 enum AVPixelFormat sw_pix_fmt)
133 int width = ctx->coded_width;
134 int height = ctx->coded_height;
136 video_format_Init(fmt, 0);
138 if (pix_fmt == sw_pix_fmt)
139 { /* software decoding */
140 int aligns[AV_NUM_DATA_POINTERS];
142 if (GetVlcChroma(fmt, pix_fmt))
143 return -1;
145 /* The libavcodec palette can only be fetched when the first output
146 * frame is decoded. Assume that the current chroma is RGB32 while we
147 * are waiting for a valid palette. Indeed, fmt_out.video.p_palette
148 * doesn't trigger a new vout request, but a new chroma yes. */
149 if (pix_fmt == AV_PIX_FMT_PAL8 && !dec->fmt_out.video.p_palette)
150 fmt->i_chroma = VLC_CODEC_RGB32;
152 avcodec_align_dimensions2(ctx, &width, &height, aligns);
154 else /* hardware decoding */
155 fmt->i_chroma = vlc_va_GetChroma(pix_fmt, sw_pix_fmt);
157 if( width == 0 || height == 0 || width > 8192 || height > 8192 ||
158 width < ctx->width || height < ctx->height )
160 msg_Err(dec, "Invalid frame size %dx%d vsz %dx%d",
161 width, height, ctx->width, ctx->height );
162 return -1; /* invalid display size */
165 fmt->i_width = width;
166 fmt->i_height = height;
167 fmt->i_visible_width = ctx->width;
168 fmt->i_visible_height = ctx->height;
170 /* If an aspect-ratio was specified in the input format then force it */
171 if (dec->fmt_in.video.i_sar_num > 0 && dec->fmt_in.video.i_sar_den > 0)
173 fmt->i_sar_num = dec->fmt_in.video.i_sar_num;
174 fmt->i_sar_den = dec->fmt_in.video.i_sar_den;
176 else
178 fmt->i_sar_num = ctx->sample_aspect_ratio.num;
179 fmt->i_sar_den = ctx->sample_aspect_ratio.den;
181 if (fmt->i_sar_num == 0 || fmt->i_sar_den == 0)
182 fmt->i_sar_num = fmt->i_sar_den = 1;
185 if (dec->fmt_in.video.i_frame_rate > 0
186 && dec->fmt_in.video.i_frame_rate_base > 0)
188 fmt->i_frame_rate = dec->fmt_in.video.i_frame_rate;
189 fmt->i_frame_rate_base = dec->fmt_in.video.i_frame_rate_base;
191 else if (ctx->framerate.num > 0 && ctx->framerate.den > 0)
193 fmt->i_frame_rate = ctx->framerate.num;
194 fmt->i_frame_rate_base = ctx->framerate.den;
195 # if LIBAVCODEC_VERSION_MICRO < 100
196 // for some reason libav don't thinkg framerate presents actually same thing as in ffmpeg
197 fmt->i_frame_rate_base *= __MAX(ctx->ticks_per_frame, 1);
198 # endif
200 else if (ctx->time_base.num > 0 && ctx->time_base.den > 0)
202 fmt->i_frame_rate = ctx->time_base.den;
203 fmt->i_frame_rate_base = ctx->time_base.num
204 * __MAX(ctx->ticks_per_frame, 1);
207 if( ctx->color_range == AVCOL_RANGE_JPEG )
208 fmt->b_color_range_full = true;
210 switch( ctx->colorspace )
212 case AVCOL_SPC_BT709:
213 fmt->space = COLOR_SPACE_BT709;
214 break;
215 case AVCOL_SPC_SMPTE170M:
216 case AVCOL_SPC_BT470BG:
217 fmt->space = COLOR_SPACE_BT601;
218 break;
219 case AVCOL_SPC_BT2020_NCL:
220 case AVCOL_SPC_BT2020_CL:
221 fmt->space = COLOR_SPACE_BT2020;
222 break;
223 default:
224 break;
227 switch( ctx->color_trc )
229 case AVCOL_TRC_LINEAR:
230 fmt->transfer = TRANSFER_FUNC_LINEAR;
231 break;
232 case AVCOL_TRC_GAMMA22:
233 fmt->transfer = TRANSFER_FUNC_SRGB;
234 break;
235 case AVCOL_TRC_BT709:
236 fmt->transfer = TRANSFER_FUNC_BT709;
237 break;
238 case AVCOL_TRC_SMPTE170M:
239 case AVCOL_TRC_BT2020_10:
240 case AVCOL_TRC_BT2020_12:
241 fmt->transfer = TRANSFER_FUNC_BT2020;
242 break;
243 #if LIBAVUTIL_VERSION_CHECK( 55, 14, 0, 31, 100)
244 case AVCOL_TRC_ARIB_STD_B67:
245 fmt->transfer = TRANSFER_FUNC_ARIB_B67;
246 break;
247 #endif
248 #if LIBAVUTIL_VERSION_CHECK( 55, 17, 0, 37, 100)
249 case AVCOL_TRC_SMPTE2084:
250 fmt->transfer = TRANSFER_FUNC_SMPTE_ST2084;
251 break;
252 case AVCOL_TRC_SMPTE240M:
253 fmt->transfer = TRANSFER_FUNC_SMPTE_240;
254 break;
255 case AVCOL_TRC_GAMMA28:
256 fmt->transfer = TRANSFER_FUNC_BT470_BG;
257 break;
258 #endif
259 default:
260 break;
263 switch( ctx->color_primaries )
265 case AVCOL_PRI_BT709:
266 fmt->primaries = COLOR_PRIMARIES_BT709;
267 break;
268 case AVCOL_PRI_BT470BG:
269 fmt->primaries = COLOR_PRIMARIES_BT601_625;
270 break;
271 case AVCOL_PRI_SMPTE170M:
272 case AVCOL_PRI_SMPTE240M:
273 fmt->primaries = COLOR_PRIMARIES_BT601_525;
274 break;
275 case AVCOL_PRI_BT2020:
276 fmt->primaries = COLOR_PRIMARIES_BT2020;
277 break;
278 default:
279 break;
282 switch( ctx->chroma_sample_location )
284 case AVCHROMA_LOC_LEFT:
285 fmt->chroma_location = CHROMA_LOCATION_LEFT;
286 break;
287 case AVCHROMA_LOC_CENTER:
288 fmt->chroma_location = CHROMA_LOCATION_CENTER;
289 break;
290 case AVCHROMA_LOC_TOPLEFT:
291 fmt->chroma_location = CHROMA_LOCATION_TOP_LEFT;
292 break;
293 default:
294 break;
297 return 0;
300 static int lavc_UpdateVideoFormat(decoder_t *dec, AVCodecContext *ctx,
301 enum AVPixelFormat fmt,
302 enum AVPixelFormat swfmt)
304 video_format_t fmt_out;
305 int val;
307 val = lavc_GetVideoFormat(dec, &fmt_out, ctx, fmt, swfmt);
308 if (val)
309 return val;
311 /* always have date in fields/ticks units */
312 if(dec->p_sys->pts.i_divider_num)
313 date_Change(&dec->p_sys->pts, fmt_out.i_frame_rate *
314 __MAX(ctx->ticks_per_frame, 1),
315 fmt_out.i_frame_rate_base);
316 else
317 date_Init(&dec->p_sys->pts, fmt_out.i_frame_rate *
318 __MAX(ctx->ticks_per_frame, 1),
319 fmt_out.i_frame_rate_base);
321 fmt_out.p_palette = dec->fmt_out.video.p_palette;
322 dec->fmt_out.video.p_palette = NULL;
324 es_format_Change(&dec->fmt_out, VIDEO_ES, fmt_out.i_chroma);
325 dec->fmt_out.video = fmt_out;
326 dec->fmt_out.video.orientation = dec->fmt_in.video.orientation;
327 dec->fmt_out.video.projection_mode = dec->fmt_in.video.projection_mode;
328 dec->fmt_out.video.multiview_mode = dec->fmt_in.video.multiview_mode;
329 dec->fmt_out.video.pose = dec->fmt_in.video.pose;
330 if ( dec->fmt_in.video.mastering.max_luminance )
331 dec->fmt_out.video.mastering = dec->fmt_in.video.mastering;
332 dec->fmt_out.video.lighting = dec->fmt_in.video.lighting;
334 return decoder_UpdateVideoFormat(dec);
338 * Copies a picture from the libavcodec-allocate buffer to a picture_t.
339 * This is used when not in direct rendering mode.
341 static int lavc_CopyPicture(decoder_t *dec, picture_t *pic, AVFrame *frame)
343 decoder_sys_t *sys = dec->p_sys;
345 vlc_fourcc_t fourcc = FindVlcChroma(frame->format);
346 if (!fourcc)
348 const char *name = av_get_pix_fmt_name(frame->format);
350 msg_Err(dec, "Unsupported decoded output format %d (%s)",
351 sys->p_context->pix_fmt, (name != NULL) ? name : "unknown");
352 return VLC_EGENERIC;
353 } else if (fourcc != pic->format.i_chroma
354 || frame->width != (int) pic->format.i_visible_width
355 || frame->height != (int) pic->format.i_visible_height)
357 msg_Warn(dec, "dropping frame because the vout changed");
358 return VLC_EGENERIC;
361 for (int plane = 0; plane < pic->i_planes; plane++)
363 const uint8_t *src = frame->data[plane];
364 uint8_t *dst = pic->p[plane].p_pixels;
365 size_t src_stride = frame->linesize[plane];
366 size_t dst_stride = pic->p[plane].i_pitch;
367 size_t size = __MIN(src_stride, dst_stride);
369 for (int line = 0; line < pic->p[plane].i_visible_lines; line++)
371 memcpy(dst, src, size);
372 src += src_stride;
373 dst += dst_stride;
376 return VLC_SUCCESS;
379 static int OpenVideoCodec( decoder_t *p_dec )
381 decoder_sys_t *p_sys = p_dec->p_sys;
382 AVCodecContext *ctx = p_sys->p_context;
383 const AVCodec *codec = p_sys->p_codec;
384 int ret;
386 if( ctx->extradata_size <= 0 )
388 if( codec->id == AV_CODEC_ID_VC1 ||
389 codec->id == AV_CODEC_ID_THEORA )
391 msg_Warn( p_dec, "waiting for extra data for codec %s",
392 codec->name );
393 return 1;
397 ctx->width = p_dec->fmt_in.video.i_visible_width;
398 ctx->height = p_dec->fmt_in.video.i_visible_height;
400 ctx->coded_width = p_dec->fmt_in.video.i_width;
401 ctx->coded_height = p_dec->fmt_in.video.i_height;
403 ctx->bits_per_coded_sample = p_dec->fmt_in.video.i_bits_per_pixel;
404 p_sys->pix_fmt = AV_PIX_FMT_NONE;
405 p_sys->profile = -1;
406 p_sys->level = -1;
407 cc_Init( &p_sys->cc );
409 set_video_color_settings( &p_dec->fmt_in.video, ctx );
411 post_mt( p_sys );
412 ret = ffmpeg_OpenCodec( p_dec, ctx, codec );
413 wait_mt( p_sys );
414 if( ret < 0 )
415 return ret;
417 switch( ctx->active_thread_type )
419 case FF_THREAD_FRAME:
420 msg_Dbg( p_dec, "using frame thread mode with %d threads",
421 ctx->thread_count );
422 break;
423 case FF_THREAD_SLICE:
424 msg_Dbg( p_dec, "using slice thread mode with %d threads",
425 ctx->thread_count );
426 break;
427 case 0:
428 if( ctx->thread_count > 1 )
429 msg_Warn( p_dec, "failed to enable threaded decoding" );
430 break;
431 default:
432 msg_Warn( p_dec, "using unknown thread mode with %d threads",
433 ctx->thread_count );
434 break;
436 return 0;
439 /*****************************************************************************
440 * InitVideo: initialize the video decoder
441 *****************************************************************************
442 * the ffmpeg codec will be opened, some memory allocated. The vout is not yet
443 * opened (done after the first decoded frame).
444 *****************************************************************************/
445 int InitVideoDec( vlc_object_t *obj )
447 decoder_t *p_dec = (decoder_t *)obj;
448 const AVCodec *p_codec;
449 AVCodecContext *p_context = ffmpeg_AllocContext( p_dec, &p_codec );
450 if( p_context == NULL )
451 return VLC_EGENERIC;
453 int i_val;
455 /* Allocate the memory needed to store the decoder's structure */
456 decoder_sys_t *p_sys = calloc( 1, sizeof(*p_sys) );
457 if( unlikely(p_sys == NULL) )
459 avcodec_free_context( &p_context );
460 return VLC_ENOMEM;
463 p_dec->p_sys = p_sys;
464 p_sys->p_context = p_context;
465 p_sys->p_codec = p_codec;
466 p_sys->p_va = NULL;
467 vlc_sem_init( &p_sys->sem_mt, 0 );
469 /* ***** Fill p_context with init values ***** */
470 p_context->codec_tag = ffmpeg_CodecTag( p_dec->fmt_in.i_original_fourcc ?
471 p_dec->fmt_in.i_original_fourcc : p_dec->fmt_in.i_codec );
473 /* ***** Get configuration of ffmpeg plugin ***** */
474 p_context->workaround_bugs =
475 var_InheritInteger( p_dec, "avcodec-workaround-bugs" );
476 p_context->err_recognition =
477 var_InheritInteger( p_dec, "avcodec-error-resilience" );
479 if( var_CreateGetBool( p_dec, "grayscale" ) )
480 p_context->flags |= AV_CODEC_FLAG_GRAY;
482 /* ***** Output always the frames ***** */
483 p_context->flags |= AV_CODEC_FLAG_OUTPUT_CORRUPT;
485 i_val = var_CreateGetInteger( p_dec, "avcodec-skiploopfilter" );
486 if( i_val >= 4 ) p_context->skip_loop_filter = AVDISCARD_ALL;
487 else if( i_val == 3 ) p_context->skip_loop_filter = AVDISCARD_NONKEY;
488 else if( i_val == 2 ) p_context->skip_loop_filter = AVDISCARD_BIDIR;
489 else if( i_val == 1 ) p_context->skip_loop_filter = AVDISCARD_NONREF;
490 else p_context->skip_loop_filter = AVDISCARD_DEFAULT;
492 if( var_CreateGetBool( p_dec, "avcodec-fast" ) )
493 p_context->flags2 |= AV_CODEC_FLAG2_FAST;
495 /* ***** libavcodec frame skipping ***** */
496 p_sys->b_hurry_up = var_CreateGetBool( p_dec, "avcodec-hurry-up" );
497 p_sys->b_show_corrupted = var_CreateGetBool( p_dec, "avcodec-corrupted" );
499 i_val = var_CreateGetInteger( p_dec, "avcodec-skip-frame" );
500 if( i_val >= 4 ) p_context->skip_frame = AVDISCARD_ALL;
501 else if( i_val == 3 ) p_context->skip_frame = AVDISCARD_NONKEY;
502 else if( i_val == 2 ) p_context->skip_frame = AVDISCARD_BIDIR;
503 else if( i_val == 1 ) p_context->skip_frame = AVDISCARD_NONREF;
504 else if( i_val == -1 ) p_context->skip_frame = AVDISCARD_NONE;
505 else p_context->skip_frame = AVDISCARD_DEFAULT;
506 p_sys->i_skip_frame = p_context->skip_frame;
508 i_val = var_CreateGetInteger( p_dec, "avcodec-skip-idct" );
509 if( i_val >= 4 ) p_context->skip_idct = AVDISCARD_ALL;
510 else if( i_val == 3 ) p_context->skip_idct = AVDISCARD_NONKEY;
511 else if( i_val == 2 ) p_context->skip_idct = AVDISCARD_BIDIR;
512 else if( i_val == 1 ) p_context->skip_idct = AVDISCARD_NONREF;
513 else if( i_val == -1 ) p_context->skip_idct = AVDISCARD_NONE;
514 else p_context->skip_idct = AVDISCARD_DEFAULT;
516 /* ***** libavcodec direct rendering ***** */
517 p_sys->b_direct_rendering = false;
518 atomic_init(&p_sys->b_dr_failure, false);
519 if( var_CreateGetBool( p_dec, "avcodec-dr" ) &&
520 (p_codec->capabilities & AV_CODEC_CAP_DR1) &&
521 /* No idea why ... but this fixes flickering on some TSCC streams */
522 p_sys->p_codec->id != AV_CODEC_ID_TSCC &&
523 p_sys->p_codec->id != AV_CODEC_ID_CSCD &&
524 p_sys->p_codec->id != AV_CODEC_ID_CINEPAK )
526 /* Some codecs set pix_fmt only after the 1st frame has been decoded,
527 * so we need to do another check in ffmpeg_GetFrameBuf() */
528 p_sys->b_direct_rendering = true;
531 p_context->get_format = ffmpeg_GetFormat;
532 /* Always use our get_buffer wrapper so we can calculate the
533 * PTS correctly */
534 p_context->get_buffer2 = lavc_GetFrame;
535 p_context->refcounted_frames = true;
536 p_context->opaque = p_dec;
538 int i_thread_count = var_InheritInteger( p_dec, "avcodec-threads" );
539 if( i_thread_count <= 0 )
541 i_thread_count = vlc_GetCPUCount();
542 if( i_thread_count > 1 )
543 i_thread_count++;
545 //FIXME: take in count the decoding time
546 i_thread_count = __MIN( i_thread_count, p_codec->id == AV_CODEC_ID_HEVC ? 6 : 4 );
548 i_thread_count = __MIN( i_thread_count, 16 );
549 msg_Dbg( p_dec, "allowing %d thread(s) for decoding", i_thread_count );
550 p_context->thread_count = i_thread_count;
551 p_context->thread_safe_callbacks = true;
553 switch( p_codec->id )
555 case AV_CODEC_ID_MPEG4:
556 case AV_CODEC_ID_H263:
557 p_context->thread_type = 0;
558 break;
559 case AV_CODEC_ID_MPEG1VIDEO:
560 case AV_CODEC_ID_MPEG2VIDEO:
561 p_context->thread_type &= ~FF_THREAD_SLICE;
562 /* fall through */
563 # if (LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55, 1, 0))
564 case AV_CODEC_ID_H264:
565 case AV_CODEC_ID_VC1:
566 case AV_CODEC_ID_WMV3:
567 p_context->thread_type &= ~FF_THREAD_FRAME;
568 # endif
569 default:
570 break;
573 if( p_context->thread_type & FF_THREAD_FRAME )
574 p_dec->i_extra_picture_buffers = 2 * p_context->thread_count;
576 /* ***** misc init ***** */
577 date_Init(&p_sys->pts, 1, 30001);
578 date_Set(&p_sys->pts, VLC_TS_INVALID);
579 p_sys->b_first_frame = true;
580 p_sys->i_late_frames = 0;
581 p_sys->b_from_preroll = false;
583 /* Set output properties */
584 if( GetVlcChroma( &p_dec->fmt_out.video, p_context->pix_fmt ) != VLC_SUCCESS )
586 /* we are doomed. but not really, because most codecs set their pix_fmt later on */
587 p_dec->fmt_out.i_codec = VLC_CODEC_I420;
589 p_dec->fmt_out.i_codec = p_dec->fmt_out.video.i_chroma;
591 p_dec->fmt_out.video.orientation = p_dec->fmt_in.video.orientation;
593 if( p_dec->fmt_in.video.p_palette ) {
594 p_sys->palette_sent = false;
595 p_dec->fmt_out.video.p_palette = malloc( sizeof(video_palette_t) );
596 if( p_dec->fmt_out.video.p_palette )
597 *p_dec->fmt_out.video.p_palette = *p_dec->fmt_in.video.p_palette;
598 } else
599 p_sys->palette_sent = true;
601 /* ***** init this codec with special data ***** */
602 ffmpeg_InitCodec( p_dec );
604 /* ***** Open the codec ***** */
605 if( OpenVideoCodec( p_dec ) < 0 )
607 vlc_sem_destroy( &p_sys->sem_mt );
608 free( p_sys );
609 avcodec_free_context( &p_context );
610 return VLC_EGENERIC;
613 p_dec->pf_decode = DecodeVideo;
614 p_dec->pf_flush = Flush;
616 /* XXX: Writing input format makes little sense. */
617 if( p_context->profile != FF_PROFILE_UNKNOWN )
618 p_dec->fmt_in.i_profile = p_context->profile;
619 if( p_context->level != FF_LEVEL_UNKNOWN )
620 p_dec->fmt_in.i_level = p_context->level;
621 return VLC_SUCCESS;
624 /*****************************************************************************
625 * Flush:
626 *****************************************************************************/
627 static void Flush( decoder_t *p_dec )
629 decoder_sys_t *p_sys = p_dec->p_sys;
630 AVCodecContext *p_context = p_sys->p_context;
632 date_Set(&p_sys->pts, VLC_TS_INVALID); /* To make sure we recover properly */
633 p_sys->i_late_frames = 0;
634 cc_Flush( &p_sys->cc );
636 /* Abort pictures in order to unblock all avcodec workers threads waiting
637 * for a picture. This will avoid a deadlock between avcodec_flush_buffers
638 * and workers threads */
639 decoder_AbortPictures( p_dec, true );
641 post_mt( p_sys );
642 /* do not flush buffers if codec hasn't been opened (theora/vorbis/VC1) */
643 if( avcodec_is_open( p_context ) )
644 avcodec_flush_buffers( p_context );
645 wait_mt( p_sys );
647 /* Reset cancel state to false */
648 decoder_AbortPictures( p_dec, false );
651 static bool check_block_validity( decoder_sys_t *p_sys, block_t *block )
653 if( !block)
654 return true;
656 if( block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
658 date_Set( &p_sys->pts, VLC_TS_INVALID ); /* To make sure we recover properly */
659 cc_Flush( &p_sys->cc );
661 p_sys->i_late_frames = 0;
662 if( block->i_flags & BLOCK_FLAG_CORRUPTED )
664 block_Release( block );
665 return false;
668 return true;
671 static bool check_block_being_late( decoder_sys_t *p_sys, block_t *block, mtime_t current_time)
673 if( !block )
674 return false;
675 if( block->i_flags & BLOCK_FLAG_PREROLL )
677 /* Do not care about late frames when prerolling
678 * TODO avoid decoding of non reference frame
679 * (ie all B except for H264 where it depends only on nal_ref_idc) */
680 p_sys->i_late_frames = 0;
681 p_sys->b_from_preroll = true;
682 p_sys->i_last_late_delay = INT64_MAX;
685 if( p_sys->i_late_frames <= 0 )
686 return false;
688 if( current_time - p_sys->i_late_frames_start > (5*CLOCK_FREQ))
690 date_Set( &p_sys->pts, VLC_TS_INVALID ); /* To make sure we recover properly */
691 block_Release( block );
692 p_sys->i_late_frames--;
693 return true;
695 return false;
698 static bool check_frame_should_be_dropped( decoder_sys_t *p_sys, AVCodecContext *p_context, bool *b_need_output_picture )
700 if( p_sys->i_late_frames <= 4)
701 return false;
703 *b_need_output_picture = false;
704 if( p_sys->i_late_frames < 12 )
706 p_context->skip_frame =
707 (p_sys->i_skip_frame <= AVDISCARD_NONREF) ?
708 AVDISCARD_NONREF : p_sys->i_skip_frame;
710 else
712 /* picture too late, won't decode
713 * but break picture until a new I, and for mpeg4 ...*/
714 p_sys->i_late_frames--; /* needed else it will never be decrease */
715 return true;
717 return false;
720 static void interpolate_next_pts( decoder_t *p_dec, AVFrame *frame )
722 decoder_sys_t *p_sys = p_dec->p_sys;
723 AVCodecContext *p_context = p_sys->p_context;
725 if( date_Get( &p_sys->pts ) == VLC_TS_INVALID ||
726 p_sys->pts.i_divider_num == 0 )
727 return;
729 int i_tick = p_context->ticks_per_frame;
730 if( i_tick <= 0 )
731 i_tick = 1;
733 /* interpolate the next PTS */
734 date_Increment( &p_sys->pts, i_tick + frame->repeat_pict );
737 static void update_late_frame_count( decoder_t *p_dec, block_t *p_block, mtime_t current_time, mtime_t i_pts )
739 decoder_sys_t *p_sys = p_dec->p_sys;
740 /* Update frame late count (except when doing preroll) */
741 mtime_t i_display_date = VLC_TS_INVALID;
742 if( !p_block || !(p_block->i_flags & BLOCK_FLAG_PREROLL) )
743 i_display_date = decoder_GetDisplayDate( p_dec, i_pts );
745 if( i_display_date > VLC_TS_INVALID && i_display_date <= current_time )
747 /* Out of preroll, consider only late frames on rising delay */
748 if( p_sys->b_from_preroll )
750 if( p_sys->i_last_late_delay > current_time - i_display_date )
752 p_sys->i_last_late_delay = current_time - i_display_date;
753 return;
755 p_sys->b_from_preroll = false;
758 p_sys->i_late_frames++;
759 if( p_sys->i_late_frames == 1 )
760 p_sys->i_late_frames_start = current_time;
763 else
765 p_sys->i_late_frames = 0;
770 static void DecodeSidedata( decoder_t *p_dec, const AVFrame *frame, picture_t *p_pic )
772 decoder_sys_t *p_sys = p_dec->p_sys;
773 bool format_changed = false;
775 #if (LIBAVUTIL_VERSION_MICRO >= 100 && LIBAVUTIL_VERSION_INT >= AV_VERSION_INT( 55, 16, 101 ) )
776 #define FROM_AVRAT(default_factor, avrat) \
777 (uint64_t)(default_factor) * (avrat).num / (avrat).den
778 const AVFrameSideData *metadata =
779 av_frame_get_side_data( frame,
780 AV_FRAME_DATA_MASTERING_DISPLAY_METADATA );
781 if ( metadata )
783 const AVMasteringDisplayMetadata *hdr_meta =
784 (const AVMasteringDisplayMetadata *) metadata->data;
785 if ( hdr_meta->has_luminance )
787 #define ST2086_LUMA_FACTOR 10000
788 p_pic->format.mastering.max_luminance =
789 FROM_AVRAT(ST2086_LUMA_FACTOR, hdr_meta->max_luminance);
790 p_pic->format.mastering.min_luminance =
791 FROM_AVRAT(ST2086_LUMA_FACTOR, hdr_meta->min_luminance);
793 if ( hdr_meta->has_primaries )
795 #define ST2086_RED 2
796 #define ST2086_GREEN 0
797 #define ST2086_BLUE 1
798 #define LAV_RED 0
799 #define LAV_GREEN 1
800 #define LAV_BLUE 2
801 #define ST2086_PRIM_FACTOR 50000
802 p_pic->format.mastering.primaries[ST2086_RED*2 + 0] =
803 FROM_AVRAT(ST2086_PRIM_FACTOR, hdr_meta->display_primaries[LAV_RED][0]);
804 p_pic->format.mastering.primaries[ST2086_RED*2 + 1] =
805 FROM_AVRAT(ST2086_PRIM_FACTOR, hdr_meta->display_primaries[LAV_RED][1]);
806 p_pic->format.mastering.primaries[ST2086_GREEN*2 + 0] =
807 FROM_AVRAT(ST2086_PRIM_FACTOR, hdr_meta->display_primaries[LAV_GREEN][0]);
808 p_pic->format.mastering.primaries[ST2086_GREEN*2 + 1] =
809 FROM_AVRAT(ST2086_PRIM_FACTOR, hdr_meta->display_primaries[LAV_GREEN][1]);
810 p_pic->format.mastering.primaries[ST2086_BLUE*2 + 0] =
811 FROM_AVRAT(ST2086_PRIM_FACTOR, hdr_meta->display_primaries[LAV_BLUE][0]);
812 p_pic->format.mastering.primaries[ST2086_BLUE*2 + 1] =
813 FROM_AVRAT(ST2086_PRIM_FACTOR, hdr_meta->display_primaries[LAV_BLUE][1]);
814 p_pic->format.mastering.white_point[0] =
815 FROM_AVRAT(ST2086_PRIM_FACTOR, hdr_meta->white_point[0]);
816 p_pic->format.mastering.white_point[1] =
817 FROM_AVRAT(ST2086_PRIM_FACTOR, hdr_meta->white_point[1]);
820 if ( memcmp( &p_dec->fmt_out.video.mastering,
821 &p_pic->format.mastering,
822 sizeof(p_pic->format.mastering) ) )
824 p_dec->fmt_out.video.mastering = p_pic->format.mastering;
825 format_changed = true;
827 #undef FROM_AVRAT
829 #endif
830 #if (LIBAVUTIL_VERSION_MICRO >= 100 && LIBAVUTIL_VERSION_INT >= AV_VERSION_INT( 55, 60, 100 ) )
831 const AVFrameSideData *metadata_lt =
832 av_frame_get_side_data( frame,
833 AV_FRAME_DATA_CONTENT_LIGHT_LEVEL );
834 if ( metadata_lt )
836 const AVContentLightMetadata *light_meta =
837 (const AVContentLightMetadata *) metadata_lt->data;
838 p_pic->format.lighting.MaxCLL = light_meta->MaxCLL;
839 p_pic->format.lighting.MaxFALL = light_meta->MaxFALL;
840 if ( memcmp( &p_dec->fmt_out.video.lighting,
841 &p_pic->format.lighting,
842 sizeof(p_pic->format.lighting) ) )
844 p_dec->fmt_out.video.lighting = p_pic->format.lighting;
845 format_changed = true;
848 #endif
850 if (format_changed)
851 decoder_UpdateVideoFormat( p_dec );
853 const AVFrameSideData *p_avcc = av_frame_get_side_data( frame, AV_FRAME_DATA_A53_CC );
854 if( p_avcc )
856 cc_Extract( &p_sys->cc, CC_PAYLOAD_RAW, true, p_avcc->data, p_avcc->size );
857 if( p_sys->cc.b_reorder || p_sys->cc.i_data )
859 block_t *p_cc = block_Alloc( p_sys->cc.i_data );
860 if( p_cc )
862 memcpy( p_cc->p_buffer, p_sys->cc.p_data, p_sys->cc.i_data );
863 if( p_sys->cc.b_reorder )
864 p_cc->i_dts = p_cc->i_pts = p_pic->date;
865 else
866 p_cc->i_pts = p_cc->i_dts;
867 decoder_QueueCc( p_dec, p_cc, p_sys->cc.pb_present, 4 );
869 cc_Flush( &p_sys->cc );
874 /*****************************************************************************
875 * DecodeBlock: Called to decode one or more frames
876 *****************************************************************************/
877 static picture_t *DecodeBlock( decoder_t *p_dec, block_t **pp_block, bool *error )
879 decoder_sys_t *p_sys = p_dec->p_sys;
880 AVCodecContext *p_context = p_sys->p_context;
881 /* Boolean if we assume that we should get valid pic as result */
882 bool b_need_output_picture = true;
884 /* Boolean for END_OF_SEQUENCE */
885 bool eos_spotted = false;
888 block_t *p_block;
889 mtime_t current_time = VLC_TS_INVALID;
891 if( !p_context->extradata_size && p_dec->fmt_in.i_extra )
893 ffmpeg_InitCodec( p_dec );
894 if( !avcodec_is_open( p_context ) )
895 OpenVideoCodec( p_dec );
898 p_block = pp_block ? *pp_block : NULL;
899 if(!p_block && !(p_sys->p_codec->capabilities & AV_CODEC_CAP_DELAY) )
900 return NULL;
902 if( !avcodec_is_open( p_context ) )
904 if( p_block )
905 block_Release( p_block );
906 return NULL;
909 if( !check_block_validity( p_sys, p_block ) )
910 return NULL;
912 current_time = mdate();
913 if( p_dec->b_frame_drop_allowed && check_block_being_late( p_sys, p_block, current_time) )
915 msg_Err( p_dec, "more than 5 seconds of late video -> "
916 "dropping frame (computer too slow ?)" );
917 return NULL;
921 /* A good idea could be to decode all I pictures and see for the other */
923 /* Defaults that if we aren't in prerolling, we want output picture
924 same for if we are flushing (p_block==NULL) */
925 if( !p_block || !(p_block->i_flags & BLOCK_FLAG_PREROLL) )
926 b_need_output_picture = true;
927 else
928 b_need_output_picture = false;
930 /* Change skip_frame config only if hurry_up is enabled */
931 if( p_sys->b_hurry_up )
933 p_context->skip_frame = p_sys->i_skip_frame;
935 /* Check also if we should/can drop the block and move to next block
936 as trying to catchup the speed*/
937 if( p_dec->b_frame_drop_allowed &&
938 check_frame_should_be_dropped( p_sys, p_context, &b_need_output_picture ) )
940 if( p_block )
941 block_Release( p_block );
942 msg_Warn( p_dec, "More than 11 late frames, dropping frame" );
943 return NULL;
946 if( !b_need_output_picture )
948 p_context->skip_frame = __MAX( p_context->skip_frame,
949 AVDISCARD_NONREF );
953 * Do the actual decoding now */
955 /* Don't forget that libavcodec requires a little more bytes
956 * that the real frame size */
957 if( p_block && p_block->i_buffer > 0 )
959 eos_spotted = ( p_block->i_flags & BLOCK_FLAG_END_OF_SEQUENCE ) != 0;
961 p_block = block_Realloc( p_block, 0,
962 p_block->i_buffer + FF_INPUT_BUFFER_PADDING_SIZE );
963 if( !p_block )
964 return NULL;
965 p_block->i_buffer -= FF_INPUT_BUFFER_PADDING_SIZE;
966 *pp_block = p_block;
967 memset( p_block->p_buffer + p_block->i_buffer, 0,
968 FF_INPUT_BUFFER_PADDING_SIZE );
971 while( !p_block || p_block->i_buffer > 0 || eos_spotted )
973 int i_used;
974 AVPacket pkt;
976 post_mt( p_sys );
978 av_init_packet( &pkt );
979 if( p_block && p_block->i_buffer > 0 )
981 pkt.data = p_block->p_buffer;
982 pkt.size = p_block->i_buffer;
983 pkt.pts = p_block->i_pts > VLC_TS_INVALID ? p_block->i_pts : AV_NOPTS_VALUE;
984 pkt.dts = p_block->i_dts > VLC_TS_INVALID ? p_block->i_dts : AV_NOPTS_VALUE;
986 else
988 /* Return delayed frames if codec has CODEC_CAP_DELAY */
989 pkt.data = NULL;
990 pkt.size = 0;
993 if( !p_sys->palette_sent )
995 uint8_t *pal = av_packet_new_side_data(&pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
996 if (pal) {
997 memcpy(pal, p_dec->fmt_in.video.p_palette->palette, AVPALETTE_SIZE);
998 p_sys->palette_sent = true;
1002 /* Make sure we don't reuse the same timestamps twice */
1003 if( p_block )
1005 p_block->i_pts =
1006 p_block->i_dts = VLC_TS_INVALID;
1009 #if LIBAVCODEC_VERSION_CHECK( 57, 0, 0xFFFFFFFFU, 64, 101 )
1010 if( !b_need_output_picture )
1011 pkt.flags |= AV_PKT_FLAG_DISCARD;
1012 #endif
1014 int ret = avcodec_send_packet(p_context, &pkt);
1015 if( ret != 0 && ret != AVERROR(EAGAIN) )
1017 if (ret == AVERROR(ENOMEM) || ret == AVERROR(EINVAL))
1019 msg_Err(p_dec, "avcodec_send_packet critical error");
1020 *error = true;
1022 av_packet_unref( &pkt );
1023 break;
1025 i_used = ret != AVERROR(EAGAIN) ? pkt.size : 0;
1026 av_packet_unref( &pkt );
1028 AVFrame *frame = av_frame_alloc();
1029 if (unlikely(frame == NULL))
1031 *error = true;
1032 break;
1035 ret = avcodec_receive_frame(p_context, frame);
1036 if( ret != 0 && ret != AVERROR(EAGAIN) )
1038 if (ret == AVERROR(ENOMEM) || ret == AVERROR(EINVAL))
1040 msg_Err(p_dec, "avcodec_receive_frame critical error");
1041 *error = true;
1043 av_frame_free(&frame);
1044 /* After draining, we need to reset decoder with a flush */
1045 if( ret == AVERROR_EOF )
1046 avcodec_flush_buffers( p_sys->p_context );
1047 break;
1049 bool not_received_frame = ret;
1051 wait_mt( p_sys );
1053 if( eos_spotted )
1054 p_sys->b_first_frame = true;
1056 if( p_block )
1058 if( p_block->i_buffer <= 0 )
1059 eos_spotted = false;
1061 /* Consumed bytes */
1062 p_block->p_buffer += i_used;
1063 p_block->i_buffer -= i_used;
1066 /* Nothing to display */
1067 if( not_received_frame )
1069 av_frame_free(&frame);
1070 if( i_used == 0 ) break;
1071 continue;
1074 /* Compute the PTS */
1075 #ifdef FF_API_PKT_PTS
1076 mtime_t i_pts = frame->pts;
1077 #else
1078 mtime_t i_pts = frame->pkt_pts;
1079 #endif
1080 if (i_pts == AV_NOPTS_VALUE )
1081 i_pts = frame->pkt_dts;
1083 if( i_pts == AV_NOPTS_VALUE )
1084 i_pts = date_Get( &p_sys->pts );
1086 /* Interpolate the next PTS */
1087 if( i_pts > VLC_TS_INVALID )
1088 date_Set( &p_sys->pts, i_pts );
1090 interpolate_next_pts( p_dec, frame );
1092 update_late_frame_count( p_dec, p_block, current_time, i_pts);
1094 if( ( !p_sys->p_va && !frame->linesize[0] ) ||
1095 ( p_dec->b_frame_drop_allowed && (frame->flags & AV_FRAME_FLAG_CORRUPT) &&
1096 !p_sys->b_show_corrupted ) )
1098 av_frame_free(&frame);
1099 continue;
1102 #if !LIBAVCODEC_VERSION_CHECK( 57, 0, 0xFFFFFFFFU, 64, 101 )
1103 if( !b_need_output_picture )
1105 av_frame_free(&frame);
1106 continue;
1108 #endif
1110 if( p_context->pix_fmt == AV_PIX_FMT_PAL8
1111 && !p_dec->fmt_out.video.p_palette )
1113 /* See AV_PIX_FMT_PAL8 comment in avc_GetVideoFormat(): update the
1114 * fmt_out palette and change the fmt_out chroma to request a new
1115 * vout */
1116 assert( p_dec->fmt_out.video.i_chroma != VLC_CODEC_RGBP );
1118 video_palette_t *p_palette;
1119 p_palette = p_dec->fmt_out.video.p_palette
1120 = malloc( sizeof(video_palette_t) );
1121 if( !p_palette )
1123 *error = true;
1124 av_frame_free(&frame);
1125 break;
1127 static_assert( sizeof(p_palette->palette) == AVPALETTE_SIZE,
1128 "Palette size mismatch between vlc and libavutil" );
1129 assert( frame->data[1] != NULL );
1130 memcpy( p_palette->palette, frame->data[1], AVPALETTE_SIZE );
1131 p_palette->i_entries = AVPALETTE_COUNT;
1132 p_dec->fmt_out.video.i_chroma = VLC_CODEC_RGBP;
1133 if( decoder_UpdateVideoFormat( p_dec ) )
1135 av_frame_free(&frame);
1136 continue;
1140 picture_t *p_pic = frame->opaque;
1141 if( p_pic == NULL )
1142 { /* When direct rendering is not used, get_format() and get_buffer()
1143 * might not be called. The output video format must be set here
1144 * then picture buffer can be allocated. */
1145 if (p_sys->p_va == NULL
1146 && lavc_UpdateVideoFormat(p_dec, p_context, p_context->pix_fmt,
1147 p_context->pix_fmt) == 0)
1148 p_pic = decoder_NewPicture(p_dec);
1150 if( !p_pic )
1152 av_frame_free(&frame);
1153 break;
1156 /* Fill picture_t from AVFrame */
1157 if( lavc_CopyPicture( p_dec, p_pic, frame ) != VLC_SUCCESS )
1159 av_frame_free(&frame);
1160 picture_Release( p_pic );
1161 break;
1164 else
1166 picture_Hold( p_pic );
1169 if( !p_dec->fmt_in.video.i_sar_num || !p_dec->fmt_in.video.i_sar_den )
1171 /* Fetch again the aspect ratio in case it changed */
1172 p_dec->fmt_out.video.i_sar_num
1173 = p_context->sample_aspect_ratio.num;
1174 p_dec->fmt_out.video.i_sar_den
1175 = p_context->sample_aspect_ratio.den;
1177 if( !p_dec->fmt_out.video.i_sar_num || !p_dec->fmt_out.video.i_sar_den )
1179 p_dec->fmt_out.video.i_sar_num = 1;
1180 p_dec->fmt_out.video.i_sar_den = 1;
1184 p_pic->date = i_pts;
1185 /* Hack to force display of still pictures */
1186 p_pic->b_force = p_sys->b_first_frame;
1187 p_pic->i_nb_fields = 2 + frame->repeat_pict;
1188 p_pic->b_progressive = !frame->interlaced_frame;
1189 p_pic->b_top_field_first = frame->top_field_first;
1191 DecodeSidedata( p_dec, frame, p_pic );
1193 av_frame_free(&frame);
1195 /* Send decoded frame to vout */
1196 if (i_pts > VLC_TS_INVALID)
1198 p_sys->b_first_frame = false;
1199 return p_pic;
1201 else
1202 picture_Release( p_pic );
1205 if( p_block )
1206 block_Release( p_block );
1207 return NULL;
1210 static int DecodeVideo( decoder_t *p_dec, block_t *p_block )
1212 block_t **pp_block = p_block ? &p_block : NULL;
1213 picture_t *p_pic;
1214 bool error = false;
1215 while( ( p_pic = DecodeBlock( p_dec, pp_block, &error ) ) != NULL )
1216 decoder_QueueVideo( p_dec, p_pic );
1217 return error ? VLCDEC_ECRITICAL : VLCDEC_SUCCESS;
1220 /*****************************************************************************
1221 * EndVideo: decoder destruction
1222 *****************************************************************************
1223 * This function is called when the thread ends after a successful
1224 * initialization.
1225 *****************************************************************************/
1226 void EndVideoDec( vlc_object_t *obj )
1228 decoder_t *p_dec = (decoder_t *)obj;
1229 decoder_sys_t *p_sys = p_dec->p_sys;
1230 AVCodecContext *ctx = p_sys->p_context;
1231 void *hwaccel_context;
1233 post_mt( p_sys );
1235 /* do not flush buffers if codec hasn't been opened (theora/vorbis/VC1) */
1236 if( avcodec_is_open( ctx ) )
1237 avcodec_flush_buffers( ctx );
1239 wait_mt( p_sys );
1241 cc_Flush( &p_sys->cc );
1243 hwaccel_context = ctx->hwaccel_context;
1244 avcodec_free_context( &ctx );
1246 if( p_sys->p_va )
1247 vlc_va_Delete( p_sys->p_va, &hwaccel_context );
1249 vlc_sem_destroy( &p_sys->sem_mt );
1250 free( p_sys );
1253 /*****************************************************************************
1254 * ffmpeg_InitCodec: setup codec extra initialization data for ffmpeg
1255 *****************************************************************************/
1256 static void ffmpeg_InitCodec( decoder_t *p_dec )
1258 decoder_sys_t *p_sys = p_dec->p_sys;
1259 size_t i_size = p_dec->fmt_in.i_extra;
1261 if( !i_size ) return;
1263 if( p_sys->p_codec->id == AV_CODEC_ID_SVQ3 )
1265 uint8_t *p;
1267 p_sys->p_context->extradata_size = i_size + 12;
1268 p = p_sys->p_context->extradata =
1269 av_malloc( p_sys->p_context->extradata_size +
1270 FF_INPUT_BUFFER_PADDING_SIZE );
1271 if( !p )
1272 return;
1274 memcpy( &p[0], "SVQ3", 4 );
1275 memset( &p[4], 0, 8 );
1276 memcpy( &p[12], p_dec->fmt_in.p_extra, i_size );
1278 /* Now remove all atoms before the SMI one */
1279 if( p_sys->p_context->extradata_size > 0x5a &&
1280 strncmp( (char*)&p[0x56], "SMI ", 4 ) )
1282 uint8_t *psz = &p[0x52];
1284 while( psz < &p[p_sys->p_context->extradata_size - 8] )
1286 uint_fast32_t atom_size = GetDWBE( psz );
1287 if( atom_size <= 1 )
1289 /* FIXME handle 1 as long size */
1290 break;
1292 if( !strncmp( (char*)&psz[4], "SMI ", 4 ) )
1294 memmove( &p[0x52], psz,
1295 &p[p_sys->p_context->extradata_size] - psz );
1296 break;
1299 psz += atom_size;
1303 else
1305 p_sys->p_context->extradata_size = i_size;
1306 p_sys->p_context->extradata =
1307 av_malloc( i_size + FF_INPUT_BUFFER_PADDING_SIZE );
1308 if( p_sys->p_context->extradata )
1310 memcpy( p_sys->p_context->extradata,
1311 p_dec->fmt_in.p_extra, i_size );
1312 memset( p_sys->p_context->extradata + i_size,
1313 0, FF_INPUT_BUFFER_PADDING_SIZE );
1318 static void lavc_ReleaseFrame(void *opaque, uint8_t *data)
1320 (void) data;
1321 picture_t *picture = opaque;
1323 picture_Release(picture);
1326 static int lavc_va_GetFrame(struct AVCodecContext *ctx, AVFrame *frame,
1327 picture_t *pic)
1329 decoder_t *dec = ctx->opaque;
1330 vlc_va_t *va = dec->p_sys->p_va;
1332 if (vlc_va_Get(va, pic, &frame->data[0]))
1334 msg_Err(dec, "hardware acceleration picture allocation failed");
1335 picture_Release(pic);
1336 return -1;
1338 assert(frame->data[0] != NULL);
1339 /* data[0] must be non-NULL for libavcodec internal checks.
1340 * data[3] actually contains the format-specific surface handle. */
1341 frame->data[3] = frame->data[0];
1343 frame->buf[0] = av_buffer_create(frame->data[0], 0, lavc_ReleaseFrame, pic, 0);
1344 if (unlikely(frame->buf[0] == NULL))
1346 lavc_ReleaseFrame(pic, frame->data[0]);
1347 return -1;
1350 frame->opaque = pic;
1351 return 0;
1354 static int lavc_dr_GetFrame(struct AVCodecContext *ctx, AVFrame *frame,
1355 picture_t *pic)
1357 decoder_t *dec = (decoder_t *)ctx->opaque;
1358 decoder_sys_t *sys = dec->p_sys;
1360 if (ctx->pix_fmt == AV_PIX_FMT_PAL8)
1361 goto error;
1363 int width = frame->width;
1364 int height = frame->height;
1365 int aligns[AV_NUM_DATA_POINTERS];
1367 avcodec_align_dimensions2(ctx, &width, &height, aligns);
1369 /* Check that the picture is suitable for libavcodec */
1370 assert(pic->p[0].i_pitch >= width * pic->p[0].i_pixel_pitch);
1371 assert(pic->p[0].i_lines >= height);
1373 for (int i = 0; i < pic->i_planes; i++)
1375 if (pic->p[i].i_pitch % aligns[i])
1377 if (!atomic_exchange(&sys->b_dr_failure, true))
1378 msg_Warn(dec, "plane %d: pitch not aligned (%d%%%d): disabling direct rendering",
1379 i, pic->p[i].i_pitch, aligns[i]);
1380 goto error;
1382 if (((uintptr_t)pic->p[i].p_pixels) % aligns[i])
1384 if (!atomic_exchange(&sys->b_dr_failure, true))
1385 msg_Warn(dec, "plane %d not aligned: disabling direct rendering", i);
1386 goto error;
1390 /* Allocate buffer references and initialize planes */
1391 assert(pic->i_planes < PICTURE_PLANE_MAX);
1392 static_assert(PICTURE_PLANE_MAX <= AV_NUM_DATA_POINTERS, "Oops!");
1394 for (int i = 0; i < pic->i_planes; i++)
1396 uint8_t *data = pic->p[i].p_pixels;
1397 int size = pic->p[i].i_pitch * pic->p[i].i_lines;
1399 frame->data[i] = data;
1400 frame->linesize[i] = pic->p[i].i_pitch;
1401 frame->buf[i] = av_buffer_create(data, size, lavc_ReleaseFrame,
1402 pic, 0);
1403 if (unlikely(frame->buf[i] == NULL))
1405 while (i > 0)
1406 av_buffer_unref(&frame->buf[--i]);
1407 goto error;
1409 picture_Hold(pic);
1412 frame->opaque = pic;
1413 /* The loop above held one reference to the picture for each plane. */
1414 picture_Release(pic);
1415 return 0;
1416 error:
1417 picture_Release(pic);
1418 return -1;
1422 * Callback used by libavcodec to get a frame buffer.
1424 * It is used for direct rendering as well as to get the right PTS for each
1425 * decoded picture (even in indirect rendering mode).
1427 static int lavc_GetFrame(struct AVCodecContext *ctx, AVFrame *frame, int flags)
1429 decoder_t *dec = ctx->opaque;
1430 decoder_sys_t *sys = dec->p_sys;
1431 picture_t *pic;
1433 for (unsigned i = 0; i < AV_NUM_DATA_POINTERS; i++)
1435 frame->data[i] = NULL;
1436 frame->linesize[i] = 0;
1437 frame->buf[i] = NULL;
1439 frame->opaque = NULL;
1441 wait_mt(sys);
1442 if (sys->p_va == NULL)
1444 if (!sys->b_direct_rendering)
1446 post_mt(sys);
1447 return avcodec_default_get_buffer2(ctx, frame, flags);
1450 /* Most unaccelerated decoders do not call get_format(), so we need to
1451 * update the output video format here. The MT semaphore must be held
1452 * to protect p_dec->fmt_out. */
1453 if (lavc_UpdateVideoFormat(dec, ctx, ctx->pix_fmt, ctx->pix_fmt))
1455 post_mt(sys);
1456 return -1;
1459 post_mt(sys);
1461 pic = decoder_NewPicture(dec);
1462 if (pic == NULL)
1463 return -ENOMEM;
1465 if (sys->p_va != NULL)
1466 return lavc_va_GetFrame(ctx, frame, pic);
1468 /* Some codecs set pix_fmt only after the 1st frame has been decoded,
1469 * so we need to check for direct rendering again. */
1470 int ret = lavc_dr_GetFrame(ctx, frame, pic);
1471 if (ret)
1472 ret = avcodec_default_get_buffer2(ctx, frame, flags);
1473 return ret;
1476 static enum PixelFormat ffmpeg_GetFormat( AVCodecContext *p_context,
1477 const enum PixelFormat *pi_fmt )
1479 decoder_t *p_dec = p_context->opaque;
1480 decoder_sys_t *p_sys = p_dec->p_sys;
1481 video_format_t fmt;
1482 size_t i;
1484 /* Enumerate available formats */
1485 enum PixelFormat swfmt = avcodec_default_get_format(p_context, pi_fmt);
1486 bool can_hwaccel = false;
1488 for( i = 0; pi_fmt[i] != AV_PIX_FMT_NONE; i++ )
1490 const AVPixFmtDescriptor *dsc = av_pix_fmt_desc_get(pi_fmt[i]);
1491 if (dsc == NULL)
1492 continue;
1493 bool hwaccel = (dsc->flags & AV_PIX_FMT_FLAG_HWACCEL) != 0;
1495 msg_Dbg( p_dec, "available %sware decoder output format %d (%s)",
1496 hwaccel ? "hard" : "soft", pi_fmt[i], dsc->name );
1497 if (hwaccel)
1498 can_hwaccel = true;
1500 #if defined(_WIN32) && LIBAVUTIL_VERSION_CHECK(54, 13, 1, 24, 100)
1501 enum PixelFormat p_fmts[i+1];
1502 if (i > 1 && pi_fmt[0] == AV_PIX_FMT_DXVA2_VLD && pi_fmt[1] == AV_PIX_FMT_D3D11VA_VLD)
1504 /* favor D3D11VA over DXVA2 as the order will decide which vout will be
1505 * used */
1506 memcpy(p_fmts, pi_fmt, sizeof(p_fmts));
1507 p_fmts[0] = AV_PIX_FMT_D3D11VA_VLD;
1508 p_fmts[1] = AV_PIX_FMT_DXVA2_VLD;
1509 pi_fmt = p_fmts;
1511 #endif
1513 /* If the format did not actually change (e.g. seeking), try to reuse the
1514 * existing output format, and if present, hardware acceleration back-end.
1515 * This avoids resetting the pipeline downstream. This also avoids
1516 * needlessly probing for hardware acceleration support. */
1517 if (p_sys->pix_fmt != AV_PIX_FMT_NONE
1518 && lavc_GetVideoFormat(p_dec, &fmt, p_context, p_sys->pix_fmt, swfmt) == 0
1519 && fmt.i_width == p_dec->fmt_out.video.i_width
1520 && fmt.i_height == p_dec->fmt_out.video.i_height
1521 && p_context->profile == p_sys->profile
1522 && p_context->level <= p_sys->level)
1524 for (size_t i = 0; pi_fmt[i] != AV_PIX_FMT_NONE; i++)
1525 if (pi_fmt[i] == p_sys->pix_fmt)
1527 msg_Dbg(p_dec, "reusing decoder output format %d", pi_fmt[i]);
1528 return p_sys->pix_fmt;
1532 if (p_sys->p_va != NULL)
1534 msg_Err(p_dec, "existing hardware acceleration cannot be reused");
1535 vlc_va_Delete(p_sys->p_va, &p_context->hwaccel_context);
1536 p_sys->p_va = NULL;
1539 p_sys->profile = p_context->profile;
1540 p_sys->level = p_context->level;
1542 if (!can_hwaccel)
1543 return swfmt;
1545 #if (LIBAVCODEC_VERSION_MICRO >= 100) \
1546 && (LIBAVCODEC_VERSION_INT < AV_VERSION_INT(57, 83, 101))
1547 if (p_context->active_thread_type)
1549 msg_Warn(p_dec, "thread type %d: disabling hardware acceleration",
1550 p_context->active_thread_type);
1551 return swfmt;
1553 #endif
1555 wait_mt(p_sys);
1557 for( size_t i = 0; pi_fmt[i] != AV_PIX_FMT_NONE; i++ )
1559 enum PixelFormat hwfmt = pi_fmt[i];
1561 p_dec->fmt_out.video.i_chroma = vlc_va_GetChroma(hwfmt, swfmt);
1562 if (p_dec->fmt_out.video.i_chroma == 0)
1563 continue; /* Unknown brand of hardware acceleration */
1564 if (p_context->width == 0 || p_context->height == 0)
1565 { /* should never happen */
1566 msg_Err(p_dec, "unspecified video dimensions");
1567 continue;
1569 if (lavc_UpdateVideoFormat(p_dec, p_context, hwfmt, swfmt))
1570 continue; /* Unsupported brand of hardware acceleration */
1571 post_mt(p_sys);
1573 picture_t *test_pic = decoder_NewPicture(p_dec);
1574 assert(!test_pic || test_pic->format.i_chroma == p_dec->fmt_out.video.i_chroma);
1575 vlc_va_t *va = vlc_va_New(VLC_OBJECT(p_dec), p_context, hwfmt,
1576 &p_dec->fmt_in,
1577 test_pic ? test_pic->p_sys : NULL);
1578 if (test_pic)
1579 picture_Release(test_pic);
1580 if (va == NULL)
1582 wait_mt(p_sys);
1583 continue; /* Unsupported codec profile or such */
1586 if (va->description != NULL)
1587 msg_Info(p_dec, "Using %s for hardware decoding", va->description);
1589 p_sys->p_va = va;
1590 p_sys->pix_fmt = hwfmt;
1591 p_context->draw_horiz_band = NULL;
1592 return pi_fmt[i];
1595 post_mt(p_sys);
1596 /* Fallback to default behaviour */
1597 p_sys->pix_fmt = swfmt;
1598 return swfmt;