]> git.sesse.net Git - vlc/blob - modules/codec/avcodec/video.c
Used reordered_opaque for timestamp managment in avcodec.
[vlc] / modules / codec / avcodec / video.c
1 /*****************************************************************************
2  * video.c: video decoder using the ffmpeg library
3  *****************************************************************************
4  * Copyright (C) 1999-2001 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Gildas Bazin <gbazin@videolan.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
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 General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc_common.h>
33 #include <vlc_codec.h>
34 #include <vlc_avcodec.h>
35 #include <assert.h>
36
37 /* ffmpeg header */
38 #ifdef HAVE_LIBAVCODEC_AVCODEC_H
39 #   include <libavcodec/avcodec.h>
40 #   ifdef HAVE_AVCODEC_VAAPI
41 #       include <libavcodec/vaapi.h>
42 #   endif
43 #   ifdef HAVE_AVCODEC_DXVA2
44 #       include <libavcodec/dxva2.h>
45 #   endif
46 #elif defined(HAVE_FFMPEG_AVCODEC_H)
47 #   include <ffmpeg/avcodec.h>
48 #else
49 #   include <avcodec.h>
50 #endif
51
52 #include "avcodec.h"
53 #include "va.h"
54 #if defined(HAVE_AVCODEC_VAAPI) || defined(HAVE_AVCODEC_DXVA2)
55 #   define HAVE_AVCODEC_VA
56 #endif
57
58 /*****************************************************************************
59  * decoder_sys_t : decoder descriptor
60  *****************************************************************************/
61 struct decoder_sys_t
62 {
63     FFMPEG_COMMON_MEMBERS
64
65     /* Video decoder specific part */
66     mtime_t i_pts;
67
68     AVFrame          *p_ff_pic;
69
70     /* for frame skipping algo */
71     bool b_hurry_up;
72     enum AVDiscard i_skip_frame;
73     enum AVDiscard i_skip_idct;
74
75     /* how many decoded frames are late */
76     int     i_late_frames;
77     mtime_t i_late_frames_start;
78
79     /* for direct rendering */
80     bool b_direct_rendering;
81     int  i_direct_rendering_used;
82
83     bool b_has_b_frames;
84
85     /* Hack to force display of still pictures */
86     bool b_first_frame;
87
88     /* */
89     AVPaletteControl palette;
90
91     /* */
92     bool b_flush;
93
94     /* VA API */
95     vlc_va_t *p_va;
96 };
97
98 /* FIXME (dummy palette for now) */
99 static const AVPaletteControl palette_control;
100
101 /*****************************************************************************
102  * Local prototypes
103  *****************************************************************************/
104 static void ffmpeg_InitCodec      ( decoder_t * );
105 static int  ffmpeg_OpenCodec      ( decoder_t * );
106 static void ffmpeg_CopyPicture    ( decoder_t *, picture_t *, AVFrame * );
107 static int  ffmpeg_GetFrameBuf    ( struct AVCodecContext *, AVFrame * );
108 static int  ffmpeg_ReGetFrameBuf( struct AVCodecContext *, AVFrame * );
109 static void ffmpeg_ReleaseFrameBuf( struct AVCodecContext *, AVFrame * );
110
111 #ifdef HAVE_AVCODEC_VA
112 static enum PixelFormat ffmpeg_GetFormat( AVCodecContext *,
113                                           const enum PixelFormat * );
114 #endif
115
116 static uint32_t ffmpeg_CodecTag( vlc_fourcc_t fcc )
117 {
118     uint8_t *p = (uint8_t*)&fcc;
119     return p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
120 }
121
122 /*****************************************************************************
123  * Local Functions
124  *****************************************************************************/
125
126 /* Returns a new picture buffer */
127 static inline picture_t *ffmpeg_NewPictBuf( decoder_t *p_dec,
128                                             AVCodecContext *p_context )
129 {
130     decoder_sys_t *p_sys = p_dec->p_sys;
131
132     p_dec->fmt_out.video.i_width = p_context->width;
133     p_dec->fmt_out.video.i_height = p_context->height;
134
135     if( !p_context->width || !p_context->height )
136     {
137         return NULL; /* invalid display size */
138     }
139
140     if( !p_sys->p_va && GetVlcChroma( &p_dec->fmt_out.video, p_context->pix_fmt ) )
141     {
142         /* we are doomed, but not really, because most codecs set their pix_fmt
143          * much later
144          * FIXME does it make sense here ? */
145         p_dec->fmt_out.video.i_chroma = VLC_CODEC_I420;
146     }
147     p_dec->fmt_out.i_codec = p_dec->fmt_out.video.i_chroma;
148
149     /* If an aspect-ratio was specified in the input format then force it */
150     if( p_dec->fmt_in.video.i_sar_num > 0 && p_dec->fmt_in.video.i_sar_den > 0 )
151     {
152         p_dec->fmt_out.video.i_sar_num = p_dec->fmt_in.video.i_sar_num;
153         p_dec->fmt_out.video.i_sar_den = p_dec->fmt_in.video.i_sar_den;
154     }
155     else
156     {
157         p_dec->fmt_out.video.i_sar_num = p_context->sample_aspect_ratio.num;
158         p_dec->fmt_out.video.i_sar_den = p_context->sample_aspect_ratio.den;
159
160         if( !p_dec->fmt_out.video.i_sar_num || !p_dec->fmt_out.video.i_sar_den )
161         {
162             p_dec->fmt_out.video.i_sar_num = 1;
163             p_dec->fmt_out.video.i_sar_den = 1;
164         }
165     }
166
167     if( p_dec->fmt_in.video.i_frame_rate > 0 &&
168         p_dec->fmt_in.video.i_frame_rate_base > 0 )
169     {
170         p_dec->fmt_out.video.i_frame_rate =
171             p_dec->fmt_in.video.i_frame_rate;
172         p_dec->fmt_out.video.i_frame_rate_base =
173             p_dec->fmt_in.video.i_frame_rate_base;
174     }
175     else if( p_context->time_base.num > 0 && p_context->time_base.den > 0 )
176     {
177         p_dec->fmt_out.video.i_frame_rate = p_context->time_base.den;
178         p_dec->fmt_out.video.i_frame_rate_base = p_context->time_base.num;
179     }
180
181     return decoder_NewPicture( p_dec );
182 }
183
184 /*****************************************************************************
185  * InitVideo: initialize the video decoder
186  *****************************************************************************
187  * the ffmpeg codec will be opened, some memory allocated. The vout is not yet
188  * opened (done after the first decoded frame).
189  *****************************************************************************/
190 int InitVideoDec( decoder_t *p_dec, AVCodecContext *p_context,
191                       AVCodec *p_codec, int i_codec_id, const char *psz_namecodec )
192 {
193     decoder_sys_t *p_sys;
194     int i_val;
195
196     /* Allocate the memory needed to store the decoder's structure */
197     if( ( p_dec->p_sys = p_sys = calloc( 1, sizeof(decoder_sys_t) ) ) == NULL )
198         return VLC_ENOMEM;
199
200     p_codec->type = CODEC_TYPE_VIDEO;
201     p_context->codec_type = CODEC_TYPE_VIDEO;
202     p_context->codec_id = i_codec_id;
203     p_sys->p_context = p_context;
204     p_sys->p_codec = p_codec;
205     p_sys->i_codec_id = i_codec_id;
206     p_sys->psz_namecodec = psz_namecodec;
207     p_sys->p_ff_pic = avcodec_alloc_frame();
208     p_sys->b_delayed_open = true;
209     p_sys->p_va = NULL;
210
211     /* ***** Fill p_context with init values ***** */
212     p_sys->p_context->codec_tag = ffmpeg_CodecTag( p_dec->fmt_in.i_original_fourcc ?: p_dec->fmt_in.i_codec );
213
214     /*  ***** Get configuration of ffmpeg plugin ***** */
215     p_sys->p_context->workaround_bugs =
216         var_InheritInteger( p_dec, "ffmpeg-workaround-bugs" );
217     p_sys->p_context->error_recognition =
218         var_InheritInteger( p_dec, "ffmpeg-error-resilience" );
219
220     if( var_CreateGetBool( p_dec, "grayscale" ) )
221         p_sys->p_context->flags |= CODEC_FLAG_GRAY;
222
223     i_val = var_CreateGetInteger( p_dec, "ffmpeg-vismv" );
224     if( i_val ) p_sys->p_context->debug_mv = i_val;
225
226     i_val = var_CreateGetInteger( p_dec, "ffmpeg-lowres" );
227     if( i_val > 0 && i_val <= 2 ) p_sys->p_context->lowres = i_val;
228
229     i_val = var_CreateGetInteger( p_dec, "ffmpeg-skiploopfilter" );
230     if( i_val >= 4 ) p_sys->p_context->skip_loop_filter = AVDISCARD_ALL;
231     else if( i_val == 3 ) p_sys->p_context->skip_loop_filter = AVDISCARD_NONKEY;
232     else if( i_val == 2 ) p_sys->p_context->skip_loop_filter = AVDISCARD_BIDIR;
233     else if( i_val == 1 ) p_sys->p_context->skip_loop_filter = AVDISCARD_NONREF;
234
235     if( var_CreateGetBool( p_dec, "ffmpeg-fast" ) )
236         p_sys->p_context->flags2 |= CODEC_FLAG2_FAST;
237
238     /* ***** ffmpeg frame skipping ***** */
239     p_sys->b_hurry_up = var_CreateGetBool( p_dec, "ffmpeg-hurry-up" );
240
241     switch( var_CreateGetInteger( p_dec, "ffmpeg-skip-frame" ) )
242     {
243         case -1:
244             p_sys->p_context->skip_frame = AVDISCARD_NONE;
245             break;
246         case 0:
247             p_sys->p_context->skip_frame = AVDISCARD_DEFAULT;
248             break;
249         case 1:
250             p_sys->p_context->skip_frame = AVDISCARD_BIDIR;
251             break;
252         case 2:
253             p_sys->p_context->skip_frame = AVDISCARD_NONKEY;
254             break;
255         case 3:
256             p_sys->p_context->skip_frame = AVDISCARD_ALL;
257             break;
258         default:
259             p_sys->p_context->skip_frame = AVDISCARD_NONE;
260             break;
261     }
262     p_sys->i_skip_frame = p_sys->p_context->skip_frame;
263
264     switch( var_CreateGetInteger( p_dec, "ffmpeg-skip-idct" ) )
265     {
266         case -1:
267             p_sys->p_context->skip_idct = AVDISCARD_NONE;
268             break;
269         case 0:
270             p_sys->p_context->skip_idct = AVDISCARD_DEFAULT;
271             break;
272         case 1:
273             p_sys->p_context->skip_idct = AVDISCARD_BIDIR;
274             break;
275         case 2:
276             p_sys->p_context->skip_idct = AVDISCARD_NONKEY;
277             break;
278         case 3:
279             p_sys->p_context->skip_idct = AVDISCARD_ALL;
280             break;
281         default:
282             p_sys->p_context->skip_idct = AVDISCARD_NONE;
283             break;
284     }
285     p_sys->i_skip_idct = p_sys->p_context->skip_idct;
286
287     /* ***** ffmpeg direct rendering ***** */
288     p_sys->b_direct_rendering = false;
289     p_sys->i_direct_rendering_used = -1;
290     if( var_CreateGetBool( p_dec, "ffmpeg-dr" ) &&
291        (p_sys->p_codec->capabilities & CODEC_CAP_DR1) &&
292         /* No idea why ... but this fixes flickering on some TSCC streams */
293         p_sys->i_codec_id != CODEC_ID_TSCC &&
294         !p_sys->p_context->debug_mv )
295     {
296         /* Some codecs set pix_fmt only after the 1st frame has been decoded,
297          * so we need to do another check in ffmpeg_GetFrameBuf() */
298         p_sys->b_direct_rendering = true;
299     }
300
301     /* ffmpeg doesn't properly release old pictures when frames are skipped */
302     //if( p_sys->b_hurry_up ) p_sys->b_direct_rendering = false;
303     if( p_sys->b_direct_rendering )
304     {
305         msg_Dbg( p_dec, "trying to use direct rendering" );
306         p_sys->p_context->flags |= CODEC_FLAG_EMU_EDGE;
307     }
308     else
309     {
310         msg_Dbg( p_dec, "direct rendering is disabled" );
311     }
312
313     /* Always use our get_buffer wrapper so we can calculate the
314      * PTS correctly */
315     p_sys->p_context->get_buffer = ffmpeg_GetFrameBuf;
316     p_sys->p_context->reget_buffer = ffmpeg_ReGetFrameBuf;
317     p_sys->p_context->release_buffer = ffmpeg_ReleaseFrameBuf;
318     p_sys->p_context->opaque = p_dec;
319
320 #ifdef HAVE_AVCODEC_VA
321     if( var_CreateGetBool( p_dec, "ffmpeg-hw" ) )
322         p_sys->p_context->get_format = ffmpeg_GetFormat;
323 #endif
324
325     /* ***** misc init ***** */
326     p_sys->i_pts = VLC_TS_INVALID;
327     p_sys->b_has_b_frames = false;
328     p_sys->b_first_frame = true;
329     p_sys->b_flush = false;
330     p_sys->i_late_frames = 0;
331
332     /* Set output properties */
333     p_dec->fmt_out.i_cat = VIDEO_ES;
334     if( GetVlcChroma( &p_dec->fmt_out.video, p_context->pix_fmt ) != VLC_SUCCESS )
335     {
336         /* we are doomed. but not really, because most codecs set their pix_fmt later on */
337         p_dec->fmt_out.i_codec = VLC_CODEC_I420;
338     }
339     p_dec->fmt_out.i_codec = p_dec->fmt_out.video.i_chroma;
340
341     /* Setup palette */
342     memset( &p_sys->palette, 0, sizeof(p_sys->palette) );
343     if( p_dec->fmt_in.video.p_palette )
344     {
345         p_sys->palette.palette_changed = 1;
346
347         for( int i = 0; i < __MIN( AVPALETTE_COUNT, p_dec->fmt_in.video.p_palette->i_entries ); i++ )
348         {
349             union {
350                 uint32_t u;
351                 uint8_t a[4];
352             } c;
353             c.a[0] = p_dec->fmt_in.video.p_palette->palette[i][0];
354             c.a[1] = p_dec->fmt_in.video.p_palette->palette[i][1];
355             c.a[2] = p_dec->fmt_in.video.p_palette->palette[i][2];
356             c.a[3] = p_dec->fmt_in.video.p_palette->palette[i][3];
357
358             p_sys->palette.palette[i] = c.u;
359         }
360         p_sys->p_context->palctrl = &p_sys->palette;
361
362         p_dec->fmt_out.video.p_palette = malloc( sizeof(video_palette_t) );
363         if( p_dec->fmt_out.video.p_palette )
364             *p_dec->fmt_out.video.p_palette = *p_dec->fmt_in.video.p_palette;
365     }
366     else if( p_sys->i_codec_id != CODEC_ID_MSVIDEO1 && p_sys->i_codec_id != CODEC_ID_CINEPAK )
367     {
368         p_sys->p_context->palctrl = &p_sys->palette;
369     }
370
371     /* ***** init this codec with special data ***** */
372     ffmpeg_InitCodec( p_dec );
373
374     /* ***** Open the codec ***** */
375     if( ffmpeg_OpenCodec( p_dec ) < 0 )
376     {
377         msg_Err( p_dec, "cannot open codec (%s)", p_sys->psz_namecodec );
378         av_free( p_sys->p_ff_pic );
379         free( p_sys );
380         return VLC_EGENERIC;
381     }
382
383     return VLC_SUCCESS;
384 }
385
386 /*****************************************************************************
387  * DecodeVideo: Called to decode one or more frames
388  *****************************************************************************/
389 picture_t *DecodeVideo( decoder_t *p_dec, block_t **pp_block )
390 {
391     decoder_sys_t *p_sys = p_dec->p_sys;
392     AVCodecContext *p_context = p_sys->p_context;
393     int b_drawpicture;
394     int b_null_size = false;
395     block_t *p_block;
396
397     if( !pp_block || !*pp_block )
398         return NULL;
399
400     if( !p_context->extradata_size && p_dec->fmt_in.i_extra )
401     {
402         ffmpeg_InitCodec( p_dec );
403         if( p_sys->b_delayed_open )
404         {
405             if( ffmpeg_OpenCodec( p_dec ) )
406                 msg_Err( p_dec, "cannot open codec (%s)", p_sys->psz_namecodec );
407         }
408     }
409
410     p_block = *pp_block;
411     if( p_sys->b_delayed_open )
412     {
413         block_Release( p_block );
414         return NULL;
415     }
416
417     if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
418     {
419         p_sys->i_pts = VLC_TS_INVALID; /* To make sure we recover properly */
420
421         p_sys->i_late_frames = 0;
422
423         block_Release( p_block );
424
425         //if( p_block->i_flags & BLOCK_FLAG_CORRUPTED )
426             //avcodec_flush_buffers( p_context );
427         return NULL;
428     }
429
430     if( p_block->i_flags & BLOCK_FLAG_PREROLL )
431     {
432         /* Do not care about late frames when prerolling
433          * TODO avoid decoding of non reference frame
434          * (ie all B except for H264 where it depends only on nal_ref_idc) */
435         p_sys->i_late_frames = 0;
436     }
437
438     if( !p_dec->b_pace_control && (p_sys->i_late_frames > 0) &&
439         (mdate() - p_sys->i_late_frames_start > INT64_C(5000000)) )
440     {
441         if( p_sys->i_pts > VLC_TS_INVALID )
442         {
443             msg_Err( p_dec, "more than 5 seconds of late video -> "
444                      "dropping frame (computer too slow ?)" );
445             p_sys->i_pts = VLC_TS_INVALID; /* To make sure we recover properly */
446         }
447         block_Release( p_block );
448         p_sys->i_late_frames--;
449         return NULL;
450     }
451
452     /* A good idea could be to decode all I pictures and see for the other */
453     if( !p_dec->b_pace_control &&
454         p_sys->b_hurry_up &&
455         (p_sys->i_late_frames > 4) )
456     {
457         b_drawpicture = 0;
458         if( p_sys->i_late_frames < 12 )
459         {
460             p_context->skip_frame =
461                     (p_sys->i_skip_frame <= AVDISCARD_BIDIR) ?
462                     AVDISCARD_BIDIR : p_sys->i_skip_frame;
463         }
464         else
465         {
466             /* picture too late, won't decode
467              * but break picture until a new I, and for mpeg4 ...*/
468             p_sys->i_late_frames--; /* needed else it will never be decrease */
469             block_Release( p_block );
470             return NULL;
471         }
472     }
473     else
474     {
475         if( p_sys->b_hurry_up )
476             p_context->skip_frame = p_sys->i_skip_frame;
477         if( !(p_block->i_flags & BLOCK_FLAG_PREROLL) )
478             b_drawpicture = 1;
479         else
480             b_drawpicture = 0;
481     }
482
483     if( p_context->width <= 0 || p_context->height <= 0 )
484     {
485         if( p_sys->b_hurry_up )
486             p_context->skip_frame = p_sys->i_skip_frame;
487         b_null_size = true;
488     }
489     else if( !b_drawpicture )
490     {
491         /* It creates broken picture
492          * FIXME either our parser or ffmpeg is broken */
493 #if 0
494         if( p_sys->b_hurry_up )
495             p_context->skip_frame = __MAX( p_context->skip_frame,
496                                                   AVDISCARD_NONREF );
497 #endif
498     }
499
500     /*
501      * Do the actual decoding now */
502
503     /* Don't forget that ffmpeg requires a little more bytes
504      * that the real frame size */
505     if( p_block->i_buffer > 0 )
506     {
507         p_sys->b_flush = ( p_block->i_flags & BLOCK_FLAG_END_OF_SEQUENCE ) != 0;
508
509         p_block = block_Realloc( p_block, 0,
510                             p_block->i_buffer + FF_INPUT_BUFFER_PADDING_SIZE );
511         if( !p_block )
512             return NULL;
513         p_block->i_buffer -= FF_INPUT_BUFFER_PADDING_SIZE;
514         *pp_block = p_block;
515         memset( p_block->p_buffer + p_block->i_buffer, 0,
516                 FF_INPUT_BUFFER_PADDING_SIZE );
517     }
518
519     while( p_block->i_buffer > 0 || p_sys->b_flush )
520     {
521         int i_used, b_gotpicture;
522         picture_t *p_pic;
523
524         /* Set the PTS/DTS in the context reordered_opaque field */
525         if( p_block->i_pts > VLC_TS_INVALID  )
526             p_context->reordered_opaque = (p_block->i_pts << 1) | 0;
527         else if( p_block->i_dts > VLC_TS_INVALID )
528             p_context->reordered_opaque = (p_block->i_dts << 1) | 1;
529         else
530             p_context->reordered_opaque = INT64_MIN;
531
532         /* Make sure we don't reuse the same timestamps twice */
533         p_block->i_pts =
534         p_block->i_dts = VLC_TS_INVALID;
535
536
537         i_used = avcodec_decode_video( p_context, p_sys->p_ff_pic,
538                                        &b_gotpicture,
539                                        p_block->i_buffer <= 0 && p_sys->b_flush ? NULL : p_block->p_buffer, p_block->i_buffer );
540
541         if( b_null_size && !p_sys->b_flush &&
542             p_context->width > 0 && p_context->height > 0 )
543         {
544             /* Reparse it to not drop the I frame */
545             b_null_size = false;
546             if( p_sys->b_hurry_up )
547                 p_context->skip_frame = p_sys->i_skip_frame;
548             i_used = avcodec_decode_video( p_context, p_sys->p_ff_pic,
549                                            &b_gotpicture, p_block->p_buffer,
550                                            p_block->i_buffer );
551         }
552
553         if( p_sys->b_flush )
554             p_sys->b_first_frame = true;
555
556         if( p_block->i_buffer <= 0 )
557             p_sys->b_flush = false;
558
559         if( i_used < 0 )
560         {
561             if( b_drawpicture )
562                 msg_Warn( p_dec, "cannot decode one frame (%zu bytes)",
563                           p_block->i_buffer );
564             block_Release( p_block );
565             return NULL;
566         }
567         else if( i_used > p_block->i_buffer )
568         {
569             i_used = p_block->i_buffer;
570         }
571
572         /* Consumed bytes */
573         p_block->i_buffer -= i_used;
574         p_block->p_buffer += i_used;
575
576         /* Nothing to display */
577         if( !b_gotpicture )
578         {
579             if( i_used == 0 ) break;
580             continue;
581         }
582
583         /* Compute the PTS */
584         mtime_t i_pts = VLC_TS_INVALID;
585         if( p_sys->p_ff_pic->reordered_opaque != INT64_MIN )
586         {
587             mtime_t i_ts = p_sys->p_ff_pic->reordered_opaque >> 1;
588             bool    b_dts = p_sys->p_ff_pic->reordered_opaque & 1;
589             if( b_dts )
590             {
591                 if( !p_context->has_b_frames ||
592                     !p_sys->b_has_b_frames ||
593                     !p_sys->p_ff_pic->reference ||
594                     p_sys->i_pts <= VLC_TS_INVALID )
595                     i_pts = i_ts;
596             }
597             else
598             {
599                 i_pts = i_ts;
600             }
601         }
602         if( i_pts <= VLC_TS_INVALID )
603             i_pts = p_sys->i_pts;
604
605         /* Interpolate the next PTS */
606         if( i_pts > VLC_TS_INVALID )
607             p_sys->i_pts = i_pts;
608         if( p_sys->i_pts > VLC_TS_INVALID )
609         {
610             /* interpolate the next PTS */
611             if( p_dec->fmt_in.video.i_frame_rate > 0 &&
612                 p_dec->fmt_in.video.i_frame_rate_base > 0 )
613             {
614                 p_sys->i_pts += INT64_C(1000000) *
615                     (2 + p_sys->p_ff_pic->repeat_pict) *
616                     p_dec->fmt_in.video.i_frame_rate_base /
617                     (2 * p_dec->fmt_in.video.i_frame_rate);
618             }
619             else if( p_context->time_base.den > 0 )
620             {
621 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(52,20,0)
622                 int i_tick = p_context->ticks_per_frame;
623                 if( i_tick <= 0 )
624                     i_tick = 1;
625 #else
626                 int i_tick = 1;
627 #endif
628
629                 p_sys->i_pts += INT64_C(1000000) *
630                     (2 + p_sys->p_ff_pic->repeat_pict) *
631                     i_tick * p_context->time_base.num /
632                     (2 * p_context->time_base.den);
633             }
634         }
635
636         /* Update frame late count (except when doing preroll) */
637         mtime_t i_display_date = 0;
638         if( !(p_block->i_flags & BLOCK_FLAG_PREROLL) )
639             i_display_date = decoder_GetDisplayDate( p_dec, i_pts );
640
641         if( i_display_date > 0 && i_display_date <= mdate() )
642         {
643             p_sys->i_late_frames++;
644             if( p_sys->i_late_frames == 1 )
645                 p_sys->i_late_frames_start = mdate();
646         }
647         else
648         {
649             p_sys->i_late_frames = 0;
650         }
651
652         if( !b_drawpicture || ( !p_sys->p_va && !p_sys->p_ff_pic->linesize[0] ) )
653             continue;
654
655         if( !p_sys->p_ff_pic->opaque )
656         {
657             /* Get a new picture */
658             p_pic = ffmpeg_NewPictBuf( p_dec, p_context );
659             if( !p_pic )
660             {
661                 block_Release( p_block );
662                 return NULL;
663             }
664
665             /* Fill p_picture_t from AVVideoFrame and do chroma conversion
666              * if needed */
667             ffmpeg_CopyPicture( p_dec, p_pic, p_sys->p_ff_pic );
668         }
669         else
670         {
671             p_pic = (picture_t *)p_sys->p_ff_pic->opaque;
672             decoder_LinkPicture( p_dec, p_pic );
673         }
674
675         /* Sanity check (seems to be needed for some streams) */
676         if( p_sys->p_ff_pic->pict_type == FF_B_TYPE )
677         {
678             p_sys->b_has_b_frames = true;
679         }
680
681         if( !p_dec->fmt_in.video.i_sar_num || !p_dec->fmt_in.video.i_sar_den )
682         {
683             /* Fetch again the aspect ratio in case it changed */
684             p_dec->fmt_out.video.i_sar_num
685                 = p_context->sample_aspect_ratio.num;
686             p_dec->fmt_out.video.i_sar_den
687                 = p_context->sample_aspect_ratio.den;
688
689             if( !p_dec->fmt_out.video.i_sar_num || !p_dec->fmt_out.video.i_sar_den )
690             {
691                 p_dec->fmt_out.video.i_sar_num = 1;
692                 p_dec->fmt_out.video.i_sar_den = 1;
693             }
694         }
695
696         /* Send decoded frame to vout */
697         if( i_pts > VLC_TS_INVALID)
698         {
699             p_pic->date = i_pts;
700
701             if( p_sys->b_first_frame )
702             {
703                 /* Hack to force display of still pictures */
704                 p_sys->b_first_frame = false;
705                 p_pic->b_force = true;
706             }
707
708             p_pic->i_nb_fields = 2 + p_sys->p_ff_pic->repeat_pict;
709             p_pic->b_progressive = !p_sys->p_ff_pic->interlaced_frame;
710             p_pic->b_top_field_first = p_sys->p_ff_pic->top_field_first;
711
712             p_pic->i_qstride = p_sys->p_ff_pic->qstride;
713             int i_mb_h = ( p_pic->format.i_height + 15 ) / 16;
714             p_pic->p_q = malloc( p_pic->i_qstride * i_mb_h );
715             memcpy( p_pic->p_q, p_sys->p_ff_pic->qscale_table,
716                     p_pic->i_qstride * i_mb_h );
717             switch( p_sys->p_ff_pic->qscale_type )
718             {
719                 case FF_QSCALE_TYPE_MPEG1:
720                     p_pic->i_qtype = QTYPE_MPEG1;
721                     break;
722                 case FF_QSCALE_TYPE_MPEG2:
723                     p_pic->i_qtype = QTYPE_MPEG2;
724                     break;
725                 case FF_QSCALE_TYPE_H264:
726                     p_pic->i_qtype = QTYPE_H264;
727                     break;
728             }
729
730             return p_pic;
731         }
732         else
733         {
734             decoder_DeletePicture( p_dec, p_pic );
735         }
736     }
737
738     block_Release( p_block );
739     return NULL;
740 }
741
742 /*****************************************************************************
743  * EndVideo: decoder destruction
744  *****************************************************************************
745  * This function is called when the thread ends after a successful
746  * initialization.
747  *****************************************************************************/
748 void EndVideoDec( decoder_t *p_dec )
749 {
750     decoder_sys_t *p_sys = p_dec->p_sys;
751
752     /* do not flush buffers if codec hasn't been opened (theora/vorbis/VC1) */
753     if( p_sys->p_context->codec )
754         avcodec_flush_buffers( p_sys->p_context );
755
756     if( p_sys->p_ff_pic ) av_free( p_sys->p_ff_pic );
757
758     if( p_sys->p_va )
759         vlc_va_Delete( p_sys->p_va );
760 }
761
762 /*****************************************************************************
763  * ffmpeg_InitCodec: setup codec extra initialization data for ffmpeg
764  *****************************************************************************/
765 static void ffmpeg_InitCodec( decoder_t *p_dec )
766 {
767     decoder_sys_t *p_sys = p_dec->p_sys;
768     int i_size = p_dec->fmt_in.i_extra;
769
770     if( !i_size ) return;
771
772     if( p_sys->i_codec_id == CODEC_ID_SVQ3 )
773     {
774         uint8_t *p;
775
776         p_sys->p_context->extradata_size = i_size + 12;
777         p = p_sys->p_context->extradata  =
778             malloc( p_sys->p_context->extradata_size );
779         if( !p )
780             return;
781
782         memcpy( &p[0],  "SVQ3", 4 );
783         memset( &p[4], 0, 8 );
784         memcpy( &p[12], p_dec->fmt_in.p_extra, i_size );
785
786         /* Now remove all atoms before the SMI one */
787         if( p_sys->p_context->extradata_size > 0x5a &&
788             strncmp( (char*)&p[0x56], "SMI ", 4 ) )
789         {
790             uint8_t *psz = &p[0x52];
791
792             while( psz < &p[p_sys->p_context->extradata_size - 8] )
793             {
794                 int i_size = GetDWBE( psz );
795                 if( i_size <= 1 )
796                 {
797                     /* FIXME handle 1 as long size */
798                     break;
799                 }
800                 if( !strncmp( (char*)&psz[4], "SMI ", 4 ) )
801                 {
802                     memmove( &p[0x52], psz,
803                              &p[p_sys->p_context->extradata_size] - psz );
804                     break;
805                 }
806
807                 psz += i_size;
808             }
809         }
810     }
811     else
812     {
813         p_sys->p_context->extradata_size = i_size;
814         p_sys->p_context->extradata =
815             malloc( i_size + FF_INPUT_BUFFER_PADDING_SIZE );
816         if( p_sys->p_context->extradata )
817         {
818             memcpy( p_sys->p_context->extradata,
819                     p_dec->fmt_in.p_extra, i_size );
820             memset( &((uint8_t*)p_sys->p_context->extradata)[i_size],
821                     0, FF_INPUT_BUFFER_PADDING_SIZE );
822         }
823     }
824 }
825
826 /*****************************************************************************
827  * ffmpeg_OpenCodec:
828  *****************************************************************************/
829 static int ffmpeg_OpenCodec( decoder_t *p_dec )
830 {
831     decoder_sys_t *p_sys = p_dec->p_sys;
832
833     if( p_sys->p_context->extradata_size <= 0 )
834     {
835         if( p_sys->i_codec_id == CODEC_ID_VC1 ||
836             p_sys->i_codec_id == CODEC_ID_VORBIS ||
837             p_sys->i_codec_id == CODEC_ID_THEORA )
838         {
839             msg_Warn( p_dec, "waiting for extra data for codec %s",
840                       p_sys->psz_namecodec );
841             return 1;
842         }
843     }
844     p_sys->p_context->width  = p_dec->fmt_in.video.i_width;
845     p_sys->p_context->height = p_dec->fmt_in.video.i_height;
846     p_sys->p_context->bits_per_coded_sample = p_dec->fmt_in.video.i_bits_per_pixel;
847
848     int ret;
849     vlc_avcodec_lock();
850     ret = avcodec_open( p_sys->p_context, p_sys->p_codec );
851     vlc_avcodec_unlock();
852     if( ret < 0 )
853         return VLC_EGENERIC;
854     msg_Dbg( p_dec, "ffmpeg codec (%s) started", p_sys->psz_namecodec );
855
856     p_sys->b_delayed_open = false;
857
858     return VLC_SUCCESS;
859 }
860 /*****************************************************************************
861  * ffmpeg_CopyPicture: copy a picture from ffmpeg internal buffers to a
862  *                     picture_t structure (when not in direct rendering mode).
863  *****************************************************************************/
864 static void ffmpeg_CopyPicture( decoder_t *p_dec,
865                                 picture_t *p_pic, AVFrame *p_ff_pic )
866 {
867     decoder_sys_t *p_sys = p_dec->p_sys;
868
869     if( p_sys->p_va )
870     {
871         vlc_va_Extract( p_sys->p_va, p_pic, p_ff_pic );
872     }
873     else if( TestFfmpegChroma( p_sys->p_context->pix_fmt, -1 ) == VLC_SUCCESS )
874     {
875         int i_plane, i_size, i_line;
876         uint8_t *p_dst, *p_src;
877         int i_src_stride, i_dst_stride;
878
879         for( i_plane = 0; i_plane < p_pic->i_planes; i_plane++ )
880         {
881             p_src  = p_ff_pic->data[i_plane];
882             p_dst = p_pic->p[i_plane].p_pixels;
883             i_src_stride = p_ff_pic->linesize[i_plane];
884             i_dst_stride = p_pic->p[i_plane].i_pitch;
885
886             i_size = __MIN( i_src_stride, i_dst_stride );
887             for( i_line = 0; i_line < p_pic->p[i_plane].i_visible_lines;
888                  i_line++ )
889             {
890                 vlc_memcpy( p_dst, p_src, i_size );
891                 p_src += i_src_stride;
892                 p_dst += i_dst_stride;
893             }
894         }
895     }
896     else
897     {
898         msg_Err( p_dec, "don't know how to convert chroma %i",
899                  p_sys->p_context->pix_fmt );
900         p_dec->b_error = 1;
901     }
902 }
903
904 /*****************************************************************************
905  * ffmpeg_GetFrameBuf: callback used by ffmpeg to get a frame buffer.
906  *****************************************************************************
907  * It is used for direct rendering as well as to get the right PTS for each
908  * decoded picture (even in indirect rendering mode).
909  *****************************************************************************/
910 static int ffmpeg_GetFrameBuf( struct AVCodecContext *p_context,
911                                AVFrame *p_ff_pic )
912 {
913     decoder_t *p_dec = (decoder_t *)p_context->opaque;
914     decoder_sys_t *p_sys = p_dec->p_sys;
915     picture_t *p_pic;
916
917     /* */
918     p_ff_pic->reordered_opaque = p_context->reordered_opaque;
919     p_ff_pic->opaque = NULL;
920
921     if( p_sys->p_va )
922     {
923 #ifdef HAVE_AVCODEC_VA
924         /* hwaccel_context is not present in old fffmpeg version */
925         if( vlc_va_Setup( p_sys->p_va,
926                           &p_sys->p_context->hwaccel_context, &p_dec->fmt_out.video.i_chroma,
927                           p_sys->p_context->width, p_sys->p_context->height ) )
928         {
929             msg_Err( p_dec, "vlc_va_Setup failed" );
930             return -1;
931         }
932 #else
933         assert(0);
934 #endif
935
936         /* */
937         p_ff_pic->type = FF_BUFFER_TYPE_USER;
938         /* FIXME what is that, should give good value */
939         p_ff_pic->age = 256*256*256*64; // FIXME FIXME from ffmpeg
940
941         if( vlc_va_Get( p_sys->p_va, p_ff_pic ) )
942         {
943             msg_Err( p_dec, "VaGrabSurface failed" );
944             return -1;
945         }
946         return 0;
947     }
948     else if( !p_sys->b_direct_rendering )
949     {
950         /* Not much to do in indirect rendering mode. */
951         return avcodec_default_get_buffer( p_context, p_ff_pic );
952     }
953
954     /* Some codecs set pix_fmt only after the 1st frame has been decoded,
955      * so we need to check for direct rendering again. */
956
957     int i_width = p_sys->p_context->width;
958     int i_height = p_sys->p_context->height;
959     avcodec_align_dimensions( p_sys->p_context, &i_width, &i_height );
960
961     if( GetVlcChroma( &p_dec->fmt_out.video, p_context->pix_fmt ) != VLC_SUCCESS ||
962         p_context->pix_fmt == PIX_FMT_PAL8 )
963         goto no_dr;
964
965     p_dec->fmt_out.i_codec = p_dec->fmt_out.video.i_chroma;
966
967     /* Get a new picture */
968     p_pic = ffmpeg_NewPictBuf( p_dec, p_sys->p_context );
969     if( !p_pic )
970         goto no_dr;
971     bool b_compatible = true;
972     if( p_pic->p[0].i_pitch / p_pic->p[0].i_pixel_pitch < i_width ||
973         p_pic->p[0].i_lines < i_height )
974         b_compatible = false;
975     for( int i = 0; i < p_pic->i_planes && b_compatible; i++ )
976     {
977         unsigned i_align;
978         switch( p_sys->i_codec_id )
979         {
980         case CODEC_ID_SVQ1:
981         case CODEC_ID_VP5:
982         case CODEC_ID_VP6:
983         case CODEC_ID_VP6F:
984         case CODEC_ID_VP6A:
985             i_align = 16;
986             break;
987         default:
988             i_align = i == 0 ? 16 : 8;
989             break;
990         }
991         if( p_pic->p[i].i_pitch % i_align )
992             b_compatible = false;
993         if( (intptr_t)p_pic->p[i].p_pixels % i_align )
994             b_compatible = false;
995     }
996     if( p_context->pix_fmt == PIX_FMT_YUV422P && b_compatible )
997     {
998         if( 2 * p_pic->p[1].i_pitch != p_pic->p[0].i_pitch ||
999             2 * p_pic->p[2].i_pitch != p_pic->p[0].i_pitch )
1000             b_compatible = false;
1001     }
1002     if( !b_compatible )
1003     {
1004         decoder_DeletePicture( p_dec, p_pic );
1005         goto no_dr;
1006     }
1007
1008     if( p_sys->i_direct_rendering_used != 1 )
1009     {
1010         msg_Dbg( p_dec, "using direct rendering" );
1011         p_sys->i_direct_rendering_used = 1;
1012     }
1013
1014     p_sys->p_context->draw_horiz_band = NULL;
1015
1016     p_ff_pic->opaque = (void*)p_pic;
1017     p_ff_pic->type = FF_BUFFER_TYPE_USER;
1018     p_ff_pic->data[0] = p_pic->p[0].p_pixels;
1019     p_ff_pic->data[1] = p_pic->p[1].p_pixels;
1020     p_ff_pic->data[2] = p_pic->p[2].p_pixels;
1021     p_ff_pic->data[3] = NULL; /* alpha channel but I'm not sure */
1022
1023     p_ff_pic->linesize[0] = p_pic->p[0].i_pitch;
1024     p_ff_pic->linesize[1] = p_pic->p[1].i_pitch;
1025     p_ff_pic->linesize[2] = p_pic->p[2].i_pitch;
1026     p_ff_pic->linesize[3] = 0;
1027
1028     /* FIXME what is that, should give good value */
1029     p_ff_pic->age = 256*256*256*64; // FIXME FIXME from ffmpeg
1030
1031     return 0;
1032
1033 no_dr:
1034     if( p_sys->i_direct_rendering_used != 0 )
1035     {
1036         msg_Warn( p_dec, "disabling direct rendering" );
1037         p_sys->i_direct_rendering_used = 0;
1038     }
1039     return avcodec_default_get_buffer( p_context, p_ff_pic );
1040 }
1041 static int  ffmpeg_ReGetFrameBuf( struct AVCodecContext *p_context, AVFrame *p_ff_pic )
1042 {
1043     p_ff_pic->reordered_opaque = p_context->reordered_opaque;
1044
1045     /* We always use default reget function, it works perfectly fine */
1046     return avcodec_default_reget_buffer( p_context, p_ff_pic );
1047 }
1048
1049 static void ffmpeg_ReleaseFrameBuf( struct AVCodecContext *p_context,
1050                                     AVFrame *p_ff_pic )
1051 {
1052     decoder_t *p_dec = (decoder_t *)p_context->opaque;
1053     decoder_sys_t *p_sys = p_dec->p_sys;
1054
1055     if( p_sys->p_va )
1056     {
1057         vlc_va_Release( p_sys->p_va, p_ff_pic );
1058
1059         /* */
1060         for( int i = 0; i < 4; i++ )
1061             p_ff_pic->data[i] = NULL;
1062     }
1063     else if( !p_ff_pic->opaque )
1064     {
1065         avcodec_default_release_buffer( p_context, p_ff_pic );
1066     }
1067     else
1068     {
1069         picture_t *p_pic = (picture_t*)p_ff_pic->opaque;
1070
1071         decoder_UnlinkPicture( p_dec, p_pic );
1072
1073         /* */
1074         for( int i = 0; i < 4; i++ )
1075             p_ff_pic->data[i] = NULL;
1076     }
1077 }
1078
1079 #ifdef HAVE_AVCODEC_VA
1080 static enum PixelFormat ffmpeg_GetFormat( AVCodecContext *p_codec,
1081                                           const enum PixelFormat *pi_fmt )
1082 {
1083     decoder_t *p_dec = p_codec->opaque;
1084     decoder_sys_t *p_sys = p_dec->p_sys;
1085
1086     if( p_sys->p_va )
1087     {
1088         vlc_va_Delete( p_sys->p_va );
1089         p_sys->p_va = NULL;
1090     }
1091
1092     /* Try too look for a supported hw acceleration */
1093     for( int i = 0; pi_fmt[i] != PIX_FMT_NONE; i++ )
1094     {
1095         static const char *ppsz_name[PIX_FMT_NB] = {
1096             [PIX_FMT_VDPAU_H264] = "PIX_FMT_VDPAU_H264",
1097             [PIX_FMT_VAAPI_IDCT] = "PIX_FMT_VAAPI_IDCT",
1098             [PIX_FMT_VAAPI_VLD] = "PIX_FMT_VAAPI_VLD",
1099             [PIX_FMT_VAAPI_MOCO] = "PIX_FMT_VAAPI_MOCO",
1100 #ifdef HAVE_AVCODEC_DXVA2
1101             [PIX_FMT_DXVA2_VLD] = "PIX_FMT_DXVA2_VLD",
1102 #endif
1103             [PIX_FMT_YUYV422] = "PIX_FMT_YUYV422",
1104             [PIX_FMT_YUV420P] = "PIX_FMT_YUV420P",
1105         };
1106         msg_Dbg( p_dec, "Available decoder output format %d (%s)", pi_fmt[i], ppsz_name[pi_fmt[i]] ?: "Unknown" );
1107
1108         /* Only VLD supported */
1109         if( pi_fmt[i] == PIX_FMT_VAAPI_VLD )
1110         {
1111 #ifdef HAVE_AVCODEC_VAAPI
1112             msg_Dbg( p_dec, "Trying VA API" );
1113             p_sys->p_va = vlc_va_NewVaapi( p_sys->i_codec_id );
1114             if( !p_sys->p_va )
1115                 msg_Warn( p_dec, "Failed to open VA API" );
1116 #else
1117             continue;
1118 #endif
1119         }
1120 #ifdef HAVE_AVCODEC_DXVA2
1121         if( pi_fmt[i] == PIX_FMT_DXVA2_VLD )
1122         {
1123             msg_Dbg( p_dec, "Trying DXVA2" );
1124             p_sys->p_va = vlc_va_NewDxva2( VLC_OBJECT(p_dec), p_sys->i_codec_id );
1125             if( !p_sys->p_va )
1126                 msg_Warn( p_dec, "Failed to open DXVA2" );
1127         }
1128 #endif
1129
1130         if( p_sys->p_va &&
1131             p_sys->p_context->width > 0 && p_sys->p_context->height > 0 )
1132         {
1133             /* We try to call vlc_va_Setup when possible to detect errors when
1134              * possible (later is too late) */
1135             if( vlc_va_Setup( p_sys->p_va,
1136                               &p_sys->p_context->hwaccel_context,
1137                               &p_dec->fmt_out.video.i_chroma,
1138                               p_sys->p_context->width, p_sys->p_context->height ) )
1139             {
1140                 msg_Err( p_dec, "vlc_va_Setup failed" );
1141                 vlc_va_Delete( p_sys->p_va );
1142                 p_sys->p_va = NULL;
1143             }
1144         }
1145
1146         if( p_sys->p_va )
1147         {
1148             if( p_sys->p_va->description )
1149                 msg_Info( p_dec, "Using %s for hardware decoding.", p_sys->p_va->description );
1150
1151             /* FIXME this will disabled direct rendering
1152              * even if a new pixel format is renegociated
1153              */
1154             p_sys->b_direct_rendering = false;
1155             p_sys->p_context->draw_horiz_band = NULL;
1156             return pi_fmt[i];
1157         }
1158     }
1159
1160     /* Fallback to default behaviour */
1161     return avcodec_default_get_format( p_codec, pi_fmt );
1162 }
1163 #endif
1164