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