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