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