]> git.sesse.net Git - vlc/blob - modules/codec/avcodec/video.c
avcodec video decoder: returns delayed frames at end of stream
[vlc] / modules / codec / avcodec / video.c
1 /*****************************************************************************
2  * video.c: video decoder using the libavcodec library
3  *****************************************************************************
4  * Copyright (C) 1999-2001 VLC authors and VideoLAN
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 it
11  * under the terms of the GNU Lesser General Public License as published by
12  * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this program; if not, write to the Free Software Foundation,
22  * 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_avcodec.h>
35 #include <vlc_cpu.h>
36 #include <assert.h>
37
38 #include <libavcodec/avcodec.h>
39 #include <libavutil/mem.h>
40 #include <libavutil/pixdesc.h>
41
42 #include "avcodec.h"
43 #include "va.h"
44
45 /*****************************************************************************
46  * decoder_sys_t : decoder descriptor
47  *****************************************************************************/
48 struct decoder_sys_t
49 {
50     AVCODEC_COMMON_MEMBERS
51
52     /* Video decoder specific part */
53     mtime_t i_pts;
54
55     AVFrame          *p_ff_pic;
56
57     /* for frame skipping algo */
58     bool b_hurry_up;
59     enum AVDiscard i_skip_frame;
60     enum AVDiscard i_skip_idct;
61
62     /* how many decoded frames are late */
63     int     i_late_frames;
64     mtime_t i_late_frames_start;
65
66     /* for direct rendering */
67     bool b_direct_rendering;
68     int  i_direct_rendering_used;
69
70     bool b_has_b_frames;
71
72     /* Hack to force display of still pictures */
73     bool b_first_frame;
74
75
76     /* */
77 #if LIBAVCODEC_VERSION_MAJOR < 54
78     AVPaletteControl palette;
79 #else
80     bool palette_sent;
81 #endif
82
83     /* */
84     bool b_flush;
85
86     /* VA API */
87     vlc_va_t *p_va;
88
89     vlc_sem_t sem_mt;
90 };
91
92 #ifdef HAVE_AVCODEC_MT
93 #   define wait_mt(s) vlc_sem_wait( &s->sem_mt )
94 #   define post_mt(s) vlc_sem_post( &s->sem_mt )
95 #else
96 #   define wait_mt(s)
97 #   define post_mt(s)
98 #endif
99
100 /*****************************************************************************
101  * Local prototypes
102  *****************************************************************************/
103 static void ffmpeg_InitCodec      ( decoder_t * );
104 static void ffmpeg_CopyPicture    ( decoder_t *, picture_t *, AVFrame * );
105 #if LIBAVCODEC_VERSION_MAJOR >= 55
106 static int lavc_GetFrame(struct AVCodecContext *, AVFrame *, int);
107 #else
108 static int  ffmpeg_GetFrameBuf    ( struct AVCodecContext *, AVFrame * );
109 static void ffmpeg_ReleaseFrameBuf( struct AVCodecContext *, AVFrame * );
110 #endif
111 static enum PixelFormat ffmpeg_GetFormat( AVCodecContext *,
112                                           const enum PixelFormat * );
113
114 static uint32_t ffmpeg_CodecTag( vlc_fourcc_t fcc )
115 {
116     uint8_t *p = (uint8_t*)&fcc;
117     return p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
118 }
119
120 /*****************************************************************************
121  * Local Functions
122  *****************************************************************************/
123
124 /* Returns a new picture buffer */
125 static inline picture_t *ffmpeg_NewPictBuf( decoder_t *p_dec,
126                                             AVCodecContext *p_context )
127 {
128     decoder_sys_t *p_sys = p_dec->p_sys;
129     int width = p_context->coded_width;
130     int height = p_context->coded_height;
131
132     if( p_sys->p_va == NULL )
133     {
134         int aligns[AV_NUM_DATA_POINTERS];
135
136         avcodec_align_dimensions2(p_context, &width, &height, aligns);
137     }
138
139     if( width == 0 || height == 0)
140         return NULL; /* invalid display size */
141
142     p_dec->fmt_out.video.i_width = width;
143     p_dec->fmt_out.video.i_height = height;
144
145     if( width != p_context->width || height != p_context->height )
146     {
147         p_dec->fmt_out.video.i_visible_width = p_context->width;
148         p_dec->fmt_out.video.i_visible_height = p_context->height;
149     }
150
151     if( !p_sys->p_va && GetVlcChroma( &p_dec->fmt_out.video, p_context->pix_fmt ) )
152     {
153         /* we are doomed, but not really, because most codecs set their pix_fmt
154          * much later
155          * FIXME does it make sense here ? */
156         p_dec->fmt_out.video.i_chroma = VLC_CODEC_I420;
157     }
158     p_dec->fmt_out.i_codec = p_dec->fmt_out.video.i_chroma;
159
160     /* If an aspect-ratio was specified in the input format then force it */
161     if( p_dec->fmt_in.video.i_sar_num > 0 && p_dec->fmt_in.video.i_sar_den > 0 )
162     {
163         p_dec->fmt_out.video.i_sar_num = p_dec->fmt_in.video.i_sar_num;
164         p_dec->fmt_out.video.i_sar_den = p_dec->fmt_in.video.i_sar_den;
165     }
166     else
167     {
168         p_dec->fmt_out.video.i_sar_num = p_context->sample_aspect_ratio.num;
169         p_dec->fmt_out.video.i_sar_den = p_context->sample_aspect_ratio.den;
170
171         if( !p_dec->fmt_out.video.i_sar_num || !p_dec->fmt_out.video.i_sar_den )
172         {
173             p_dec->fmt_out.video.i_sar_num = 1;
174             p_dec->fmt_out.video.i_sar_den = 1;
175         }
176     }
177
178     if( p_dec->fmt_in.video.i_frame_rate > 0 &&
179         p_dec->fmt_in.video.i_frame_rate_base > 0 )
180     {
181         p_dec->fmt_out.video.i_frame_rate =
182             p_dec->fmt_in.video.i_frame_rate;
183         p_dec->fmt_out.video.i_frame_rate_base =
184             p_dec->fmt_in.video.i_frame_rate_base;
185     }
186     else if( p_context->time_base.num > 0 && p_context->time_base.den > 0 )
187     {
188         p_dec->fmt_out.video.i_frame_rate = p_context->time_base.den;
189         p_dec->fmt_out.video.i_frame_rate_base = p_context->time_base.num * __MAX( p_context->ticks_per_frame, 1 );
190     }
191
192     return decoder_NewPicture( p_dec );
193 }
194
195 /*****************************************************************************
196  * InitVideo: initialize the video decoder
197  *****************************************************************************
198  * the ffmpeg codec will be opened, some memory allocated. The vout is not yet
199  * opened (done after the first decoded frame).
200  *****************************************************************************/
201 int InitVideoDec( decoder_t *p_dec, AVCodecContext *p_context,
202                       AVCodec *p_codec, int i_codec_id, const char *psz_namecodec )
203 {
204     decoder_sys_t *p_sys;
205     int i_val;
206
207     /* Allocate the memory needed to store the decoder's structure */
208     if( ( p_dec->p_sys = p_sys = calloc( 1, sizeof(decoder_sys_t) ) ) == NULL )
209         return VLC_ENOMEM;
210
211     p_codec->type = AVMEDIA_TYPE_VIDEO;
212     p_context->codec_type = AVMEDIA_TYPE_VIDEO;
213     p_context->codec_id = i_codec_id;
214     p_sys->p_context = p_context;
215     p_sys->p_codec = p_codec;
216     p_sys->i_codec_id = i_codec_id;
217     p_sys->psz_namecodec = psz_namecodec;
218     p_sys->p_ff_pic = avcodec_alloc_frame();
219     p_sys->b_delayed_open = true;
220     p_sys->p_va = NULL;
221     vlc_sem_init( &p_sys->sem_mt, 0 );
222
223     /* ***** Fill p_context with init values ***** */
224     p_sys->p_context->codec_tag = ffmpeg_CodecTag( p_dec->fmt_in.i_original_fourcc ?: p_dec->fmt_in.i_codec );
225
226     /*  ***** Get configuration of ffmpeg plugin ***** */
227     p_sys->p_context->workaround_bugs =
228         var_InheritInteger( p_dec, "avcodec-workaround-bugs" );
229     p_sys->p_context->err_recognition =
230         var_InheritInteger( p_dec, "avcodec-error-resilience" );
231
232     if( var_CreateGetBool( p_dec, "grayscale" ) )
233         p_sys->p_context->flags |= CODEC_FLAG_GRAY;
234
235     /* ***** Output always the frames ***** */
236 #if LIBAVCODEC_VERSION_CHECK(55, 23, 1, 40, 101)
237     p_sys->p_context->flags |= CODEC_FLAG_OUTPUT_CORRUPT;
238 #endif
239
240     i_val = var_CreateGetInteger( p_dec, "avcodec-vismv" );
241     if( i_val ) p_sys->p_context->debug_mv = i_val;
242
243     i_val = var_CreateGetInteger( p_dec, "avcodec-skiploopfilter" );
244     if( i_val >= 4 ) p_sys->p_context->skip_loop_filter = AVDISCARD_ALL;
245     else if( i_val == 3 ) p_sys->p_context->skip_loop_filter = AVDISCARD_NONKEY;
246     else if( i_val == 2 ) p_sys->p_context->skip_loop_filter = AVDISCARD_BIDIR;
247     else if( i_val == 1 ) p_sys->p_context->skip_loop_filter = AVDISCARD_NONREF;
248
249     if( var_CreateGetBool( p_dec, "avcodec-fast" ) )
250         p_sys->p_context->flags2 |= CODEC_FLAG2_FAST;
251
252     /* ***** libavcodec frame skipping ***** */
253     p_sys->b_hurry_up = var_CreateGetBool( p_dec, "avcodec-hurry-up" );
254
255     i_val = var_CreateGetInteger( p_dec, "avcodec-skip-frame" );
256     if( i_val >= 4 ) p_sys->p_context->skip_frame = AVDISCARD_ALL;
257     else if( i_val == 3 ) p_sys->p_context->skip_frame = AVDISCARD_NONKEY;
258     else if( i_val == 2 ) p_sys->p_context->skip_frame = AVDISCARD_BIDIR;
259     else if( i_val == 1 ) p_sys->p_context->skip_frame = AVDISCARD_NONREF;
260     else if( i_val == -1 ) p_sys->p_context->skip_frame = AVDISCARD_NONE;
261     else p_sys->p_context->skip_frame = AVDISCARD_DEFAULT;
262     p_sys->i_skip_frame = p_sys->p_context->skip_frame;
263
264     i_val = var_CreateGetInteger( p_dec, "avcodec-skip-idct" );
265     if( i_val >= 4 ) p_sys->p_context->skip_idct = AVDISCARD_ALL;
266     else if( i_val == 3 ) p_sys->p_context->skip_idct = AVDISCARD_NONKEY;
267     else if( i_val == 2 ) p_sys->p_context->skip_idct = AVDISCARD_BIDIR;
268     else if( i_val == 1 ) p_sys->p_context->skip_idct = AVDISCARD_NONREF;
269     else if( i_val == -1 ) p_sys->p_context->skip_idct = AVDISCARD_NONE;
270     else p_sys->p_context->skip_idct = AVDISCARD_DEFAULT;
271     p_sys->i_skip_idct = p_sys->p_context->skip_idct;
272
273     /* ***** libavcodec direct rendering ***** */
274     p_sys->b_direct_rendering = false;
275     p_sys->i_direct_rendering_used = -1;
276     if( var_CreateGetBool( p_dec, "avcodec-dr" ) &&
277        (p_sys->p_codec->capabilities & CODEC_CAP_DR1) &&
278         /* No idea why ... but this fixes flickering on some TSCC streams */
279         p_sys->i_codec_id != AV_CODEC_ID_TSCC && p_sys->i_codec_id != AV_CODEC_ID_CSCD &&
280         p_sys->i_codec_id != AV_CODEC_ID_CINEPAK &&
281         !p_sys->p_context->debug_mv )
282     {
283         /* Some codecs set pix_fmt only after the 1st frame has been decoded,
284          * so we need to do another check in ffmpeg_GetFrameBuf() */
285         p_sys->b_direct_rendering = true;
286     }
287
288     /* libavcodec doesn't properly release old pictures when frames are skipped */
289     //if( p_sys->b_hurry_up ) p_sys->b_direct_rendering = false;
290     if( p_sys->b_direct_rendering )
291     {
292         msg_Dbg( p_dec, "trying to use direct rendering" );
293         p_sys->p_context->flags |= CODEC_FLAG_EMU_EDGE;
294     }
295     else
296     {
297         msg_Dbg( p_dec, "direct rendering is disabled" );
298     }
299
300     p_sys->p_context->get_format = ffmpeg_GetFormat;
301     /* Always use our get_buffer wrapper so we can calculate the
302      * PTS correctly */
303 #if LIBAVCODEC_VERSION_MAJOR >= 55
304     p_sys->p_context->get_buffer2 = lavc_GetFrame;
305 #else
306     p_sys->p_context->get_buffer = ffmpeg_GetFrameBuf;
307     p_sys->p_context->reget_buffer = avcodec_default_reget_buffer;
308     p_sys->p_context->release_buffer = ffmpeg_ReleaseFrameBuf;
309 #endif
310     p_sys->p_context->opaque = p_dec;
311
312 #ifdef HAVE_AVCODEC_MT
313     int i_thread_count = var_InheritInteger( p_dec, "avcodec-threads" );
314     if( i_thread_count <= 0 )
315     {
316         i_thread_count = vlc_GetCPUCount();
317         if( i_thread_count > 1 )
318             i_thread_count++;
319
320         //FIXME: take in count the decoding time
321         i_thread_count = __MIN( i_thread_count, 4 );
322     }
323     i_thread_count = __MIN( i_thread_count, 16 );
324     msg_Dbg( p_dec, "allowing %d thread(s) for decoding", i_thread_count );
325     p_sys->p_context->thread_count = i_thread_count;
326     p_sys->p_context->thread_safe_callbacks = true;
327
328     switch( i_codec_id )
329     {
330         case AV_CODEC_ID_MPEG4:
331         case AV_CODEC_ID_H263:
332             p_sys->p_context->thread_type = 0;
333             break;
334         case AV_CODEC_ID_MPEG1VIDEO:
335         case AV_CODEC_ID_MPEG2VIDEO:
336             p_sys->p_context->thread_type &= ~FF_THREAD_SLICE;
337             /* fall through */
338 # if (LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55, 1, 0))
339         case AV_CODEC_ID_H264:
340         case AV_CODEC_ID_VC1:
341         case AV_CODEC_ID_WMV3:
342             p_sys->p_context->thread_type &= ~FF_THREAD_FRAME;
343 # endif
344     }
345
346     if( p_sys->p_context->thread_type & FF_THREAD_FRAME )
347         p_dec->i_extra_picture_buffers = 2 * p_sys->p_context->thread_count;
348 #endif
349
350     /* ***** misc init ***** */
351     p_sys->i_pts = VLC_TS_INVALID;
352     p_sys->b_has_b_frames = false;
353     p_sys->b_first_frame = true;
354     p_sys->b_flush = false;
355     p_sys->i_late_frames = 0;
356
357     /* Set output properties */
358     p_dec->fmt_out.i_cat = VIDEO_ES;
359     if( GetVlcChroma( &p_dec->fmt_out.video, p_context->pix_fmt ) != VLC_SUCCESS )
360     {
361         /* we are doomed. but not really, because most codecs set their pix_fmt later on */
362         p_dec->fmt_out.i_codec = VLC_CODEC_I420;
363     }
364     p_dec->fmt_out.i_codec = p_dec->fmt_out.video.i_chroma;
365
366 #if LIBAVCODEC_VERSION_MAJOR < 54
367     /* Setup palette */
368     memset( &p_sys->palette, 0, sizeof(p_sys->palette) );
369     if( p_dec->fmt_in.video.p_palette )
370     {
371         p_sys->palette.palette_changed = 1;
372
373         for( int i = 0; i < __MIN( AVPALETTE_COUNT, p_dec->fmt_in.video.p_palette->i_entries ); i++ )
374         {
375             union {
376                 uint32_t u;
377                 uint8_t a[4];
378             } c;
379             c.a[0] = p_dec->fmt_in.video.p_palette->palette[i][0];
380             c.a[1] = p_dec->fmt_in.video.p_palette->palette[i][1];
381             c.a[2] = p_dec->fmt_in.video.p_palette->palette[i][2];
382             c.a[3] = p_dec->fmt_in.video.p_palette->palette[i][3];
383
384             p_sys->palette.palette[i] = c.u;
385         }
386         p_sys->p_context->palctrl = &p_sys->palette;
387
388         p_dec->fmt_out.video.p_palette = malloc( sizeof(video_palette_t) );
389         if( p_dec->fmt_out.video.p_palette )
390             *p_dec->fmt_out.video.p_palette = *p_dec->fmt_in.video.p_palette;
391     }
392     else if( p_sys->i_codec_id != CODEC_ID_MSVIDEO1 && p_sys->i_codec_id != CODEC_ID_CINEPAK )
393     {
394         p_sys->p_context->palctrl = &p_sys->palette;
395     }
396 #else
397     if( p_dec->fmt_in.video.p_palette ) {
398         p_sys->palette_sent = false;
399         p_dec->fmt_out.video.p_palette = malloc( sizeof(video_palette_t) );
400         if( p_dec->fmt_out.video.p_palette )
401             *p_dec->fmt_out.video.p_palette = *p_dec->fmt_in.video.p_palette;
402     } else
403         p_sys->palette_sent = true;
404 #endif
405
406     /* ***** init this codec with special data ***** */
407     ffmpeg_InitCodec( p_dec );
408
409     /* ***** Open the codec ***** */
410     if( ffmpeg_OpenCodec( p_dec ) < 0 )
411     {
412         msg_Err( p_dec, "cannot open codec (%s)", p_sys->psz_namecodec );
413         av_free( p_sys->p_ff_pic );
414         vlc_sem_destroy( &p_sys->sem_mt );
415         free( p_sys );
416         return VLC_EGENERIC;
417     }
418
419     return VLC_SUCCESS;
420 }
421
422 /*****************************************************************************
423  * DecodeVideo: Called to decode one or more frames
424  *****************************************************************************/
425 picture_t *DecodeVideo( decoder_t *p_dec, block_t **pp_block )
426 {
427     decoder_sys_t *p_sys = p_dec->p_sys;
428     AVCodecContext *p_context = p_sys->p_context;
429     int b_drawpicture;
430     int b_null_size = false;
431     block_t *p_block;
432
433     if( !pp_block )
434         return NULL;
435
436     if( !p_context->extradata_size && p_dec->fmt_in.i_extra )
437     {
438         ffmpeg_InitCodec( p_dec );
439         if( p_sys->b_delayed_open )
440         {
441             if( ffmpeg_OpenCodec( p_dec ) )
442                 msg_Err( p_dec, "cannot open codec (%s)", p_sys->psz_namecodec );
443         }
444     }
445
446     p_block = *pp_block;
447     if(!p_block && !(p_sys->p_codec->capabilities & CODEC_CAP_DELAY) )
448         return NULL;
449
450     if( p_sys->b_delayed_open )
451     {
452         if( p_block )
453             block_Release( p_block );
454         return NULL;
455     }
456
457     if( p_block)
458     {
459         if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
460         {
461             p_sys->i_pts = VLC_TS_INVALID; /* To make sure we recover properly */
462
463             p_sys->i_late_frames = 0;
464
465             post_mt( p_sys );
466             if( p_block->i_flags & BLOCK_FLAG_DISCONTINUITY )
467                 avcodec_flush_buffers( p_context );
468             wait_mt( p_sys );
469
470             block_Release( p_block );
471             return NULL;
472         }
473
474         if( p_block->i_flags & BLOCK_FLAG_PREROLL )
475         {
476             /* Do not care about late frames when prerolling
477              * TODO avoid decoding of non reference frame
478              * (ie all B except for H264 where it depends only on nal_ref_idc) */
479             p_sys->i_late_frames = 0;
480         }
481     }
482
483     if( !p_dec->b_pace_control && (p_sys->i_late_frames > 0) &&
484         (mdate() - p_sys->i_late_frames_start > INT64_C(5000000)) )
485     {
486         if( p_sys->i_pts > VLC_TS_INVALID )
487         {
488             msg_Err( p_dec, "more than 5 seconds of late video -> "
489                      "dropping frame (computer too slow ?)" );
490             p_sys->i_pts = VLC_TS_INVALID; /* To make sure we recover properly */
491         }
492         if( p_block )
493             block_Release( p_block );
494         p_sys->i_late_frames--;
495         return NULL;
496     }
497
498     /* A good idea could be to decode all I pictures and see for the other */
499     if( !p_dec->b_pace_control &&
500         p_sys->b_hurry_up &&
501         (p_sys->i_late_frames > 4) )
502     {
503         b_drawpicture = 0;
504         if( p_sys->i_late_frames < 12 )
505         {
506             p_context->skip_frame =
507                     (p_sys->i_skip_frame <= AVDISCARD_NONREF) ?
508                     AVDISCARD_NONREF : p_sys->i_skip_frame;
509         }
510         else
511         {
512             /* picture too late, won't decode
513              * but break picture until a new I, and for mpeg4 ...*/
514             p_sys->i_late_frames--; /* needed else it will never be decrease */
515             if( p_block )
516                 block_Release( p_block );
517             return NULL;
518         }
519     }
520     else
521     {
522         if( p_sys->b_hurry_up )
523             p_context->skip_frame = p_sys->i_skip_frame;
524         if( !p_block || !(p_block->i_flags & BLOCK_FLAG_PREROLL) )
525             b_drawpicture = 1;
526         else
527             b_drawpicture = 0;
528     }
529
530     if( p_context->width <= 0 || p_context->height <= 0 )
531     {
532         if( p_sys->b_hurry_up )
533             p_context->skip_frame = p_sys->i_skip_frame;
534         b_null_size = true;
535     }
536     else if( !b_drawpicture )
537     {
538         /* It creates broken picture
539          * FIXME either our parser or ffmpeg is broken */
540 #if 0
541         if( p_sys->b_hurry_up )
542             p_context->skip_frame = __MAX( p_context->skip_frame,
543                                                   AVDISCARD_NONREF );
544 #endif
545     }
546
547     /*
548      * Do the actual decoding now */
549
550     /* Don't forget that libavcodec requires a little more bytes
551      * that the real frame size */
552     if( p_block && p_block->i_buffer > 0 )
553     {
554         p_sys->b_flush = ( p_block->i_flags & BLOCK_FLAG_END_OF_SEQUENCE ) != 0;
555
556         p_block = block_Realloc( p_block, 0,
557                             p_block->i_buffer + FF_INPUT_BUFFER_PADDING_SIZE );
558         if( !p_block )
559             return NULL;
560         p_block->i_buffer -= FF_INPUT_BUFFER_PADDING_SIZE;
561         *pp_block = p_block;
562         memset( p_block->p_buffer + p_block->i_buffer, 0,
563                 FF_INPUT_BUFFER_PADDING_SIZE );
564     }
565
566     while( !p_block || p_block->i_buffer > 0 || p_sys->b_flush )
567     {
568         int i_used, b_gotpicture;
569         picture_t *p_pic;
570         AVPacket pkt;
571
572         post_mt( p_sys );
573
574         av_init_packet( &pkt );
575         if( p_block )
576         {
577             pkt.data = p_block->p_buffer;
578             pkt.size = p_block->i_buffer;
579             pkt.pts = p_block->i_pts;
580             pkt.dts = p_block->i_dts;
581         }
582         else
583         {
584             /* Return delayed frames if codec has CODEC_CAP_DELAY */
585             pkt.data = NULL;
586             pkt.size = 0;
587         }
588
589 #if LIBAVCODEC_VERSION_MAJOR >= 54
590         if( !p_sys->palette_sent )
591         {
592             uint8_t *pal = av_packet_new_side_data(&pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
593             if (pal) {
594                 memcpy(pal, p_dec->fmt_in.video.p_palette->palette, AVPALETTE_SIZE);
595                 p_sys->palette_sent = true;
596             }
597         }
598 #endif
599
600         /* Make sure we don't reuse the same timestamps twice */
601         if( p_block )
602         {
603             p_block->i_pts =
604             p_block->i_dts = VLC_TS_INVALID;
605         }
606
607         i_used = avcodec_decode_video2( p_context, p_sys->p_ff_pic,
608                                        &b_gotpicture, &pkt );
609
610         if( b_null_size && !p_sys->b_flush &&
611             p_context->width > 0 && p_context->height > 0 )
612         {
613             /* Reparse it to not drop the I frame */
614             b_null_size = false;
615             if( p_sys->b_hurry_up )
616                 p_context->skip_frame = p_sys->i_skip_frame;
617             i_used = avcodec_decode_video2( p_context, p_sys->p_ff_pic,
618                                            &b_gotpicture, &pkt );
619         }
620         wait_mt( p_sys );
621
622         if( p_sys->b_flush )
623             p_sys->b_first_frame = true;
624
625         if( p_block )
626         {
627             if( p_block->i_buffer <= 0 )
628                 p_sys->b_flush = false;
629
630             if( i_used < 0 )
631             {
632                 if( b_drawpicture )
633                     msg_Warn( p_dec, "cannot decode one frame (%zu bytes)",
634                             p_block->i_buffer );
635                 block_Release( p_block );
636                 return NULL;
637             }
638             else if( (unsigned)i_used > p_block->i_buffer ||
639                     p_context->thread_count > 1 )
640             {
641                 i_used = p_block->i_buffer;
642             }
643
644             /* Consumed bytes */
645             p_block->i_buffer -= i_used;
646             p_block->p_buffer += i_used;
647         }
648
649         /* Nothing to display */
650         if( !b_gotpicture )
651         {
652             if( i_used == 0 ) break;
653             continue;
654         }
655
656         /* Sanity check (seems to be needed for some streams) */
657         if( p_sys->p_ff_pic->pict_type == AV_PICTURE_TYPE_B)
658         {
659             p_sys->b_has_b_frames = true;
660         }
661
662         /* Compute the PTS */
663         mtime_t i_pts =
664                     p_sys->p_ff_pic->pkt_pts;
665         if (i_pts <= VLC_TS_INVALID)
666             i_pts = p_sys->p_ff_pic->pkt_dts;
667
668         if( i_pts <= VLC_TS_INVALID )
669             i_pts = p_sys->i_pts;
670
671         /* Interpolate the next PTS */
672         if( i_pts > VLC_TS_INVALID )
673             p_sys->i_pts = i_pts;
674         if( p_sys->i_pts > VLC_TS_INVALID )
675         {
676             /* interpolate the next PTS */
677             if( p_dec->fmt_in.video.i_frame_rate > 0 &&
678                 p_dec->fmt_in.video.i_frame_rate_base > 0 )
679             {
680                 p_sys->i_pts += INT64_C(1000000) *
681                     (2 + p_sys->p_ff_pic->repeat_pict) *
682                     p_dec->fmt_in.video.i_frame_rate_base /
683                     (2 * p_dec->fmt_in.video.i_frame_rate);
684             }
685             else if( p_context->time_base.den > 0 )
686             {
687                 int i_tick = p_context->ticks_per_frame;
688                 if( i_tick <= 0 )
689                     i_tick = 1;
690
691                 p_sys->i_pts += INT64_C(1000000) *
692                     (2 + p_sys->p_ff_pic->repeat_pict) *
693                     i_tick * p_context->time_base.num /
694                     (2 * p_context->time_base.den);
695             }
696         }
697
698         /* Update frame late count (except when doing preroll) */
699         mtime_t i_display_date = 0;
700         if( !p_block || !(p_block->i_flags & BLOCK_FLAG_PREROLL) )
701             i_display_date = decoder_GetDisplayDate( p_dec, i_pts );
702
703         if( i_display_date > 0 && i_display_date <= mdate() )
704         {
705             p_sys->i_late_frames++;
706             if( p_sys->i_late_frames == 1 )
707                 p_sys->i_late_frames_start = mdate();
708         }
709         else
710         {
711             p_sys->i_late_frames = 0;
712         }
713
714         if( !b_drawpicture || ( !p_sys->p_va && !p_sys->p_ff_pic->linesize[0] ) )
715             continue;
716
717         if( p_sys->p_va != NULL || p_sys->p_ff_pic->opaque == NULL )
718         {
719             /* Get a new picture */
720             p_pic = ffmpeg_NewPictBuf( p_dec, p_context );
721             if( !p_pic )
722             {
723                 if( p_block )
724                     block_Release( p_block );
725                 return NULL;
726             }
727
728             /* Fill p_picture_t from AVVideoFrame and do chroma conversion
729              * if needed */
730             ffmpeg_CopyPicture( p_dec, p_pic, p_sys->p_ff_pic );
731         }
732         else
733         {
734             p_pic = (picture_t *)p_sys->p_ff_pic->opaque;
735             decoder_LinkPicture( p_dec, p_pic );
736         }
737
738         if( !p_dec->fmt_in.video.i_sar_num || !p_dec->fmt_in.video.i_sar_den )
739         {
740             /* Fetch again the aspect ratio in case it changed */
741             p_dec->fmt_out.video.i_sar_num
742                 = p_context->sample_aspect_ratio.num;
743             p_dec->fmt_out.video.i_sar_den
744                 = p_context->sample_aspect_ratio.den;
745
746             if( !p_dec->fmt_out.video.i_sar_num || !p_dec->fmt_out.video.i_sar_den )
747             {
748                 p_dec->fmt_out.video.i_sar_num = 1;
749                 p_dec->fmt_out.video.i_sar_den = 1;
750             }
751         }
752
753         /* Send decoded frame to vout */
754         if( i_pts > VLC_TS_INVALID)
755         {
756             p_pic->date = i_pts;
757
758             if( p_sys->b_first_frame )
759             {
760                 /* Hack to force display of still pictures */
761                 p_sys->b_first_frame = false;
762                 p_pic->b_force = true;
763             }
764
765             p_pic->i_nb_fields = 2 + p_sys->p_ff_pic->repeat_pict;
766             p_pic->b_progressive = !p_sys->p_ff_pic->interlaced_frame;
767             p_pic->b_top_field_first = p_sys->p_ff_pic->top_field_first;
768
769             return p_pic;
770         }
771         else
772         {
773             decoder_DeletePicture( p_dec, p_pic );
774         }
775     }
776
777     if( p_block )
778         block_Release( p_block );
779     return NULL;
780 }
781
782 /*****************************************************************************
783  * EndVideo: decoder destruction
784  *****************************************************************************
785  * This function is called when the thread ends after a successful
786  * initialization.
787  *****************************************************************************/
788 void EndVideoDec( decoder_t *p_dec )
789 {
790     decoder_sys_t *p_sys = p_dec->p_sys;
791
792     post_mt( p_sys );
793
794     /* do not flush buffers if codec hasn't been opened (theora/vorbis/VC1) */
795     if( p_sys->p_context->codec )
796         avcodec_flush_buffers( p_sys->p_context );
797
798     wait_mt( p_sys );
799
800     if( p_sys->p_ff_pic )
801         av_free( p_sys->p_ff_pic );
802
803     if( p_sys->p_va )
804         vlc_va_Delete( p_sys->p_va );
805
806     vlc_sem_destroy( &p_sys->sem_mt );
807 }
808
809 /*****************************************************************************
810  * ffmpeg_InitCodec: setup codec extra initialization data for ffmpeg
811  *****************************************************************************/
812 static void ffmpeg_InitCodec( decoder_t *p_dec )
813 {
814     decoder_sys_t *p_sys = p_dec->p_sys;
815     int i_size = p_dec->fmt_in.i_extra;
816
817     if( !i_size ) return;
818
819     if( p_sys->i_codec_id == AV_CODEC_ID_SVQ3 )
820     {
821         uint8_t *p;
822
823         p_sys->p_context->extradata_size = i_size + 12;
824         p = p_sys->p_context->extradata =
825             av_malloc( p_sys->p_context->extradata_size +
826                        FF_INPUT_BUFFER_PADDING_SIZE );
827         if( !p )
828             return;
829
830         memcpy( &p[0],  "SVQ3", 4 );
831         memset( &p[4], 0, 8 );
832         memcpy( &p[12], p_dec->fmt_in.p_extra, i_size );
833
834         /* Now remove all atoms before the SMI one */
835         if( p_sys->p_context->extradata_size > 0x5a &&
836             strncmp( (char*)&p[0x56], "SMI ", 4 ) )
837         {
838             uint8_t *psz = &p[0x52];
839
840             while( psz < &p[p_sys->p_context->extradata_size - 8] )
841             {
842                 int i_size = GetDWBE( psz );
843                 if( i_size <= 1 )
844                 {
845                     /* FIXME handle 1 as long size */
846                     break;
847                 }
848                 if( !strncmp( (char*)&psz[4], "SMI ", 4 ) )
849                 {
850                     memmove( &p[0x52], psz,
851                              &p[p_sys->p_context->extradata_size] - psz );
852                     break;
853                 }
854
855                 psz += i_size;
856             }
857         }
858     }
859     else
860     {
861         p_sys->p_context->extradata_size = i_size;
862         p_sys->p_context->extradata =
863             av_malloc( i_size + FF_INPUT_BUFFER_PADDING_SIZE );
864         if( p_sys->p_context->extradata )
865         {
866             memcpy( p_sys->p_context->extradata,
867                     p_dec->fmt_in.p_extra, i_size );
868             memset( p_sys->p_context->extradata + i_size,
869                     0, FF_INPUT_BUFFER_PADDING_SIZE );
870         }
871     }
872 }
873
874 /*****************************************************************************
875  * ffmpeg_CopyPicture: copy a picture from ffmpeg internal buffers to a
876  *                     picture_t structure (when not in direct rendering mode).
877  *****************************************************************************/
878 static void ffmpeg_CopyPicture( decoder_t *p_dec,
879                                 picture_t *p_pic, AVFrame *p_ff_pic )
880 {
881     decoder_sys_t *p_sys = p_dec->p_sys;
882
883     if( p_sys->p_va )
884     {
885         vlc_va_Extract( p_sys->p_va, p_pic, p_ff_pic->opaque,
886                         p_ff_pic->data[3] );
887     }
888     else if( FindVlcChroma( p_sys->p_context->pix_fmt ) )
889     {
890         int i_plane, i_size, i_line;
891         uint8_t *p_dst, *p_src;
892         int i_src_stride, i_dst_stride;
893
894         for( i_plane = 0; i_plane < p_pic->i_planes; i_plane++ )
895         {
896             p_src  = p_ff_pic->data[i_plane];
897             p_dst = p_pic->p[i_plane].p_pixels;
898             i_src_stride = p_ff_pic->linesize[i_plane];
899             i_dst_stride = p_pic->p[i_plane].i_pitch;
900
901             i_size = __MIN( i_src_stride, i_dst_stride );
902             for( i_line = 0; i_line < p_pic->p[i_plane].i_visible_lines;
903                  i_line++ )
904             {
905                 memcpy( p_dst, p_src, i_size );
906                 p_src += i_src_stride;
907                 p_dst += i_dst_stride;
908             }
909         }
910     }
911     else
912     {
913         const char *name = av_get_pix_fmt_name( p_sys->p_context->pix_fmt );
914         msg_Err( p_dec, "Unsupported decoded output format %d (%s)",
915                  p_sys->p_context->pix_fmt, name ? name : "unknown" );
916         p_dec->b_error = 1;
917     }
918 }
919
920 #if LIBAVCODEC_VERSION_MAJOR >= 55
921 static int lavc_va_GetFrame(struct AVCodecContext *ctx, AVFrame *frame,
922                             int flags)
923 {
924     decoder_t *dec = ctx->opaque;
925     decoder_sys_t *sys = dec->p_sys;
926     vlc_va_t *va = sys->p_va;
927
928     if (vlc_va_Setup(va, &ctx->hwaccel_context, &dec->fmt_out.video.i_chroma,
929                      ctx->coded_width, ctx->coded_height))
930     {
931         msg_Err(dec, "hardware acceleration setup failed");
932         return -1;
933     }
934     if (vlc_va_Get(va, &frame->opaque, &frame->data[0]))
935     {
936         msg_Err(dec, "hardware acceleration picture allocation failed");
937         return -1;
938     }
939     /* data[0] must be non-NULL for libavcodec internal checks.
940      * data[3] actually contains the format-specific surface handle. */
941     frame->data[3] = frame->data[0];
942
943     frame->buf[0] = av_buffer_create(frame->data[0], 0, va->release,
944                                      frame->opaque, 0);
945     if (unlikely(frame->buf[0] == NULL))
946     {
947         vlc_va_Release(va, frame->opaque, frame->data[0]);
948         return -1;
949     }
950     assert(frame->data[0] != NULL);
951     (void) flags;
952     return 0;
953 }
954
955 typedef struct
956 {
957     decoder_t *decoder;
958     picture_t *picture;
959 } lavc_pic_ref_t;
960
961 static void lavc_dr_ReleaseFrame(void *opaque, uint8_t *data)
962 {
963     lavc_pic_ref_t *ref = opaque;
964
965     decoder_UnlinkPicture(ref->decoder, ref->picture);
966     free(ref);
967     (void) data;
968 }
969
970 static picture_t *lavc_dr_GetFrame(struct AVCodecContext *ctx,
971                                    AVFrame *frame, int flags)
972 {
973     decoder_t *dec = (decoder_t *)ctx->opaque;
974     decoder_sys_t *sys = dec->p_sys;
975
976     if (GetVlcChroma(&dec->fmt_out.video, ctx->pix_fmt) != VLC_SUCCESS)
977         return NULL;
978     dec->fmt_out.i_codec = dec->fmt_out.video.i_chroma;
979     if (ctx->pix_fmt == PIX_FMT_PAL8)
980         return NULL;
981
982     int width = frame->width;
983     int height = frame->height;
984     int aligns[AV_NUM_DATA_POINTERS];
985
986     avcodec_align_dimensions2(ctx, &width, &height, aligns);
987
988     picture_t *pic = ffmpeg_NewPictBuf(dec, ctx);
989     if (pic == NULL)
990         return NULL;
991
992     /* Check that the picture is suitable for libavcodec */
993     if (pic->p[0].i_pitch < width * pic->p[0].i_pixel_pitch)
994     {
995         if (sys->i_direct_rendering_used != 0)
996             msg_Dbg(dec, "plane 0: pitch too small (%d/%d*%d)",
997                     pic->p[0].i_pitch, width, pic->p[0].i_pixel_pitch);
998         goto no_dr;
999     }
1000
1001     if (pic->p[0].i_lines < height)
1002     {
1003         if (sys->i_direct_rendering_used != 0)
1004             msg_Dbg(dec, "plane 0: lines too few (%d/%d)",
1005                     pic->p[0].i_lines, height);
1006         goto no_dr;
1007     }
1008
1009     for (int i = 0; i < pic->i_planes; i++)
1010     {
1011         if (pic->p[i].i_pitch % aligns[i])
1012         {
1013             if (sys->i_direct_rendering_used != 0)
1014                 msg_Dbg(dec, "plane %d: pitch not aligned (%d%%%d)",
1015                         i, pic->p[i].i_pitch, aligns[i]);
1016             goto no_dr;
1017         }
1018         if (((uintptr_t)pic->p[i].p_pixels) % aligns[i])
1019         {
1020             if (sys->i_direct_rendering_used != 0)
1021                 msg_Warn(dec, "plane %d not aligned", i);
1022             goto no_dr;
1023         }
1024     }
1025
1026     /* Allocate buffer references */
1027     for (int i = 0; i < pic->i_planes; i++)
1028     {
1029         lavc_pic_ref_t *ref = malloc(sizeof (*ref));
1030         if (ref == NULL)
1031             goto error;
1032         ref->decoder = dec;
1033         ref->picture = pic;
1034         decoder_LinkPicture(dec, pic);
1035
1036         uint8_t *data = pic->p[i].p_pixels;
1037         int size = pic->p[i].i_pitch * pic->p[i].i_lines;
1038
1039         frame->buf[i] = av_buffer_create(data, size, lavc_dr_ReleaseFrame,
1040                                          ref, 0);
1041         if (unlikely(frame->buf[i] == NULL))
1042         {
1043             lavc_dr_ReleaseFrame(ref, data);
1044             goto error;
1045         }
1046     }
1047     decoder_UnlinkPicture(dec, pic);
1048     (void) flags;
1049     return pic;
1050 error:
1051     for (unsigned i = 0; frame->buf[i] != NULL; i++)
1052         av_buffer_unref(&frame->buf[i]);
1053 no_dr:
1054     decoder_DeletePicture(dec, pic);
1055     return NULL;
1056 }
1057
1058 /**
1059  * Callback used by libavcodec to get a frame buffer.
1060  *
1061  * It is used for direct rendering as well as to get the right PTS for each
1062  * decoded picture (even in indirect rendering mode).
1063  */
1064 static int lavc_GetFrame(struct AVCodecContext *ctx, AVFrame *frame, int flags)
1065 {
1066     decoder_t *dec = ctx->opaque;
1067     decoder_sys_t *sys = dec->p_sys;
1068     picture_t *pic;
1069
1070     for (unsigned i = 0; i < AV_NUM_DATA_POINTERS; i++)
1071     {
1072         frame->data[i] = NULL;
1073         frame->linesize[i] = 0;
1074         frame->buf[i] = NULL;
1075     }
1076
1077     if (sys->p_va != NULL)
1078         return lavc_va_GetFrame(ctx, frame, flags);
1079
1080     frame->opaque = NULL;
1081     if (!sys->b_direct_rendering)
1082         return avcodec_default_get_buffer2(ctx, frame, flags);
1083
1084     /* Some codecs set pix_fmt only after the 1st frame has been decoded,
1085      * so we need to check for direct rendering again. */
1086     wait_mt(sys);
1087     pic = lavc_dr_GetFrame(ctx, frame, flags);
1088     if (pic == NULL)
1089     {
1090         if (sys->i_direct_rendering_used != 0)
1091         {
1092             msg_Warn(dec, "disabling direct rendering");
1093             sys->i_direct_rendering_used = 0;
1094         }
1095         post_mt(sys);
1096         return avcodec_default_get_buffer2(ctx, frame, flags);
1097     }
1098
1099     if (sys->i_direct_rendering_used != 1)
1100     {
1101         msg_Dbg(dec, "enabling direct rendering");
1102         sys->i_direct_rendering_used = 1;
1103     }
1104     post_mt(sys);
1105
1106     frame->opaque = pic;
1107     static_assert(PICTURE_PLANE_MAX <= AV_NUM_DATA_POINTERS, "Oops!");
1108     for (unsigned i = 0; i < PICTURE_PLANE_MAX; i++)
1109     {
1110         frame->data[i] = pic->p[i].p_pixels;
1111         frame->linesize[i] = pic->p[i].i_pitch;
1112     }
1113     return 0;
1114 }
1115 #else
1116 static int ffmpeg_va_GetFrameBuf( struct AVCodecContext *p_context, AVFrame *p_ff_pic )
1117 {
1118     decoder_t *p_dec = (decoder_t *)p_context->opaque;
1119     decoder_sys_t *p_sys = p_dec->p_sys;
1120     vlc_va_t *p_va = p_sys->p_va;
1121
1122     /* hwaccel_context is not present in old ffmpeg version */
1123     if( vlc_va_Setup( p_va,
1124                 &p_context->hwaccel_context, &p_dec->fmt_out.video.i_chroma,
1125                 p_context->coded_width, p_context->coded_height ) )
1126     {
1127         msg_Err( p_dec, "vlc_va_Setup failed" );
1128         return -1;
1129     }
1130
1131     if( vlc_va_Get( p_va, &p_ff_pic->opaque, &p_ff_pic->data[0] ) )
1132     {
1133         msg_Err( p_dec, "vlc_va_Get failed" );
1134         return -1;
1135     }
1136
1137     p_ff_pic->data[3] = p_ff_pic->data[0];
1138     p_ff_pic->type = FF_BUFFER_TYPE_USER;
1139     return 0;
1140 }
1141
1142 static picture_t *ffmpeg_dr_GetFrameBuf(struct AVCodecContext *p_context)
1143 {
1144     decoder_t *p_dec = (decoder_t *)p_context->opaque;
1145     decoder_sys_t *p_sys = p_dec->p_sys;
1146
1147     int i_width = p_context->width;
1148     int i_height = p_context->height;
1149     avcodec_align_dimensions( p_context, &i_width, &i_height );
1150
1151     picture_t *p_pic = NULL;
1152     if (GetVlcChroma(&p_dec->fmt_out.video, p_context->pix_fmt) != VLC_SUCCESS)
1153         goto no_dr;
1154
1155     if (p_context->pix_fmt == PIX_FMT_PAL8)
1156         goto no_dr;
1157
1158     p_dec->fmt_out.i_codec = p_dec->fmt_out.video.i_chroma;
1159
1160     p_pic = ffmpeg_NewPictBuf( p_dec, p_context );
1161     if( !p_pic )
1162         goto no_dr;
1163
1164     if( p_pic->p[0].i_pitch / p_pic->p[0].i_pixel_pitch < i_width ||
1165         p_pic->p[0].i_lines < i_height )
1166         goto no_dr;
1167
1168     for( int i = 0; i < p_pic->i_planes; i++ )
1169     {
1170         unsigned i_align;
1171         switch( p_sys->i_codec_id )
1172         {
1173         case AV_CODEC_ID_SVQ1:
1174         case AV_CODEC_ID_VP5:
1175         case AV_CODEC_ID_VP6:
1176         case AV_CODEC_ID_VP6F:
1177         case AV_CODEC_ID_VP6A:
1178             i_align = 16;
1179             break;
1180         default:
1181             i_align = i == 0 ? 16 : 8;
1182             break;
1183         }
1184         if( p_pic->p[i].i_pitch % i_align )
1185             goto no_dr;
1186         if( (intptr_t)p_pic->p[i].p_pixels % i_align )
1187             goto no_dr;
1188     }
1189
1190     if( p_context->pix_fmt == PIX_FMT_YUV422P )
1191     {
1192         if( 2 * p_pic->p[1].i_pitch != p_pic->p[0].i_pitch ||
1193             2 * p_pic->p[2].i_pitch != p_pic->p[0].i_pitch )
1194             goto no_dr;
1195     }
1196
1197     return p_pic;
1198
1199 no_dr:
1200     if (p_pic)
1201         decoder_DeletePicture( p_dec, p_pic );
1202
1203     return NULL;
1204 }
1205
1206 static int ffmpeg_GetFrameBuf( struct AVCodecContext *p_context,
1207                                AVFrame *p_ff_pic )
1208 {
1209     decoder_t *p_dec = (decoder_t *)p_context->opaque;
1210     decoder_sys_t *p_sys = p_dec->p_sys;
1211
1212     /* */
1213     p_ff_pic->opaque = NULL;
1214 #if ! LIBAVCODEC_VERSION_CHECK(54, 34, 0, 79, 101)
1215     p_ff_pic->pkt_pts = p_context->pkt ? p_context->pkt->pts : AV_NOPTS_VALUE;
1216 #endif
1217 #if LIBAVCODEC_VERSION_MAJOR < 54
1218     p_ff_pic->age = 256*256*256*64;
1219 #endif
1220
1221     if( p_sys->p_va )
1222         return ffmpeg_va_GetFrameBuf(p_context, p_ff_pic);
1223
1224     if( !p_sys->b_direct_rendering )
1225         return avcodec_default_get_buffer( p_context, p_ff_pic );
1226
1227     wait_mt( p_sys );
1228     /* Some codecs set pix_fmt only after the 1st frame has been decoded,
1229      * so we need to check for direct rendering again. */
1230
1231     picture_t *p_pic = ffmpeg_dr_GetFrameBuf(p_context);
1232     if (!p_pic) {
1233         if( p_sys->i_direct_rendering_used != 0 )
1234         {
1235             msg_Warn( p_dec, "disabling direct rendering" );
1236             p_sys->i_direct_rendering_used = 0;
1237         }
1238
1239         post_mt( p_sys );
1240         return avcodec_default_get_buffer( p_context, p_ff_pic );
1241     }
1242
1243     if( p_sys->i_direct_rendering_used != 1 ) {
1244         msg_Dbg( p_dec, "using direct rendering" );
1245         p_sys->i_direct_rendering_used = 1;
1246     }
1247
1248     p_context->draw_horiz_band = NULL;
1249     post_mt( p_sys );
1250
1251     p_ff_pic->opaque = (void*)p_pic;
1252     p_ff_pic->type = FF_BUFFER_TYPE_USER;
1253     p_ff_pic->data[0] = p_pic->p[0].p_pixels;
1254     p_ff_pic->data[1] = p_pic->p[1].p_pixels;
1255     p_ff_pic->data[2] = p_pic->p[2].p_pixels;
1256     p_ff_pic->data[3] = NULL; /* alpha channel but I'm not sure */
1257
1258     p_ff_pic->linesize[0] = p_pic->p[0].i_pitch;
1259     p_ff_pic->linesize[1] = p_pic->p[1].i_pitch;
1260     p_ff_pic->linesize[2] = p_pic->p[2].i_pitch;
1261     p_ff_pic->linesize[3] = 0;
1262
1263     return 0;
1264 }
1265
1266 static void ffmpeg_ReleaseFrameBuf( struct AVCodecContext *p_context,
1267                                     AVFrame *p_ff_pic )
1268 {
1269     decoder_t *p_dec = (decoder_t *)p_context->opaque;
1270     decoder_sys_t *p_sys = p_dec->p_sys;
1271
1272     if( p_sys->p_va )
1273         vlc_va_Release( p_sys->p_va, p_ff_pic->opaque, p_ff_pic->data[0] );
1274     else if( p_ff_pic->opaque )
1275         decoder_UnlinkPicture( p_dec, (picture_t*)p_ff_pic->opaque);
1276     else if( p_ff_pic->type == FF_BUFFER_TYPE_INTERNAL )
1277         /* We can end up here without the AVFrame being allocated by
1278          * avcodec_default_get_buffer() if VA is used and the frame is
1279          * released when the decoder is closed
1280          */
1281         avcodec_default_release_buffer( p_context, p_ff_pic );
1282
1283     for( int i = 0; i < 4; i++ )
1284         p_ff_pic->data[i] = NULL;
1285 }
1286 #endif
1287
1288 static enum PixelFormat ffmpeg_GetFormat( AVCodecContext *p_context,
1289                                           const enum PixelFormat *pi_fmt )
1290 {
1291     decoder_t *p_dec = p_context->opaque;
1292     decoder_sys_t *p_sys = p_dec->p_sys;
1293     vlc_va_t *p_va = p_sys->p_va;
1294
1295     if( p_va != NULL )
1296         vlc_va_Delete( p_va );
1297
1298     /* Enumerate available formats */
1299     bool can_hwaccel = false;
1300     for( size_t i = 0; pi_fmt[i] != PIX_FMT_NONE; i++ )
1301     {
1302         const AVPixFmtDescriptor *dsc = av_pix_fmt_desc_get(pi_fmt[i]);
1303         if (dsc == NULL)
1304             continue;
1305         bool hwaccel = (dsc->flags & AV_PIX_FMT_FLAG_HWACCEL) != 0;
1306
1307         msg_Dbg( p_dec, "available %sware decoder output format %d (%s)",
1308                  hwaccel ? "hard" : "soft", pi_fmt[i], dsc->name );
1309         if (hwaccel)
1310             can_hwaccel = true;
1311     }
1312
1313     if (!can_hwaccel)
1314         goto end;
1315
1316     /* Profile and level information is needed now.
1317      * TODO: avoid code duplication with avcodec.c */
1318     if( p_context->profile != FF_PROFILE_UNKNOWN)
1319         p_dec->fmt_in.i_profile = p_context->profile;
1320     if( p_context->level != FF_LEVEL_UNKNOWN)
1321         p_dec->fmt_in.i_level = p_context->level;
1322
1323     p_va = vlc_va_New( VLC_OBJECT(p_dec), p_sys->i_codec_id, &p_dec->fmt_in );
1324     if( p_va == NULL )
1325         goto end;
1326
1327     for( size_t i = 0; pi_fmt[i] != PIX_FMT_NONE; i++ )
1328     {
1329         if( p_va->pix_fmt != pi_fmt[i] )
1330             continue;
1331
1332         /* We try to call vlc_va_Setup when possible to detect errors when
1333          * possible (later is too late) */
1334         if( p_context->width > 0 && p_context->height > 0
1335          && vlc_va_Setup( p_va, &p_context->hwaccel_context,
1336                           &p_dec->fmt_out.video.i_chroma,
1337                           p_context->width, p_context->height ) )
1338         {
1339             msg_Err( p_dec, "acceleration setup failure" );
1340             break;
1341         }
1342
1343         if( p_va->description )
1344             msg_Info( p_dec, "Using %s for hardware decoding.",
1345                       p_va->description );
1346
1347         /* FIXME this will disable direct rendering
1348          * even if a new pixel format is renegotiated
1349          */
1350         p_sys->b_direct_rendering = false;
1351         p_sys->p_va = p_va;
1352         p_context->draw_horiz_band = NULL;
1353         return pi_fmt[i];
1354     }
1355
1356     vlc_va_Delete( p_va );
1357
1358 end:
1359     /* Fallback to default behaviour */
1360     p_sys->p_va = NULL;
1361     return avcodec_default_get_format( p_context, pi_fmt );
1362 }