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