]> git.sesse.net Git - vlc/blob - modules/codec/avcodec/video.c
1ba84781832d5582ab313026b8f1666bff788f45
[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_vout.h>
35 #include <vlc_input.h>                  /* hmmm, just for INPUT_RATE_DEFAULT */
36 #include <vlc_codecs.h>                               /* BITMAPINFOHEADER */
37
38 /* ffmpeg header */
39 #ifdef HAVE_LIBAVCODEC_AVCODEC_H
40 #   include <libavcodec/avcodec.h>
41 #elif defined(HAVE_FFMPEG_AVCODEC_H)
42 #   include <ffmpeg/avcodec.h>
43 #else
44 #   include <avcodec.h>
45 #endif
46
47 #include "avcodec.h"
48
49 /*****************************************************************************
50  * decoder_sys_t : decoder descriptor
51  *****************************************************************************/
52 struct decoder_sys_t
53 {
54     FFMPEG_COMMON_MEMBERS
55
56     /* Video decoder specific part */
57     mtime_t input_pts;
58     mtime_t input_dts;
59     mtime_t i_pts;
60
61     AVFrame          *p_ff_pic;
62     BITMAPINFOHEADER *p_format;
63
64     /* for frame skipping algo */
65     int b_hurry_up;
66     enum AVDiscard i_skip_frame;
67     enum AVDiscard i_skip_idct;
68
69     /* how many decoded frames are late */
70     int     i_late_frames;
71     mtime_t i_late_frames_start;
72
73     /* for direct rendering */
74     int b_direct_rendering;
75
76     bool b_has_b_frames;
77
78     /* Hack to force display of still pictures */
79     bool b_first_frame;
80
81     int i_buffer_orig, i_buffer;
82     char *p_buffer_orig, *p_buffer;
83 };
84
85 /* FIXME (dummy palette for now) */
86 static AVPaletteControl palette_control;
87
88 /*****************************************************************************
89  * Local prototypes
90  *****************************************************************************/
91 static void ffmpeg_InitCodec      ( decoder_t * );
92 static void ffmpeg_CopyPicture    ( decoder_t *, picture_t *, AVFrame * );
93 static int  ffmpeg_GetFrameBuf    ( struct AVCodecContext *, AVFrame * );
94 static int  ffmpeg_ReGetFrameBuf( struct AVCodecContext *, AVFrame * );
95 static void ffmpeg_ReleaseFrameBuf( struct AVCodecContext *, AVFrame * );
96
97 static uint32_t ffmpeg_CodecTag( vlc_fourcc_t fcc )
98 {
99     uint8_t *p = (uint8_t*)&fcc;
100     return p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
101 }
102
103 /*****************************************************************************
104  * Local Functions
105  *****************************************************************************/
106 static uint32_t ffmpeg_PixFmtToChroma( int i_ff_chroma )
107 {
108     switch( i_ff_chroma )
109     {
110     case PIX_FMT_YUV420P:
111     case PIX_FMT_YUVJ420P: /* Hacky but better then chroma conversion */
112         return VLC_FOURCC('I','4','2','0');
113     case PIX_FMT_YUV422P:
114     case PIX_FMT_YUVJ422P: /* Hacky but better then chroma conversion */
115         return VLC_FOURCC('I','4','2','2');
116     case PIX_FMT_YUV444P:
117     case PIX_FMT_YUVJ444P: /* Hacky but better then chroma conversion */
118         return VLC_FOURCC('I','4','4','4');
119
120     case PIX_FMT_YUV422:
121         return VLC_FOURCC('Y','U','Y','2');
122
123 #if defined(WORDS_BIGENDIAN)
124     case PIX_FMT_BGR8:
125         return VLC_FOURCC('R','G','B','8');
126     case PIX_FMT_BGR555:
127         return VLC_FOURCC('R','V','1','5');
128     case PIX_FMT_BGR565:
129         return VLC_FOURCC('R','V','1','6');
130     case PIX_FMT_BGR24:
131         return VLC_FOURCC('R','V','2','4');
132 #else
133 #if defined(PIX_FMT_RGB8)
134     case PIX_FMT_RGB8:
135         return VLC_FOURCC('R','G','B','8');
136 #endif
137     case PIX_FMT_RGB555:
138         return VLC_FOURCC('R','V','1','5');
139     case PIX_FMT_RGB565:
140         return VLC_FOURCC('R','V','1','6');
141     case PIX_FMT_RGB24:
142         return VLC_FOURCC('R','V','2','4');
143 #endif
144     case PIX_FMT_RGBA32:
145         return VLC_FOURCC('R','V','3','2');
146 #ifdef PIX_FMT_RGBA
147     case PIX_FMT_RGBA:
148         return VLC_FOURCC('R','G','B','A');
149 #endif
150     case PIX_FMT_GRAY8:
151         return VLC_FOURCC('G','R','E','Y');
152
153     case PIX_FMT_YUV410P:
154     case PIX_FMT_YUV411P:
155     default:
156         return 0;
157     }
158 }
159
160 /* Returns a new picture buffer */
161 static inline picture_t *ffmpeg_NewPictBuf( decoder_t *p_dec,
162                                             AVCodecContext *p_context )
163 {
164     picture_t *p_pic;
165
166     p_dec->fmt_out.video.i_width = p_context->width;
167     p_dec->fmt_out.video.i_height = p_context->height;
168     p_dec->fmt_out.i_codec = ffmpeg_PixFmtToChroma( p_context->pix_fmt );
169
170     if( !p_context->width || !p_context->height )
171     {
172         return NULL; /* invalid display size */
173     }
174
175     if( !p_dec->fmt_out.i_codec )
176     {
177         /* we make conversion if possible*/
178         p_dec->fmt_out.i_codec = VLC_FOURCC('I','4','2','0');
179     }
180
181     /* If an aspect-ratio was specified in the input format then force it */
182     if( p_dec->fmt_in.video.i_aspect )
183     {
184         p_dec->fmt_out.video.i_aspect = p_dec->fmt_in.video.i_aspect;
185     }
186     else
187     {
188         p_dec->fmt_out.video.i_aspect =
189             VOUT_ASPECT_FACTOR * ( av_q2d(p_context->sample_aspect_ratio) *
190                 p_context->width / p_context->height );
191         p_dec->fmt_out.video.i_sar_num = p_context->sample_aspect_ratio.num;
192         p_dec->fmt_out.video.i_sar_den = p_context->sample_aspect_ratio.den;
193
194         if( p_dec->fmt_out.video.i_aspect == 0 )
195         {
196             p_dec->fmt_out.video.i_aspect =
197                 VOUT_ASPECT_FACTOR * p_context->width / p_context->height;
198         }
199     }
200
201     if( p_dec->fmt_out.video.i_frame_rate > 0 &&
202         p_dec->fmt_out.video.i_frame_rate_base > 0 )
203     {
204         p_dec->fmt_out.video.i_frame_rate =
205             p_dec->fmt_in.video.i_frame_rate;
206         p_dec->fmt_out.video.i_frame_rate_base =
207             p_dec->fmt_in.video.i_frame_rate_base;
208     }
209     else if( p_context->time_base.num > 0 && p_context->time_base.den > 0 )
210     {
211         p_dec->fmt_out.video.i_frame_rate = p_context->time_base.den;
212         p_dec->fmt_out.video.i_frame_rate_base = p_context->time_base.num;
213     }
214
215     p_pic = p_dec->pf_vout_buffer_new( p_dec );
216
217     return p_pic;
218 }
219
220 /*****************************************************************************
221  * InitVideo: initialize the video decoder
222  *****************************************************************************
223  * the ffmpeg codec will be opened, some memory allocated. The vout is not yet
224  * opened (done after the first decoded frame).
225  *****************************************************************************/
226 int InitVideoDec( decoder_t *p_dec, AVCodecContext *p_context,
227                       AVCodec *p_codec, int i_codec_id, const char *psz_namecodec )
228 {
229     decoder_sys_t *p_sys;
230     vlc_value_t val;
231
232     /* Allocate the memory needed to store the decoder's structure */
233     if( ( p_dec->p_sys = p_sys =
234           (decoder_sys_t *)malloc(sizeof(decoder_sys_t)) ) == NULL )
235     {
236         return VLC_ENOMEM;
237     }
238     memset( p_sys, 0, sizeof(decoder_sys_t) );
239
240     p_dec->p_sys->p_context = p_context;
241     p_dec->p_sys->p_codec = p_codec;
242     p_dec->p_sys->i_codec_id = i_codec_id;
243     p_dec->p_sys->psz_namecodec = psz_namecodec;
244     p_sys->p_ff_pic = avcodec_alloc_frame();
245
246     /* ***** Fill p_context with init values ***** */
247     p_sys->p_context->codec_tag = ffmpeg_CodecTag( p_dec->fmt_in.i_codec );
248     p_sys->p_context->width  = p_dec->fmt_in.video.i_width;
249     p_sys->p_context->height = p_dec->fmt_in.video.i_height;
250     p_sys->p_context->bits_per_sample = p_dec->fmt_in.video.i_bits_per_pixel;
251
252     /*  ***** Get configuration of ffmpeg plugin ***** */
253     p_sys->p_context->workaround_bugs =
254         config_GetInt( p_dec, "ffmpeg-workaround-bugs" );
255     p_sys->p_context->error_resilience =
256         config_GetInt( p_dec, "ffmpeg-error-resilience" );
257
258     var_Create( p_dec, "grayscale", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
259     var_Get( p_dec, "grayscale", &val );
260     if( val.b_bool ) p_sys->p_context->flags |= CODEC_FLAG_GRAY;
261
262     var_Create( p_dec, "ffmpeg-vismv", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
263     var_Get( p_dec, "ffmpeg-vismv", &val );
264     if( val.i_int ) p_sys->p_context->debug_mv = val.i_int;
265
266     var_Create( p_dec, "ffmpeg-lowres", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
267     var_Get( p_dec, "ffmpeg-lowres", &val );
268     if( val.i_int > 0 && val.i_int <= 2 ) p_sys->p_context->lowres = val.i_int;
269
270     var_Create( p_dec, "ffmpeg-skiploopfilter",
271                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
272     var_Get( p_dec, "ffmpeg-skiploopfilter", &val );
273     if( val.i_int > 0 ) p_sys->p_context->skip_loop_filter = AVDISCARD_NONREF;
274     if( val.i_int > 1 ) p_sys->p_context->skip_loop_filter = AVDISCARD_BIDIR;
275     if( val.i_int > 2 ) p_sys->p_context->skip_loop_filter = AVDISCARD_NONKEY;
276     if( val.i_int > 3 ) p_sys->p_context->skip_loop_filter = AVDISCARD_ALL;
277
278     /* ***** ffmpeg frame skipping ***** */
279     var_Create( p_dec, "ffmpeg-hurry-up", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
280     var_Get( p_dec, "ffmpeg-hurry-up", &val );
281     p_sys->b_hurry_up = val.b_bool;
282
283     var_Create( p_dec, "ffmpeg-skip-frame", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
284     var_Get( p_dec, "ffmpeg-skip-frame", &val );
285     switch( val.i_int )
286     {
287         case -1:
288             p_sys->p_context->skip_frame = AVDISCARD_NONE;
289             break;
290         case 0:
291             p_sys->p_context->skip_frame = AVDISCARD_DEFAULT;
292             break;
293         case 1:
294             p_sys->p_context->skip_frame = AVDISCARD_BIDIR;
295             break;
296         case 2:
297             p_sys->p_context->skip_frame = AVDISCARD_NONKEY;
298             break;
299         case 3:
300             p_sys->p_context->skip_frame = AVDISCARD_ALL;
301             break;
302         default:
303             p_sys->p_context->skip_frame = AVDISCARD_NONE;
304             break;
305     }
306     p_sys->i_skip_frame = p_sys->p_context->skip_frame;
307
308     var_Create( p_dec, "ffmpeg-skip-idct",  VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
309     var_Get( p_dec, "ffmpeg-skip-idct", &val );
310     switch( val.i_int )
311     {
312         case -1:
313             p_sys->p_context->skip_idct = AVDISCARD_NONE;
314             break;
315         case 0:
316             p_sys->p_context->skip_idct = AVDISCARD_DEFAULT;
317             break;
318         case 1:
319             p_sys->p_context->skip_idct = AVDISCARD_BIDIR;
320             break;
321         case 2:
322             p_sys->p_context->skip_idct = AVDISCARD_NONKEY;
323             break;
324         case 3:
325             p_sys->p_context->skip_idct = AVDISCARD_ALL;
326             break;
327         default:
328             p_sys->p_context->skip_idct = AVDISCARD_NONE;
329             break;
330     }
331     p_sys->i_skip_idct = p_sys->p_context->skip_idct;
332
333     /* ***** ffmpeg direct rendering ***** */
334     p_sys->b_direct_rendering = 0;
335     var_Create( p_dec, "ffmpeg-dr", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
336     var_Get( p_dec, "ffmpeg-dr", &val );
337     if( val.b_bool && (p_sys->p_codec->capabilities & CODEC_CAP_DR1) &&
338         /* Apparently direct rendering doesn't work with YUV422P */
339         p_sys->p_context->pix_fmt != PIX_FMT_YUV422P &&
340         /* H264 uses too many reference frames */
341         p_sys->i_codec_id != CODEC_ID_H264 &&
342         !p_sys->p_context->debug_mv )
343     {
344         /* Some codecs set pix_fmt only after the 1st frame has been decoded,
345          * so we need to do another check in ffmpeg_GetFrameBuf() */
346         p_sys->b_direct_rendering = 1;
347     }
348
349     /* ffmpeg doesn't properly release old pictures when frames are skipped */
350     //if( p_sys->b_hurry_up ) p_sys->b_direct_rendering = 0;
351     if( p_sys->b_direct_rendering )
352     {
353         msg_Dbg( p_dec, "using direct rendering" );
354         p_sys->p_context->flags |= CODEC_FLAG_EMU_EDGE;
355     }
356
357     /* Always use our get_buffer wrapper so we can calculate the
358      * PTS correctly */
359     p_sys->p_context->get_buffer = ffmpeg_GetFrameBuf;
360     p_sys->p_context->reget_buffer = ffmpeg_ReGetFrameBuf;
361     p_sys->p_context->release_buffer = ffmpeg_ReleaseFrameBuf;
362     p_sys->p_context->opaque = p_dec;
363
364     /* ***** init this codec with special data ***** */
365     ffmpeg_InitCodec( p_dec );
366
367     /* ***** misc init ***** */
368     p_sys->input_pts = p_sys->input_dts = 0;
369     p_sys->i_pts = 0;
370     p_sys->b_has_b_frames = false;
371     p_sys->b_first_frame = true;
372     p_sys->i_late_frames = 0;
373     p_sys->i_buffer = 0;
374     p_sys->i_buffer_orig = 1;
375     p_sys->p_buffer_orig = p_sys->p_buffer = malloc( p_sys->i_buffer_orig );
376     if( !p_sys->p_buffer_orig )
377     {
378         free( p_sys );
379         return VLC_ENOMEM;
380     }
381
382     /* Set output properties */
383     p_dec->fmt_out.i_cat = VIDEO_ES;
384     p_dec->fmt_out.i_codec = ffmpeg_PixFmtToChroma( p_context->pix_fmt );
385
386     /* Setup palette */
387     if( p_dec->fmt_in.video.p_palette )
388         p_sys->p_context->palctrl =
389             (AVPaletteControl *)p_dec->fmt_in.video.p_palette;
390     else if( p_sys->i_codec_id != CODEC_ID_MSVIDEO1 )
391         p_sys->p_context->palctrl = &palette_control;
392
393     /* ***** Open the codec ***** */
394     vlc_mutex_t *lock = var_AcquireMutex( "avcodec" );
395     if( lock == NULL )
396     {
397         free( p_sys->p_buffer_orig );
398         free( p_sys );
399         return VLC_ENOMEM;
400     }
401
402     if( avcodec_open( p_sys->p_context, p_sys->p_codec ) < 0 )
403     {
404         vlc_mutex_unlock( lock );
405         msg_Err( p_dec, "cannot open codec (%s)", p_sys->psz_namecodec );
406         free( p_sys->p_buffer_orig );
407         free( p_sys );
408         return VLC_EGENERIC;
409     }
410     vlc_mutex_unlock( lock );
411     msg_Dbg( p_dec, "ffmpeg codec (%s) started", p_sys->psz_namecodec );
412
413
414     return VLC_SUCCESS;
415 }
416
417 /*****************************************************************************
418  * DecodeVideo: Called to decode one or more frames
419  *****************************************************************************/
420 picture_t *DecodeVideo( decoder_t *p_dec, block_t **pp_block )
421 {
422     decoder_sys_t *p_sys = p_dec->p_sys;
423     int b_drawpicture;
424     int b_null_size = false;
425     block_t *p_block;
426
427     if( !pp_block || !*pp_block ) return NULL;
428
429     if( !p_sys->p_context->extradata_size && p_dec->fmt_in.i_extra )
430         ffmpeg_InitCodec( p_dec );
431
432     p_block = *pp_block;
433
434     if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
435     {
436         p_sys->i_buffer = 0;
437         p_sys->i_pts = 0; /* To make sure we recover properly */
438
439         p_sys->input_pts = p_sys->input_dts = 0;
440         p_sys->i_late_frames = 0;
441
442         block_Release( p_block );
443
444         //if( p_block->i_flags & BLOCK_FLAG_CORRUPTED )
445             //avcodec_flush_buffers( p_sys->p_context );
446         return NULL;
447     }
448
449     if( p_block->i_flags & BLOCK_FLAG_PREROLL )
450     {
451         /* Do not care about late frames when prerolling
452          * TODO avoid decoding of non reference frame
453          * (ie all B except for H264 where it depends only on nal_ref_idc) */
454         p_sys->i_late_frames = 0;
455     }
456
457     if( !p_dec->b_pace_control && (p_sys->i_late_frames > 0) &&
458         (mdate() - p_sys->i_late_frames_start > INT64_C(5000000)) )
459     {
460         if( p_sys->i_pts )
461         {
462             msg_Err( p_dec, "more than 5 seconds of late video -> "
463                      "dropping frame (computer too slow ?)" );
464             p_sys->i_pts = 0; /* To make sure we recover properly */
465         }
466         block_Release( p_block );
467         p_sys->i_late_frames--;
468         return NULL;
469     }
470
471     if( p_block->i_pts > 0 || p_block->i_dts > 0 )
472     {
473         p_sys->input_pts = p_block->i_pts;
474         p_sys->input_dts = p_block->i_dts;
475
476         /* Make sure we don't reuse the same timestamps twice */
477         p_block->i_pts = p_block->i_dts = 0;
478     }
479
480     /* A good idea could be to decode all I pictures and see for the other */
481     if( !p_dec->b_pace_control &&
482         p_sys->b_hurry_up &&
483         (p_sys->i_late_frames > 4) )
484     {
485         b_drawpicture = 0;
486         if( p_sys->i_late_frames < 8 )
487         {
488             p_sys->p_context->skip_frame =
489                     (p_sys->i_skip_frame <= AVDISCARD_BIDIR) ?
490                     AVDISCARD_BIDIR : p_sys->i_skip_frame;
491         }
492         else
493         {
494             /* picture too late, won't decode
495              * but break picture until a new I, and for mpeg4 ...*/
496             p_sys->i_late_frames--; /* needed else it will never be decrease */
497             block_Release( p_block );
498             p_sys->i_buffer = 0;
499             return NULL;
500         }
501     }
502     else
503     {
504         if( p_sys->b_hurry_up )
505             p_sys->p_context->skip_frame = p_sys->i_skip_frame;
506         if( !(p_block->i_flags & BLOCK_FLAG_PREROLL) )
507             b_drawpicture = 1;
508         else
509             b_drawpicture = 0;
510     }
511
512     if( p_sys->p_context->width <= 0 || p_sys->p_context->height <= 0 )
513     {
514         if( p_sys->b_hurry_up )
515             p_sys->p_context->skip_frame = p_sys->i_skip_frame;
516         b_null_size = true;
517     }
518
519     /*
520      * Do the actual decoding now
521      */
522
523     /* Don't forget that ffmpeg requires a little more bytes
524      * that the real frame size */
525     if( p_block->i_buffer > 0 )
526     {
527         p_sys->i_buffer = p_block->i_buffer;
528         if( p_sys->i_buffer + FF_INPUT_BUFFER_PADDING_SIZE >
529             p_sys->i_buffer_orig )
530         {
531             free( p_sys->p_buffer_orig );
532             p_sys->i_buffer_orig =
533                 p_block->i_buffer + FF_INPUT_BUFFER_PADDING_SIZE;
534             p_sys->p_buffer_orig = malloc( p_sys->i_buffer_orig );
535         }
536         p_sys->p_buffer = p_sys->p_buffer_orig;
537         p_sys->i_buffer = p_block->i_buffer;
538         if( !p_sys->p_buffer )
539         {
540             block_Release( p_block );
541             return NULL;
542         }
543         vlc_memcpy( p_sys->p_buffer, p_block->p_buffer, p_block->i_buffer );
544         memset( p_sys->p_buffer + p_block->i_buffer, 0,
545                 FF_INPUT_BUFFER_PADDING_SIZE );
546
547         p_block->i_buffer = 0;
548     }
549
550     while( p_sys->i_buffer > 0 )
551     {
552         int i_used, b_gotpicture;
553         picture_t *p_pic;
554
555         i_used = avcodec_decode_video( p_sys->p_context, p_sys->p_ff_pic,
556                                        &b_gotpicture,
557                                        (uint8_t*)p_sys->p_buffer, p_sys->i_buffer );
558         if( b_null_size && p_sys->p_context->width > 0 &&
559             p_sys->p_context->height > 0 )
560         {
561             /* Reparse it to not drop the I frame */
562             b_null_size = false;
563             if( p_sys->b_hurry_up )
564                 p_sys->p_context->skip_frame = p_sys->i_skip_frame;
565             i_used = avcodec_decode_video( p_sys->p_context, p_sys->p_ff_pic,
566                                            &b_gotpicture,
567                                            (uint8_t*)p_sys->p_buffer, p_sys->i_buffer );
568         }
569
570         if( i_used < 0 )
571         {
572             msg_Warn( p_dec, "cannot decode one frame (%d bytes)",
573                       p_sys->i_buffer );
574             block_Release( p_block );
575             return NULL;
576         }
577         else if( i_used > p_sys->i_buffer )
578         {
579             i_used = p_sys->i_buffer;
580         }
581
582         /* Consumed bytes */
583         p_sys->i_buffer -= i_used;
584         p_sys->p_buffer += i_used;
585
586         /* Nothing to display */
587         if( !b_gotpicture )
588         {
589             if( i_used == 0 ) break;
590             continue;
591         }
592
593         /* Update frame late count (except when doing preroll) */
594         if( p_sys->i_pts && decoder_GetDisplayDate(p_dec, p_sys->i_pts) <= mdate() &&
595             !(p_block->i_flags & BLOCK_FLAG_PREROLL) )
596         {
597             p_sys->i_late_frames++;
598             if( p_sys->i_late_frames == 1 )
599                 p_sys->i_late_frames_start = mdate();
600         }
601         else
602         {
603             p_sys->i_late_frames = 0;
604         }
605
606         if( !b_drawpicture || !p_sys->p_ff_pic->linesize[0] )
607         {
608             /* Do not display the picture */
609             p_pic = (picture_t *)p_sys->p_ff_pic->opaque;
610             if( !b_drawpicture && p_pic )
611                 p_dec->pf_vout_buffer_del( p_dec, p_pic );
612             continue;
613         }
614
615         if( !p_sys->p_ff_pic->opaque )
616         {
617             /* Get a new picture */
618             p_pic = ffmpeg_NewPictBuf( p_dec, p_sys->p_context );
619             if( !p_pic )
620             {
621                 block_Release( p_block );
622                 return NULL;
623             }
624
625             /* Fill p_picture_t from AVVideoFrame and do chroma conversion
626              * if needed */
627             ffmpeg_CopyPicture( p_dec, p_pic, p_sys->p_ff_pic );
628         }
629         else
630         {
631             p_pic = (picture_t *)p_sys->p_ff_pic->opaque;
632         }
633
634         /* Set the PTS */
635         if( p_sys->p_ff_pic->pts ) p_sys->i_pts = p_sys->p_ff_pic->pts;
636
637         /* Sanity check (seems to be needed for some streams) */
638         if( p_sys->p_ff_pic->pict_type == FF_B_TYPE )
639         {
640             p_sys->b_has_b_frames = true;
641         }
642
643         if( !p_dec->fmt_in.video.i_aspect )
644         {
645             /* Fetch again the aspect ratio in case it changed */
646             p_dec->fmt_out.video.i_aspect =
647                 VOUT_ASPECT_FACTOR
648                     * ( av_q2d(p_sys->p_context->sample_aspect_ratio)
649                     * p_sys->p_context->width / p_sys->p_context->height );
650             p_dec->fmt_out.video.i_sar_num
651                 = p_sys->p_context->sample_aspect_ratio.num;
652             p_dec->fmt_out.video.i_sar_den
653                 = p_sys->p_context->sample_aspect_ratio.den;
654
655             if( p_dec->fmt_out.video.i_aspect == 0 )
656             {
657                 p_dec->fmt_out.video.i_aspect = VOUT_ASPECT_FACTOR
658                     * p_sys->p_context->width / p_sys->p_context->height;
659             }
660         }
661
662         /* Send decoded frame to vout */
663         if( p_sys->i_pts )
664         {
665             p_pic->date = p_sys->i_pts;
666
667             /* interpolate the next PTS */
668             if( p_dec->fmt_in.video.i_frame_rate > 0 &&
669                 p_dec->fmt_in.video.i_frame_rate_base > 0 )
670             {
671                 p_sys->i_pts += INT64_C(1000000) *
672                     (2 + p_sys->p_ff_pic->repeat_pict) *
673                     p_dec->fmt_in.video.i_frame_rate_base *
674                     p_block->i_rate / INPUT_RATE_DEFAULT /
675                     (2 * p_dec->fmt_in.video.i_frame_rate);
676             }
677             else if( p_sys->p_context->time_base.den > 0 )
678             {
679                 p_sys->i_pts += INT64_C(1000000) *
680                     (2 + p_sys->p_ff_pic->repeat_pict) *
681                     p_sys->p_context->time_base.num *
682                     p_block->i_rate / INPUT_RATE_DEFAULT /
683                     (2 * p_sys->p_context->time_base.den);
684             }
685
686             if( p_sys->b_first_frame )
687             {
688                 /* Hack to force display of still pictures */
689                 p_sys->b_first_frame = false;
690                 p_pic->b_force = true;
691             }
692
693             p_pic->i_nb_fields = 2 + p_sys->p_ff_pic->repeat_pict;
694             p_pic->b_progressive = !p_sys->p_ff_pic->interlaced_frame;
695             p_pic->b_top_field_first = p_sys->p_ff_pic->top_field_first;
696
697             return p_pic;
698         }
699         else
700         {
701             p_dec->pf_vout_buffer_del( p_dec, p_pic );
702         }
703     }
704
705     block_Release( p_block );
706     return NULL;
707 }
708
709 /*****************************************************************************
710  * EndVideo: decoder destruction
711  *****************************************************************************
712  * This function is called when the thread ends after a successful
713  * initialization.
714  *****************************************************************************/
715 void EndVideoDec( decoder_t *p_dec )
716 {
717     decoder_sys_t *p_sys = p_dec->p_sys;
718
719     if( p_sys->p_ff_pic ) av_free( p_sys->p_ff_pic );
720     free( p_sys->p_buffer_orig );
721 }
722
723 /*****************************************************************************
724  * ffmpeg_InitCodec: setup codec extra initialization data for ffmpeg
725  *****************************************************************************/
726 static void ffmpeg_InitCodec( decoder_t *p_dec )
727 {
728     decoder_sys_t *p_sys = p_dec->p_sys;
729     int i_size = p_dec->fmt_in.i_extra;
730
731     if( !i_size ) return;
732
733     if( p_sys->i_codec_id == CODEC_ID_SVQ3 )
734     {
735         uint8_t *p;
736
737         p_sys->p_context->extradata_size = i_size + 12;
738         p = p_sys->p_context->extradata  =
739             malloc( p_sys->p_context->extradata_size );
740         if( !p )
741             return;
742
743         memcpy( &p[0],  "SVQ3", 4 );
744         memset( &p[4], 0, 8 );
745         memcpy( &p[12], p_dec->fmt_in.p_extra, i_size );
746
747         /* Now remove all atoms before the SMI one */
748         if( p_sys->p_context->extradata_size > 0x5a &&
749             strncmp( (char*)&p[0x56], "SMI ", 4 ) )
750         {
751             uint8_t *psz = &p[0x52];
752
753             while( psz < &p[p_sys->p_context->extradata_size - 8] )
754             {
755                 int i_size = GetDWBE( psz );
756                 if( i_size <= 1 )
757                 {
758                     /* FIXME handle 1 as long size */
759                     break;
760                 }
761                 if( !strncmp( (char*)&psz[4], "SMI ", 4 ) )
762                 {
763                     memmove( &p[0x52], psz,
764                              &p[p_sys->p_context->extradata_size] - psz );
765                     break;
766                 }
767
768                 psz += i_size;
769             }
770         }
771     }
772     else if( p_dec->fmt_in.i_codec == VLC_FOURCC( 'R', 'V', '1', '0' ) ||
773              p_dec->fmt_in.i_codec == VLC_FOURCC( 'R', 'V', '1', '3' ) ||
774              p_dec->fmt_in.i_codec == VLC_FOURCC( 'R', 'V', '2', '0' ) )
775     {
776         if( p_dec->fmt_in.i_extra == 8 )
777         {
778             p_sys->p_context->extradata_size = 8;
779             p_sys->p_context->extradata = malloc( 8 );
780             if( p_sys->p_context->extradata )
781             {
782                 memcpy( p_sys->p_context->extradata,
783                         p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra );
784                 p_sys->p_context->sub_id = ((uint32_t*)p_dec->fmt_in.p_extra)[1];
785
786                 msg_Warn( p_dec, "using extra data for RV codec sub_id=%08x",
787                           p_sys->p_context->sub_id );
788             }
789         }
790     }
791     else
792     {
793         p_sys->p_context->extradata_size = i_size;
794         p_sys->p_context->extradata =
795             malloc( i_size + FF_INPUT_BUFFER_PADDING_SIZE );
796         if( p_sys->p_context->extradata )
797         {
798             memcpy( p_sys->p_context->extradata,
799                     p_dec->fmt_in.p_extra, i_size );
800             memset( &((uint8_t*)p_sys->p_context->extradata)[i_size],
801                     0, FF_INPUT_BUFFER_PADDING_SIZE );
802         }
803     }
804 }
805
806 /*****************************************************************************
807  * ffmpeg_CopyPicture: copy a picture from ffmpeg internal buffers to a
808  *                     picture_t structure (when not in direct rendering mode).
809  *****************************************************************************/
810 static void ffmpeg_CopyPicture( decoder_t *p_dec,
811                                 picture_t *p_pic, AVFrame *p_ff_pic )
812 {
813     decoder_sys_t *p_sys = p_dec->p_sys;
814
815     if( ffmpeg_PixFmtToChroma( p_sys->p_context->pix_fmt ) )
816     {
817         int i_plane, i_size, i_line;
818         uint8_t *p_dst, *p_src;
819         int i_src_stride, i_dst_stride;
820
821         for( i_plane = 0; i_plane < p_pic->i_planes; i_plane++ )
822         {
823             p_src  = p_ff_pic->data[i_plane];
824             p_dst = p_pic->p[i_plane].p_pixels;
825             i_src_stride = p_ff_pic->linesize[i_plane];
826             i_dst_stride = p_pic->p[i_plane].i_pitch;
827
828             i_size = __MIN( i_src_stride, i_dst_stride );
829             for( i_line = 0; i_line < p_pic->p[i_plane].i_visible_lines;
830                  i_line++ )
831             {
832                 vlc_memcpy( p_dst, p_src, i_size );
833                 p_src += i_src_stride;
834                 p_dst += i_dst_stride;
835             }
836         }
837     }
838     else
839     {
840         AVPicture dest_pic;
841         int i;
842
843         /* we need to convert to I420 */
844         switch( p_sys->p_context->pix_fmt )
845         {
846         case PIX_FMT_YUV410P:
847         case PIX_FMT_YUV411P:
848         case PIX_FMT_RGB32:
849         case PIX_FMT_RGB24:
850 #if defined(PIX_FMT_RGB8)
851         case PIX_FMT_RGB8:
852 #endif
853 #if defined(PIX_FMT_BRG32)
854         case PIX_FMT_BGR32:
855 #endif
856         case PIX_FMT_BGR24:
857 #if defined(PIX_FMT_BGR8)
858         case PIX_FMT_BGR8:
859 #endif
860         case PIX_FMT_PAL8:
861             for( i = 0; i < p_pic->i_planes; i++ )
862             {
863                 dest_pic.data[i] = p_pic->p[i].p_pixels;
864                 dest_pic.linesize[i] = p_pic->p[i].i_pitch;
865             }
866 #if !defined(HAVE_LIBSWSCALE_SWSCALE_H)  && !defined(HAVE_FFMPEG_SWSCALE_H)
867             img_convert( &dest_pic, PIX_FMT_YUV420P,
868                          (AVPicture *)p_ff_pic,
869                          p_sys->p_context->pix_fmt,
870                          p_sys->p_context->width,
871                          p_sys->p_context->height );
872 #endif
873             break;
874         default:
875             msg_Err( p_dec, "don't know how to convert chroma %i",
876                      p_sys->p_context->pix_fmt );
877             p_dec->b_error = 1;
878             break;
879         }
880     }
881 }
882
883 /*****************************************************************************
884  * ffmpeg_GetFrameBuf: callback used by ffmpeg to get a frame buffer.
885  *****************************************************************************
886  * It is used for direct rendering as well as to get the right PTS for each
887  * decoded picture (even in indirect rendering mode).
888  *****************************************************************************/
889 static void ffmpeg_SetFrameBufferPts( decoder_t *p_dec, AVFrame *p_ff_pic );
890
891 static int ffmpeg_GetFrameBuf( struct AVCodecContext *p_context,
892                                AVFrame *p_ff_pic )
893 {
894     decoder_t *p_dec = (decoder_t *)p_context->opaque;
895     decoder_sys_t *p_sys = p_dec->p_sys;
896     picture_t *p_pic;
897
898     /* Set picture PTS */
899     ffmpeg_SetFrameBufferPts( p_dec, p_ff_pic );
900
901     /* */
902     p_ff_pic->opaque = 0;
903
904     /* Not much to do in indirect rendering mode */
905     if( !p_sys->b_direct_rendering )
906     {
907         return avcodec_default_get_buffer( p_context, p_ff_pic );
908     }
909
910     /* Some codecs set pix_fmt only after the 1st frame has been decoded,
911      * so this check is necessary. */
912     if( !ffmpeg_PixFmtToChroma( p_context->pix_fmt ) ||
913         p_sys->p_context->width % 16 || p_sys->p_context->height % 16 )
914     {
915         msg_Dbg( p_dec, "disabling direct rendering" );
916         p_sys->b_direct_rendering = 0;
917         return avcodec_default_get_buffer( p_context, p_ff_pic );
918     }
919
920     /* Get a new picture */
921     //p_sys->p_vout->render.b_allow_modify_pics = 0;
922     p_pic = ffmpeg_NewPictBuf( p_dec, p_sys->p_context );
923     if( !p_pic )
924     {
925         p_sys->b_direct_rendering = 0;
926         return avcodec_default_get_buffer( p_context, p_ff_pic );
927     }
928     p_sys->p_context->draw_horiz_band = NULL;
929
930     p_ff_pic->opaque = (void*)p_pic;
931     p_ff_pic->type = FF_BUFFER_TYPE_USER;
932     p_ff_pic->data[0] = p_pic->p[0].p_pixels;
933     p_ff_pic->data[1] = p_pic->p[1].p_pixels;
934     p_ff_pic->data[2] = p_pic->p[2].p_pixels;
935     p_ff_pic->data[3] = NULL; /* alpha channel but I'm not sure */
936
937     p_ff_pic->linesize[0] = p_pic->p[0].i_pitch;
938     p_ff_pic->linesize[1] = p_pic->p[1].i_pitch;
939     p_ff_pic->linesize[2] = p_pic->p[2].i_pitch;
940     p_ff_pic->linesize[3] = 0;
941
942     if( p_ff_pic->reference != 0 )
943     {
944         p_dec->pf_picture_link( p_dec, p_pic );
945     }
946
947     /* FIXME what is that, should give good value */
948     p_ff_pic->age = 256*256*256*64; // FIXME FIXME from ffmpeg
949
950     return 0;
951 }
952 static int  ffmpeg_ReGetFrameBuf( struct AVCodecContext *p_context, AVFrame *p_ff_pic )
953 {
954     decoder_t *p_dec = (decoder_t *)p_context->opaque;
955
956     /* Set picture PTS */
957     ffmpeg_SetFrameBufferPts( p_dec, p_ff_pic );
958
959     /* We always use default reget function, it works perfectly fine */
960     return avcodec_default_reget_buffer( p_context, p_ff_pic );
961 }
962
963 static void ffmpeg_SetFrameBufferPts( decoder_t *p_dec, AVFrame *p_ff_pic )
964 {
965     decoder_sys_t *p_sys = p_dec->p_sys;
966
967     /* Set picture PTS */
968     if( p_sys->input_pts )
969     {
970         p_ff_pic->pts = p_sys->input_pts;
971     }
972     else if( p_sys->input_dts )
973     {
974         /* Some demuxers only set the dts so let's try to find a useful
975          * timestamp from this */
976         if( !p_sys->p_context->has_b_frames || !p_sys->b_has_b_frames ||
977             !p_ff_pic->reference || !p_sys->i_pts )
978         {
979             p_ff_pic->pts = p_sys->input_dts;
980         }
981         else p_ff_pic->pts = 0;
982     }
983     else p_ff_pic->pts = 0;
984
985     if( p_sys->i_pts ) /* make sure 1st frame has a pts > 0 */
986     {
987         p_sys->input_pts = p_sys->input_dts = 0;
988     }
989 }
990
991 static void ffmpeg_ReleaseFrameBuf( struct AVCodecContext *p_context,
992                                     AVFrame *p_ff_pic )
993 {
994     decoder_t *p_dec = (decoder_t *)p_context->opaque;
995     picture_t *p_pic;
996
997     if( !p_ff_pic->opaque )
998     {
999         avcodec_default_release_buffer( p_context, p_ff_pic );
1000         return;
1001     }
1002
1003     p_pic = (picture_t*)p_ff_pic->opaque;
1004
1005     p_ff_pic->data[0] = NULL;
1006     p_ff_pic->data[1] = NULL;
1007     p_ff_pic->data[2] = NULL;
1008     p_ff_pic->data[3] = NULL;
1009
1010     if( p_ff_pic->reference != 0 )
1011     {
1012         p_dec->pf_picture_unlink( p_dec, p_pic );
1013     }
1014 }