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