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