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