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