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