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