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