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