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