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