]> git.sesse.net Git - vlc/blob - src/input/decoder.c
decoder: fix data race in input_DecoderIsEmpty()
[vlc] / src / input / decoder.c
1 /*****************************************************************************
2  * decoder.c: Functions for the management of decoders
3  *****************************************************************************
4  * Copyright (C) 1999-2004 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Christophe Massiot <massiot@via.ecp.fr>
8  *          Gildas Bazin <gbazin@videolan.org>
9  *          Laurent Aimar <fenrir@via.ecp.fr>
10  *
11  * This program is free software; you can redistribute it and/or modify it
12  * under the terms of the GNU Lesser General Public License as published by
13  * the Free Software Foundation; either version 2.1 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19  * GNU Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public License
22  * along with this program; if not, write to the Free Software Foundation,
23  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32 #include <assert.h>
33
34 #include <vlc_common.h>
35
36 #include <vlc_block.h>
37 #include <vlc_vout.h>
38 #include <vlc_aout.h>
39 #include <vlc_sout.h>
40 #include <vlc_codec.h>
41 #include <vlc_spu.h>
42 #include <vlc_meta.h>
43 #include <vlc_dialog.h>
44 #include <vlc_modules.h>
45
46 #include "audio_output/aout_internal.h"
47 #include "stream_output/stream_output.h"
48 #include "input_internal.h"
49 #include "clock.h"
50 #include "decoder.h"
51 #include "event.h"
52 #include "resource.h"
53
54 #include "../video_output/vout_control.h"
55
56 static decoder_t *CreateDecoder( vlc_object_t *, input_thread_t *,
57                                  const es_format_t *, bool, input_resource_t *,
58                                  sout_instance_t *p_sout );
59 static void       DeleteDecoder( decoder_t * );
60
61 static void      *DecoderThread( void * );
62 static void       DecoderProcess( decoder_t *, block_t * );
63 static void       DecoderFlush( decoder_t * );
64 static void       DecoderSignalWait( decoder_t *, bool );
65
66 static void       DecoderUnsupportedCodec( decoder_t *, vlc_fourcc_t );
67
68 /* Buffers allocation callbacks for the decoders */
69 static int vout_update_format( decoder_t * );
70 static picture_t *vout_new_buffer( decoder_t * );
71 static int aout_update_format( decoder_t * );
72 static subpicture_t *spu_new_buffer( decoder_t *, const subpicture_updater_t * );
73
74 struct decoder_owner_sys_t
75 {
76     int64_t         i_preroll_end;
77
78     input_thread_t  *p_input;
79     input_resource_t*p_resource;
80     input_clock_t   *p_clock;
81     int             i_last_rate;
82
83     vout_thread_t   *p_spu_vout;
84     int              i_spu_channel;
85     int64_t          i_spu_order;
86
87     sout_instance_t         *p_sout;
88     sout_packetizer_input_t *p_sout_input;
89
90     vlc_thread_t     thread;
91
92     /* Some decoders require already packetized data (ie. not truncated) */
93     decoder_t *p_packetizer;
94     bool b_packetizer;
95
96     /* Current format in use by the output */
97     es_format_t    fmt;
98
99     /* */
100     bool           b_fmt_description;
101     vlc_meta_t     *p_description;
102
103     /* fifo */
104     block_fifo_t *p_fifo;
105
106     /* Lock for communication with decoder thread */
107     vlc_mutex_t lock;
108     vlc_cond_t  wait_request;
109     vlc_cond_t  wait_acknowledge;
110
111     /* -- These variables need locking on write(only) -- */
112     audio_output_t *p_aout;
113
114     vout_thread_t   *p_vout;
115
116     /* -- Theses variables need locking on read *and* write -- */
117     bool b_exit;
118
119     /* Pause */
120     bool b_paused;
121     struct
122     {
123         mtime_t i_date;
124         int     i_ignore;
125     } pause;
126
127     /* Waiting */
128     bool b_waiting;
129     bool b_first;
130     bool b_has_data;
131
132     /* Flushing */
133     bool b_flushing;
134
135     /* CC */
136     struct
137     {
138         bool b_supported;
139         bool pb_present[4];
140         decoder_t *pp_decoder[4];
141     } cc;
142
143     /* Delay */
144     mtime_t i_ts_delay;
145 };
146
147 /* Pictures which are DECODER_BOGUS_VIDEO_DELAY or more in advance probably have
148  * a bogus PTS and won't be displayed */
149 #define DECODER_BOGUS_VIDEO_DELAY                ((mtime_t)(DEFAULT_PTS_DELAY * 30))
150
151 /* */
152 #define DECODER_SPU_VOUT_WAIT_DURATION ((int)(0.200*CLOCK_FREQ))
153
154
155 /*****************************************************************************
156  * Public functions
157  *****************************************************************************/
158 picture_t *decoder_NewPicture( decoder_t *p_decoder )
159 {
160     if( decoder_UpdateVideoFormat( p_decoder ) )
161         return NULL;
162
163     picture_t *p_picture = p_decoder->pf_vout_buffer_new( p_decoder );
164     if( !p_picture )
165         msg_Warn( p_decoder, "can't get output picture" );
166     return p_picture;
167 }
168
169 block_t *decoder_NewAudioBuffer( decoder_t *dec, int samples )
170 {
171     if( decoder_UpdateAudioFormat( dec ) )
172         return NULL;
173
174     size_t length = samples * dec->fmt_out.audio.i_bytes_per_frame
175                             / dec->fmt_out.audio.i_frame_length;
176     block_t *block = block_Alloc( length );
177     if( likely(block != NULL) )
178     {
179         block->i_nb_samples = samples;
180         block->i_pts = block->i_length = 0;
181     }
182     return block;
183 }
184
185 subpicture_t *decoder_NewSubpicture( decoder_t *p_decoder,
186                                      const subpicture_updater_t *p_dyn )
187 {
188     subpicture_t *p_subpicture = p_decoder->pf_spu_buffer_new( p_decoder, p_dyn );
189     if( !p_subpicture )
190         msg_Warn( p_decoder, "can't get output subpicture" );
191     return p_subpicture;
192 }
193
194 /* decoder_GetInputAttachments:
195  */
196 int decoder_GetInputAttachments( decoder_t *p_dec,
197                                  input_attachment_t ***ppp_attachment,
198                                  int *pi_attachment )
199 {
200     if( !p_dec->pf_get_attachments )
201         return VLC_EGENERIC;
202
203     return p_dec->pf_get_attachments( p_dec, ppp_attachment, pi_attachment );
204 }
205 /* decoder_GetDisplayDate:
206  */
207 mtime_t decoder_GetDisplayDate( decoder_t *p_dec, mtime_t i_ts )
208 {
209     if( !p_dec->pf_get_display_date )
210         return VLC_TS_INVALID;
211
212     return p_dec->pf_get_display_date( p_dec, i_ts );
213 }
214 /* decoder_GetDisplayRate:
215  */
216 int decoder_GetDisplayRate( decoder_t *p_dec )
217 {
218     if( !p_dec->pf_get_display_rate )
219         return INPUT_RATE_DEFAULT;
220
221     return p_dec->pf_get_display_rate( p_dec );
222 }
223
224 /* TODO: pass p_sout through p_resource? -- Courmisch */
225 static decoder_t *decoder_New( vlc_object_t *p_parent, input_thread_t *p_input,
226                                const es_format_t *fmt, input_clock_t *p_clock,
227                                input_resource_t *p_resource,
228                                sout_instance_t *p_sout  )
229 {
230     decoder_t *p_dec = NULL;
231     const char *psz_type = p_sout ? N_("packetizer") : N_("decoder");
232     int i_priority;
233
234     /* Create the decoder configuration structure */
235     p_dec = CreateDecoder( p_parent, p_input, fmt,
236                            p_sout != NULL, p_resource, p_sout );
237     if( p_dec == NULL )
238     {
239         msg_Err( p_parent, "could not create %s", psz_type );
240         dialog_Fatal( p_parent, _("Streaming / Transcoding failed"),
241                       _("VLC could not open the %s module."),
242                       vlc_gettext( psz_type ) );
243         return NULL;
244     }
245
246     if( !p_dec->p_module )
247     {
248         DecoderUnsupportedCodec( p_dec, fmt->i_codec );
249
250         DeleteDecoder( p_dec );
251         return NULL;
252     }
253
254     p_dec->p_owner->p_clock = p_clock;
255     assert( p_dec->fmt_out.i_cat != UNKNOWN_ES );
256
257     if( p_dec->fmt_out.i_cat == AUDIO_ES )
258         i_priority = VLC_THREAD_PRIORITY_AUDIO;
259     else
260         i_priority = VLC_THREAD_PRIORITY_VIDEO;
261
262     /* Spawn the decoder thread */
263     if( vlc_clone( &p_dec->p_owner->thread, DecoderThread, p_dec, i_priority ) )
264     {
265         msg_Err( p_dec, "cannot spawn decoder thread" );
266         module_unneed( p_dec, p_dec->p_module );
267         DeleteDecoder( p_dec );
268         return NULL;
269     }
270
271     return p_dec;
272 }
273
274
275 /**
276  * Spawns a new decoder thread from the input thread
277  *
278  * \param p_input the input thread
279  * \param p_es the es descriptor
280  * \return the spawned decoder object
281  */
282 decoder_t *input_DecoderNew( input_thread_t *p_input,
283                              es_format_t *fmt, input_clock_t *p_clock,
284                              sout_instance_t *p_sout  )
285 {
286     return decoder_New( VLC_OBJECT(p_input), p_input, fmt, p_clock,
287                         p_input->p->p_resource, p_sout );
288 }
289
290 /**
291  * Spawn a decoder thread outside of the input thread.
292  */
293 decoder_t *input_DecoderCreate( vlc_object_t *p_parent, const es_format_t *fmt,
294                                 input_resource_t *p_resource )
295 {
296     return decoder_New( p_parent, NULL, fmt, NULL, p_resource, NULL );
297 }
298
299
300 /**
301  * Kills a decoder thread and waits until it's finished
302  *
303  * \param p_input the input thread
304  * \param p_es the es descriptor
305  * \return nothing
306  */
307 void input_DecoderDelete( decoder_t *p_dec )
308 {
309     decoder_owner_sys_t *p_owner = p_dec->p_owner;
310
311     vlc_cancel( p_owner->thread );
312
313     /* Make sure we aren't paused/waiting/decoding anymore */
314     vlc_mutex_lock( &p_owner->lock );
315     p_owner->b_paused = false;
316     p_owner->b_waiting = false;
317     p_owner->b_flushing = true;
318     p_owner->b_exit = true;
319     vlc_cond_signal( &p_owner->wait_request );
320     vlc_mutex_unlock( &p_owner->lock );
321
322     vlc_join( p_owner->thread, NULL );
323
324     module_unneed( p_dec, p_dec->p_module );
325
326     /* */
327     if( p_dec->p_owner->cc.b_supported )
328     {
329         int i;
330         for( i = 0; i < 4; i++ )
331             input_DecoderSetCcState( p_dec, false, i );
332     }
333
334     /* Delete decoder */
335     DeleteDecoder( p_dec );
336 }
337
338 /**
339  * Put a block_t in the decoder's fifo.
340  * Thread-safe w.r.t. the decoder. May be a cancellation point.
341  *
342  * \param p_dec the decoder object
343  * \param p_block the data block
344  */
345 void input_DecoderDecode( decoder_t *p_dec, block_t *p_block, bool b_do_pace )
346 {
347     decoder_owner_sys_t *p_owner = p_dec->p_owner;
348
349     if( b_do_pace )
350     {
351         /* The fifo is not consumed when waiting and so will
352          * deadlock vlc.
353          * There is no need to lock as b_waiting is never modified
354          * inside decoder thread. */
355         if( !p_owner->b_waiting )
356             block_FifoPace( p_owner->p_fifo, 10, SIZE_MAX );
357     }
358 #ifdef __arm__
359     else if( block_FifoSize( p_owner->p_fifo ) > 50*1024*1024 /* 50 MiB */ )
360 #else
361     else if( block_FifoSize( p_owner->p_fifo ) > 400*1024*1024 /* 400 MiB, ie ~ 50mb/s for 60s */ )
362 #endif
363     {
364         /* FIXME: ideally we would check the time amount of data
365          * in the FIFO instead of its size. */
366         msg_Warn( p_dec, "decoder/packetizer fifo full (data not "
367                   "consumed quickly enough), resetting fifo!" );
368         block_FifoEmpty( p_owner->p_fifo );
369     }
370
371     block_FifoPut( p_owner->p_fifo, p_block );
372 }
373
374 bool input_DecoderIsEmpty( decoder_t * p_dec )
375 {
376     decoder_owner_sys_t *p_owner = p_dec->p_owner;
377     assert( !p_owner->b_waiting );
378
379     bool b_empty = block_FifoCount( p_dec->p_owner->p_fifo ) <= 0;
380
381     if( b_empty )
382     {
383         vlc_mutex_lock( &p_owner->lock );
384         /* TODO subtitles support */
385         if( p_owner->fmt.i_cat == VIDEO_ES && p_owner->p_vout )
386             b_empty = vout_IsEmpty( p_owner->p_vout );
387         else if( p_owner->fmt.i_cat == AUDIO_ES && p_owner->p_aout )
388             b_empty = aout_DecIsEmpty( p_owner->p_aout );
389         vlc_mutex_unlock( &p_owner->lock );
390     }
391     return b_empty;
392 }
393
394 void input_DecoderIsCcPresent( decoder_t *p_dec, bool pb_present[4] )
395 {
396     decoder_owner_sys_t *p_owner = p_dec->p_owner;
397     int i;
398
399     vlc_mutex_lock( &p_owner->lock );
400     for( i = 0; i < 4; i++ )
401         pb_present[i] =  p_owner->cc.pb_present[i];
402     vlc_mutex_unlock( &p_owner->lock );
403 }
404 int input_DecoderSetCcState( decoder_t *p_dec, bool b_decode, int i_channel )
405 {
406     decoder_owner_sys_t *p_owner = p_dec->p_owner;
407
408     //msg_Warn( p_dec, "input_DecoderSetCcState: %d @%d", b_decode, i_channel );
409
410     if( i_channel < 0 || i_channel >= 4 || !p_owner->cc.pb_present[i_channel] )
411         return VLC_EGENERIC;
412
413     if( b_decode )
414     {
415         static const vlc_fourcc_t fcc[4] = {
416             VLC_FOURCC('c', 'c', '1', ' '),
417             VLC_FOURCC('c', 'c', '2', ' '),
418             VLC_FOURCC('c', 'c', '3', ' '),
419             VLC_FOURCC('c', 'c', '4', ' '),
420         };
421         decoder_t *p_cc;
422         es_format_t fmt;
423
424         es_format_Init( &fmt, SPU_ES, fcc[i_channel] );
425         p_cc = input_DecoderNew( p_owner->p_input, &fmt,
426                               p_dec->p_owner->p_clock, p_owner->p_sout );
427         if( !p_cc )
428         {
429             msg_Err( p_dec, "could not create decoder" );
430             dialog_Fatal( p_dec, _("Streaming / Transcoding failed"), "%s",
431                           _("VLC could not open the decoder module.") );
432             return VLC_EGENERIC;
433         }
434         else if( !p_cc->p_module )
435         {
436             DecoderUnsupportedCodec( p_dec, fcc[i_channel] );
437             input_DecoderDelete(p_cc);
438             return VLC_EGENERIC;
439         }
440         p_cc->p_owner->p_clock = p_owner->p_clock;
441
442         vlc_mutex_lock( &p_owner->lock );
443         p_owner->cc.pp_decoder[i_channel] = p_cc;
444         vlc_mutex_unlock( &p_owner->lock );
445     }
446     else
447     {
448         decoder_t *p_cc;
449
450         vlc_mutex_lock( &p_owner->lock );
451         p_cc = p_owner->cc.pp_decoder[i_channel];
452         p_owner->cc.pp_decoder[i_channel] = NULL;
453         vlc_mutex_unlock( &p_owner->lock );
454
455         if( p_cc )
456             input_DecoderDelete(p_cc);
457     }
458     return VLC_SUCCESS;
459 }
460 int input_DecoderGetCcState( decoder_t *p_dec, bool *pb_decode, int i_channel )
461 {
462     decoder_owner_sys_t *p_owner = p_dec->p_owner;
463
464     *pb_decode = false;
465     if( i_channel < 0 || i_channel >= 4 || !p_owner->cc.pb_present[i_channel] )
466         return VLC_EGENERIC;
467
468     vlc_mutex_lock( &p_owner->lock );
469     *pb_decode = p_owner->cc.pp_decoder[i_channel] != NULL;
470     vlc_mutex_unlock( &p_owner->lock );
471     return VLC_EGENERIC;
472 }
473
474 void input_DecoderChangePause( decoder_t *p_dec, bool b_paused, mtime_t i_date )
475 {
476     decoder_owner_sys_t *p_owner = p_dec->p_owner;
477
478     vlc_mutex_lock( &p_owner->lock );
479     /* Normally, p_owner->b_paused != b_paused here. But if a track is added
480      * while the input is paused (e.g. add sub file), then b_paused is
481      * (incorrectly) false. */
482     if( likely(p_owner->b_paused != b_paused) ) {
483         p_owner->b_paused = b_paused;
484         p_owner->pause.i_date = i_date;
485         p_owner->pause.i_ignore = 0;
486         vlc_cond_signal( &p_owner->wait_request );
487
488         /* XXX only audio and video output have to be paused.
489          * - for sout it is useless
490          * - for subs, it is done by the vout
491          */
492         if( p_dec->fmt_out.i_cat == AUDIO_ES )
493         {
494             if( p_owner->p_aout )
495                 aout_DecChangePause( p_owner->p_aout, b_paused, i_date );
496         }
497         else if( p_dec->fmt_out.i_cat == VIDEO_ES )
498         {
499             if( p_owner->p_vout )
500                 vout_ChangePause( p_owner->p_vout, b_paused, i_date );
501         }
502     }
503     vlc_mutex_unlock( &p_owner->lock );
504 }
505
506 void input_DecoderChangeDelay( decoder_t *p_dec, mtime_t i_delay )
507 {
508     decoder_owner_sys_t *p_owner = p_dec->p_owner;
509
510     vlc_mutex_lock( &p_owner->lock );
511     p_owner->i_ts_delay = i_delay;
512     vlc_mutex_unlock( &p_owner->lock );
513 }
514
515 void input_DecoderStartWait( decoder_t *p_dec )
516 {
517     decoder_owner_sys_t *p_owner = p_dec->p_owner;
518
519     vlc_mutex_lock( &p_owner->lock );
520
521     DecoderFlush( p_dec );
522
523     p_owner->b_first = true;
524     p_owner->b_has_data = false;
525
526     p_owner->b_waiting = true;
527
528     vlc_cond_signal( &p_owner->wait_request );
529
530     vlc_mutex_unlock( &p_owner->lock );
531 }
532
533 void input_DecoderStopWait( decoder_t *p_dec )
534 {
535     decoder_owner_sys_t *p_owner = p_dec->p_owner;
536
537     vlc_mutex_lock( &p_owner->lock );
538
539     p_owner->b_waiting = false;
540
541     vlc_cond_signal( &p_owner->wait_request );
542
543     vlc_mutex_unlock( &p_owner->lock );
544 }
545
546 void input_DecoderWait( decoder_t *p_dec )
547 {
548     decoder_owner_sys_t *p_owner = p_dec->p_owner;
549
550     vlc_mutex_lock( &p_owner->lock );
551
552     while( p_owner->b_waiting && !p_owner->b_has_data )
553     {
554         block_FifoWake( p_owner->p_fifo );
555         vlc_cond_wait( &p_owner->wait_acknowledge, &p_owner->lock );
556     }
557
558     vlc_mutex_unlock( &p_owner->lock );
559 }
560
561 void input_DecoderFrameNext( decoder_t *p_dec, mtime_t *pi_duration )
562 {
563     decoder_owner_sys_t *p_owner = p_dec->p_owner;
564
565     *pi_duration = 0;
566
567     vlc_mutex_lock( &p_owner->lock );
568     if( p_dec->fmt_out.i_cat == VIDEO_ES )
569     {
570         if( p_owner->b_paused && p_owner->p_vout )
571         {
572             vout_NextPicture( p_owner->p_vout, pi_duration );
573             p_owner->pause.i_ignore++;
574             vlc_cond_signal( &p_owner->wait_request );
575         }
576     }
577     else
578     {
579         /* TODO subtitle should not be flushed */
580         DecoderFlush( p_dec );
581     }
582     vlc_mutex_unlock( &p_owner->lock );
583 }
584
585 bool input_DecoderHasFormatChanged( decoder_t *p_dec, es_format_t *p_fmt, vlc_meta_t **pp_meta )
586 {
587     decoder_owner_sys_t *p_owner = p_dec->p_owner;
588     bool b_changed;
589
590     vlc_mutex_lock( &p_owner->lock );
591     b_changed = p_owner->b_fmt_description;
592     if( b_changed )
593     {
594         if( p_fmt != NULL )
595             es_format_Copy( p_fmt, &p_owner->fmt );
596
597         if( pp_meta )
598         {
599             *pp_meta = NULL;
600             if( p_owner->p_description )
601             {
602                 *pp_meta = vlc_meta_New();
603                 if( *pp_meta )
604                     vlc_meta_Merge( *pp_meta, p_owner->p_description );
605             }
606         }
607         p_owner->b_fmt_description = false;
608     }
609     vlc_mutex_unlock( &p_owner->lock );
610     return b_changed;
611 }
612
613 size_t input_DecoderGetFifoSize( decoder_t *p_dec )
614 {
615     decoder_owner_sys_t *p_owner = p_dec->p_owner;
616
617     return block_FifoSize( p_owner->p_fifo );
618 }
619
620 void input_DecoderGetObjects( decoder_t *p_dec,
621                               vout_thread_t **pp_vout, audio_output_t **pp_aout )
622 {
623     decoder_owner_sys_t *p_owner = p_dec->p_owner;
624
625     vlc_mutex_lock( &p_owner->lock );
626     if( pp_vout )
627         *pp_vout = p_owner->p_vout ? vlc_object_hold( p_owner->p_vout ) : NULL;
628     if( pp_aout )
629         *pp_aout = p_owner->p_aout ? vlc_object_hold( p_owner->p_aout ) : NULL;
630     vlc_mutex_unlock( &p_owner->lock );
631 }
632
633 /*****************************************************************************
634  * Internal functions
635  *****************************************************************************/
636 static int DecoderGetInputAttachments( decoder_t *p_dec,
637                                        input_attachment_t ***ppp_attachment,
638                                        int *pi_attachment )
639 {
640     input_thread_t *p_input = p_dec->p_owner->p_input;
641
642     if( unlikely(p_input == NULL) )
643         return VLC_ENOOBJ;
644     return input_Control( p_input, INPUT_GET_ATTACHMENTS,
645                           ppp_attachment, pi_attachment );
646 }
647 static mtime_t DecoderGetDisplayDate( decoder_t *p_dec, mtime_t i_ts )
648 {
649     decoder_owner_sys_t *p_owner = p_dec->p_owner;
650
651     vlc_mutex_lock( &p_owner->lock );
652     if( p_owner->b_waiting || p_owner->b_paused )
653         i_ts = VLC_TS_INVALID;
654     vlc_mutex_unlock( &p_owner->lock );
655
656     if( !p_owner->p_clock || i_ts <= VLC_TS_INVALID )
657         return i_ts;
658
659     if( input_clock_ConvertTS( VLC_OBJECT(p_dec), p_owner->p_clock, NULL, &i_ts, NULL, INT64_MAX ) ) {
660         msg_Err(p_dec, "Could not get display date for timestamp %"PRId64"", i_ts);
661         return VLC_TS_INVALID;
662     }
663
664     return i_ts;
665 }
666 static int DecoderGetDisplayRate( decoder_t *p_dec )
667 {
668     decoder_owner_sys_t *p_owner = p_dec->p_owner;
669
670     if( !p_owner->p_clock )
671         return INPUT_RATE_DEFAULT;
672     return input_clock_GetRate( p_owner->p_clock );
673 }
674
675 /* */
676 static void DecoderUnsupportedCodec( decoder_t *p_dec, vlc_fourcc_t codec )
677 {
678     if (codec != VLC_FOURCC('u','n','d','f')) {
679         const char *desc = vlc_fourcc_GetDescription(p_dec->fmt_in.i_cat, codec);
680         if (!desc || !*desc)
681             desc = N_("No description for this codec");
682         msg_Err( p_dec, "Codec `%4.4s' (%s) is not supported.", (char*)&codec, desc );
683         dialog_Fatal( p_dec, _("Codec not supported"),
684                 _("VLC could not decode the format \"%4.4s\" (%s)"),
685                 (char*)&codec, desc );
686     } else {
687         msg_Err( p_dec, "could not identify codec" );
688         dialog_Fatal( p_dec, _("Unidentified codec"),
689             _("VLC could not identify the audio or video codec" ) );
690     }
691 }
692
693
694 /**
695  * Create a decoder object
696  *
697  * \param p_input the input thread
698  * \param p_es the es descriptor
699  * \param b_packetizer instead of a decoder
700  * \return the decoder object
701  */
702 static decoder_t * CreateDecoder( vlc_object_t *p_parent,
703                                   input_thread_t *p_input,
704                                   const es_format_t *fmt, bool b_packetizer,
705                                   input_resource_t *p_resource,
706                                   sout_instance_t *p_sout )
707 {
708     decoder_t *p_dec;
709     decoder_owner_sys_t *p_owner;
710     es_format_t null_es_format;
711
712     p_dec = vlc_custom_create( p_parent, sizeof( *p_dec ), "decoder" );
713     if( p_dec == NULL )
714         return NULL;
715
716     p_dec->pf_decode_audio = NULL;
717     p_dec->pf_decode_video = NULL;
718     p_dec->pf_decode_sub = NULL;
719     p_dec->pf_get_cc = NULL;
720     p_dec->pf_packetize = NULL;
721
722     /* Initialize the decoder */
723     p_dec->p_module = NULL;
724
725     memset( &null_es_format, 0, sizeof(es_format_t) );
726     es_format_Copy( &p_dec->fmt_in, fmt );
727     es_format_Copy( &p_dec->fmt_out, &null_es_format );
728
729     p_dec->p_description = NULL;
730
731     /* Allocate our private structure for the decoder */
732     p_dec->p_owner = p_owner = malloc( sizeof( decoder_owner_sys_t ) );
733     if( unlikely(p_owner == NULL) )
734     {
735         vlc_object_release( p_dec );
736         return NULL;
737     }
738     p_owner->i_preroll_end = VLC_TS_INVALID;
739     p_owner->i_last_rate = INPUT_RATE_DEFAULT;
740     p_owner->p_input = p_input;
741     p_owner->p_resource = p_resource;
742     p_owner->p_aout = NULL;
743     p_owner->p_vout = NULL;
744     p_owner->p_spu_vout = NULL;
745     p_owner->i_spu_channel = 0;
746     p_owner->i_spu_order = 0;
747     p_owner->p_sout = p_sout;
748     p_owner->p_sout_input = NULL;
749     p_owner->p_packetizer = NULL;
750     p_owner->b_packetizer = b_packetizer;
751     es_format_Init( &p_owner->fmt, UNKNOWN_ES, 0 );
752
753     /* decoder fifo */
754     p_owner->p_fifo = block_FifoNew();
755     if( unlikely(p_owner->p_fifo == NULL) )
756     {
757         free( p_owner );
758         vlc_object_release( p_dec );
759         return NULL;
760     }
761
762     /* Set buffers allocation callbacks for the decoders */
763     p_dec->pf_aout_format_update = aout_update_format;
764     p_dec->pf_vout_format_update = vout_update_format;
765     p_dec->pf_vout_buffer_new = vout_new_buffer;
766     p_dec->pf_spu_buffer_new  = spu_new_buffer;
767     /* */
768     p_dec->pf_get_attachments  = DecoderGetInputAttachments;
769     p_dec->pf_get_display_date = DecoderGetDisplayDate;
770     p_dec->pf_get_display_rate = DecoderGetDisplayRate;
771
772     /* Find a suitable decoder/packetizer module */
773     if( !b_packetizer )
774         p_dec->p_module = module_need( p_dec, "decoder", "$codec", false );
775     else
776         p_dec->p_module = module_need( p_dec, "packetizer", "$packetizer", false );
777
778     /* Check if decoder requires already packetized data */
779     if( !b_packetizer &&
780         p_dec->b_need_packetized && !p_dec->fmt_in.b_packetized )
781     {
782         p_owner->p_packetizer =
783             vlc_custom_create( p_parent, sizeof( decoder_t ), "packetizer" );
784         if( p_owner->p_packetizer )
785         {
786             es_format_Copy( &p_owner->p_packetizer->fmt_in,
787                             &p_dec->fmt_in );
788
789             es_format_Copy( &p_owner->p_packetizer->fmt_out,
790                             &null_es_format );
791
792             p_owner->p_packetizer->p_module =
793                 module_need( p_owner->p_packetizer,
794                              "packetizer", "$packetizer", false );
795
796             if( !p_owner->p_packetizer->p_module )
797             {
798                 es_format_Clean( &p_owner->p_packetizer->fmt_in );
799                 vlc_object_release( p_owner->p_packetizer );
800                 p_owner->p_packetizer = NULL;
801             }
802         }
803     }
804
805     /* Copy ourself the input replay gain */
806     if( fmt->i_cat == AUDIO_ES )
807     {
808         for( unsigned i = 0; i < AUDIO_REPLAY_GAIN_MAX; i++ )
809         {
810             if( !p_dec->fmt_out.audio_replay_gain.pb_peak[i] )
811             {
812                 p_dec->fmt_out.audio_replay_gain.pb_peak[i] = fmt->audio_replay_gain.pb_peak[i];
813                 p_dec->fmt_out.audio_replay_gain.pf_peak[i] = fmt->audio_replay_gain.pf_peak[i];
814             }
815             if( !p_dec->fmt_out.audio_replay_gain.pb_gain[i] )
816             {
817                 p_dec->fmt_out.audio_replay_gain.pb_gain[i] = fmt->audio_replay_gain.pb_gain[i];
818                 p_dec->fmt_out.audio_replay_gain.pf_gain[i] = fmt->audio_replay_gain.pf_gain[i];
819             }
820         }
821     }
822
823     /* */
824     vlc_mutex_init( &p_owner->lock );
825     vlc_cond_init( &p_owner->wait_request );
826     vlc_cond_init( &p_owner->wait_acknowledge );
827
828     p_owner->b_fmt_description = false;
829     p_owner->p_description = NULL;
830
831     p_owner->b_exit = false;
832
833     p_owner->b_paused = false;
834     p_owner->pause.i_date = VLC_TS_INVALID;
835     p_owner->pause.i_ignore = 0;
836
837     p_owner->b_waiting = false;
838     p_owner->b_first = true;
839     p_owner->b_has_data = false;
840
841     p_owner->b_flushing = false;
842
843     /* */
844     p_owner->cc.b_supported = false;
845     if( !b_packetizer )
846     {
847         if( p_owner->p_packetizer && p_owner->p_packetizer->pf_get_cc )
848             p_owner->cc.b_supported = true;
849         if( p_dec->pf_get_cc )
850             p_owner->cc.b_supported = true;
851     }
852
853     for( unsigned i = 0; i < 4; i++ )
854     {
855         p_owner->cc.pb_present[i] = false;
856         p_owner->cc.pp_decoder[i] = NULL;
857     }
858     p_owner->i_ts_delay = 0;
859     return p_dec;
860 }
861
862 /**
863  * The decoding main loop
864  *
865  * \param p_dec the decoder
866  */
867 static void *DecoderThread( void *p_data )
868 {
869     decoder_t *p_dec = (decoder_t *)p_data;
870     decoder_owner_sys_t *p_owner = p_dec->p_owner;
871
872     /* The decoder's main loop */
873     for( ;; )
874     {
875         block_t *p_block = block_FifoGet( p_owner->p_fifo );
876
877         /* Make sure there is no cancellation point other than this one^^.
878          * If you need one, be sure to push cleanup of p_block. */
879         bool end_wait = !p_block || p_block->i_flags & BLOCK_FLAG_CORE_EOS;
880         DecoderSignalWait( p_dec, end_wait );
881         if (end_wait)
882             input_DecoderStopWait( p_dec );
883
884         if( p_block )
885         {
886             int canc = vlc_savecancel();
887
888             if( p_block->i_flags & BLOCK_FLAG_CORE_EOS )
889             {
890                 /* calling DecoderProcess() with NULL block will make
891                  * decoders/packetizers flush their buffers */
892                 block_Release( p_block );
893                 p_block = NULL;
894             }
895
896             DecoderProcess( p_dec, p_block );
897
898             vlc_restorecancel( canc );
899         }
900     }
901     return NULL;
902 }
903
904 static block_t *DecoderBlockFlushNew()
905 {
906     block_t *p_null = block_Alloc( 128 );
907     if( !p_null )
908         return NULL;
909
910     p_null->i_flags |= BLOCK_FLAG_DISCONTINUITY |
911                        BLOCK_FLAG_CORRUPTED |
912                        BLOCK_FLAG_CORE_FLUSH;
913     memset( p_null->p_buffer, 0, p_null->i_buffer );
914
915     return p_null;
916 }
917
918 static void DecoderFlush( decoder_t *p_dec )
919 {
920     decoder_owner_sys_t *p_owner = p_dec->p_owner;
921
922     vlc_assert_locked( &p_owner->lock );
923
924     /* Empty the fifo */
925     block_FifoEmpty( p_owner->p_fifo );
926
927     p_owner->b_waiting = false;
928     /* Monitor for flush end */
929     p_owner->b_flushing = true;
930     vlc_cond_signal( &p_owner->wait_request );
931
932     /* Send a special block */
933     block_t *p_null = DecoderBlockFlushNew();
934     if( !p_null )
935         return;
936     input_DecoderDecode( p_dec, p_null, false );
937
938     /* */
939     while( p_owner->b_flushing )
940         vlc_cond_wait( &p_owner->wait_acknowledge, &p_owner->lock );
941 }
942
943 static void DecoderSignalWait( decoder_t *p_dec, bool b_has_data )
944 {
945     decoder_owner_sys_t *p_owner = p_dec->p_owner;
946
947     vlc_mutex_lock( &p_owner->lock );
948
949     if( p_owner->b_waiting )
950     {
951         if( b_has_data )
952             p_owner->b_has_data = true;
953         vlc_cond_signal( &p_owner->wait_acknowledge );
954     }
955
956     vlc_mutex_unlock( &p_owner->lock );
957 }
958
959 static bool DecoderIsFlushing( decoder_t *p_dec )
960 {
961     decoder_owner_sys_t *p_owner = p_dec->p_owner;
962     bool b_flushing;
963
964     vlc_mutex_lock( &p_owner->lock );
965
966     b_flushing = p_owner->b_flushing;
967
968     vlc_mutex_unlock( &p_owner->lock );
969
970     return b_flushing;
971 }
972
973 static bool DecoderWaitUnblock( decoder_t *p_dec )
974 {
975     decoder_owner_sys_t *p_owner = p_dec->p_owner;
976
977     vlc_assert_locked( &p_owner->lock );
978
979     for( ;; )
980     {
981         if( p_owner->b_flushing )
982             break;
983         if( p_owner->b_paused )
984         {
985             if( p_owner->b_waiting && !p_owner->b_has_data )
986                 break;
987             if( p_owner->pause.i_ignore > 0 )
988             {
989                 p_owner->pause.i_ignore--;
990                 break;
991             }
992         }
993         else
994         {
995             if( !p_owner->b_waiting || !p_owner->b_has_data )
996                 break;
997         }
998         vlc_cond_wait( &p_owner->wait_request, &p_owner->lock );
999     }
1000
1001     return p_owner->b_flushing;
1002 }
1003
1004 static inline void DecoderUpdatePreroll( int64_t *pi_preroll, const block_t *p )
1005 {
1006     if( p->i_flags & (BLOCK_FLAG_PREROLL|BLOCK_FLAG_DISCONTINUITY) )
1007         *pi_preroll = INT64_MAX;
1008     else if( p->i_dts > VLC_TS_INVALID )
1009         *pi_preroll = __MIN( *pi_preroll, p->i_dts );
1010     else if( p->i_pts > VLC_TS_INVALID )
1011         *pi_preroll = __MIN( *pi_preroll, p->i_pts );
1012 }
1013
1014 static void DecoderFixTs( decoder_t *p_dec, mtime_t *pi_ts0, mtime_t *pi_ts1,
1015                           mtime_t *pi_duration, int *pi_rate, mtime_t i_ts_bound )
1016 {
1017     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1018     input_clock_t   *p_clock = p_owner->p_clock;
1019
1020     vlc_assert_locked( &p_owner->lock );
1021
1022     const mtime_t i_es_delay = p_owner->i_ts_delay;
1023
1024     if( !p_clock )
1025         return;
1026
1027     const bool b_ephemere = pi_ts1 && *pi_ts0 == *pi_ts1;
1028     int i_rate;
1029
1030     if( *pi_ts0 > VLC_TS_INVALID )
1031     {
1032         *pi_ts0 += i_es_delay;
1033         if( pi_ts1 && *pi_ts1 > VLC_TS_INVALID )
1034             *pi_ts1 += i_es_delay;
1035         if( input_clock_ConvertTS( VLC_OBJECT(p_dec), p_clock, &i_rate, pi_ts0, pi_ts1, i_ts_bound ) ) {
1036             if( pi_ts1 != NULL )
1037                 msg_Err(p_dec, "Could not convert timestamps %"PRId64
1038                         ", %"PRId64"", *pi_ts0, *pi_ts1);
1039             else
1040                 msg_Err(p_dec, "Could not convert timestamp %"PRId64, *pi_ts0);
1041             *pi_ts0 = VLC_TS_INVALID;
1042         }
1043     }
1044     else
1045     {
1046         i_rate = input_clock_GetRate( p_clock );
1047     }
1048
1049     /* Do not create ephemere data because of rounding errors */
1050     if( !b_ephemere && pi_ts1 && *pi_ts0 == *pi_ts1 )
1051         *pi_ts1 += 1;
1052
1053     if( pi_duration )
1054         *pi_duration = ( *pi_duration * i_rate + INPUT_RATE_DEFAULT-1 )
1055             / INPUT_RATE_DEFAULT;
1056
1057     if( pi_rate )
1058         *pi_rate = i_rate;
1059 }
1060
1061 static bool DecoderIsExitRequested( decoder_t *p_dec )
1062 {
1063     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1064
1065     vlc_mutex_lock( &p_owner->lock );
1066     bool b_exit = p_owner->b_exit;
1067     vlc_mutex_unlock( &p_owner->lock );
1068
1069     return b_exit;
1070 }
1071
1072 /**
1073  * If *pb_reject, it does nothing, otherwise it waits for the given
1074  * deadline or a flush request (in which case it set *pi_reject to true.
1075  */
1076 static void DecoderWaitDate( decoder_t *p_dec,
1077                              bool *pb_reject, mtime_t i_deadline )
1078 {
1079     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1080
1081     vlc_assert_locked( &p_owner->lock );
1082
1083     if( *pb_reject || i_deadline < 0 )
1084         return;
1085
1086     do
1087     {
1088         if( p_owner->b_flushing || p_owner->b_exit )
1089         {
1090             *pb_reject = true;
1091             break;
1092         }
1093     }
1094     while( vlc_cond_timedwait( &p_owner->wait_request, &p_owner->lock,
1095                                i_deadline ) == 0 );
1096 }
1097
1098 static void DecoderPlayAudio( decoder_t *p_dec, block_t *p_audio,
1099                               int *pi_played_sum, int *pi_lost_sum )
1100 {
1101     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1102     audio_output_t *p_aout = p_owner->p_aout;
1103
1104     /* */
1105     if( p_audio && p_audio->i_pts <= VLC_TS_INVALID ) // FIXME --VLC_TS_INVALID verify audio_output/*
1106     {
1107         msg_Warn( p_dec, "non-dated audio buffer received" );
1108         *pi_lost_sum += 1;
1109         block_Release( p_audio );
1110         return;
1111     }
1112
1113     /* */
1114     vlc_mutex_lock( &p_owner->lock );
1115
1116     if( p_audio && p_owner->b_waiting )
1117     {
1118         p_owner->b_has_data = true;
1119         vlc_cond_signal( &p_owner->wait_acknowledge );
1120     }
1121
1122     for( ;; )
1123     {
1124         bool b_paused;
1125
1126         bool b_reject = DecoderWaitUnblock( p_dec );
1127
1128         b_paused = p_owner->b_paused;
1129
1130         if (!p_audio)
1131             break;
1132
1133         /* */
1134         int i_rate = INPUT_RATE_DEFAULT;
1135
1136         DecoderFixTs( p_dec, &p_audio->i_pts, NULL, &p_audio->i_length,
1137                       &i_rate, AOUT_MAX_ADVANCE_TIME );
1138
1139         if( p_audio->i_pts <= VLC_TS_INVALID
1140          || i_rate < INPUT_RATE_DEFAULT/AOUT_MAX_INPUT_RATE
1141          || i_rate > INPUT_RATE_DEFAULT*AOUT_MAX_INPUT_RATE )
1142             b_reject = true;
1143
1144         DecoderWaitDate( p_dec, &b_reject,
1145                          p_audio->i_pts - AOUT_MAX_PREPARE_TIME );
1146
1147         if( unlikely(p_owner->b_paused != b_paused) )
1148             continue; /* race with input thread? retry... */
1149         if( p_aout == NULL )
1150             b_reject = true;
1151
1152         if( !b_reject )
1153         {
1154             assert( !p_owner->b_paused );
1155             if( !aout_DecPlay( p_aout, p_audio, i_rate ) )
1156                 *pi_played_sum += 1;
1157             *pi_lost_sum += aout_DecGetResetLost( p_aout );
1158         }
1159         else
1160         {
1161             msg_Dbg( p_dec, "discarded audio buffer" );
1162             *pi_lost_sum += 1;
1163             block_Release( p_audio );
1164         }
1165
1166         break;
1167     }
1168     vlc_mutex_unlock( &p_owner->lock );
1169 }
1170
1171 static void DecoderDecodeAudio( decoder_t *p_dec, block_t *p_block )
1172 {
1173     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1174     block_t *p_aout_buf;
1175     int i_decoded = 0;
1176     int i_lost = 0;
1177     int i_played = 0;
1178
1179     if (!p_block) {
1180         /* Play a NULL block to output buffered frames */
1181         DecoderPlayAudio( p_dec, NULL, &i_played, &i_lost );
1182     }
1183     else while( (p_aout_buf = p_dec->pf_decode_audio( p_dec, &p_block )) )
1184     {
1185         if( DecoderIsExitRequested( p_dec ) )
1186         {
1187             /* It prevent freezing VLC in case of broken decoder */
1188             block_Release( p_aout_buf );
1189             if( p_block )
1190                 block_Release( p_block );
1191             break;
1192         }
1193         i_decoded++;
1194
1195         if( p_owner->i_preroll_end > VLC_TS_INVALID &&
1196             p_aout_buf->i_pts < p_owner->i_preroll_end )
1197         {
1198             block_Release( p_aout_buf );
1199             continue;
1200         }
1201
1202         if( p_owner->i_preroll_end > VLC_TS_INVALID )
1203         {
1204             msg_Dbg( p_dec, "End of audio preroll" );
1205             if( p_owner->p_aout )
1206                 aout_DecFlush( p_owner->p_aout );
1207             /* */
1208             p_owner->i_preroll_end = VLC_TS_INVALID;
1209         }
1210
1211         DecoderPlayAudio( p_dec, p_aout_buf, &i_played, &i_lost );
1212     }
1213
1214     /* Update ugly stat */
1215     input_thread_t  *p_input = p_owner->p_input;
1216
1217     if( p_input != NULL && (i_decoded > 0 || i_lost > 0 || i_played > 0) )
1218     {
1219         vlc_mutex_lock( &p_input->p->counters.counters_lock);
1220         stats_Update( p_input->p->counters.p_lost_abuffers, i_lost, NULL );
1221         stats_Update( p_input->p->counters.p_played_abuffers, i_played, NULL );
1222         stats_Update( p_input->p->counters.p_decoded_audio, i_decoded, NULL );
1223         vlc_mutex_unlock( &p_input->p->counters.counters_lock);
1224     }
1225 }
1226 static void DecoderGetCc( decoder_t *p_dec, decoder_t *p_dec_cc )
1227 {
1228     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1229     block_t *p_cc;
1230     bool pb_present[4];
1231     bool b_processed = false;
1232     int i;
1233     int i_cc_decoder;
1234
1235     assert( p_dec_cc->pf_get_cc != NULL );
1236
1237     /* Do not try retreiving CC if not wanted (sout) or cannot be retreived */
1238     if( !p_owner->cc.b_supported )
1239         return;
1240
1241     p_cc = p_dec_cc->pf_get_cc( p_dec_cc, pb_present );
1242     if( !p_cc )
1243         return;
1244
1245     vlc_mutex_lock( &p_owner->lock );
1246     for( i = 0, i_cc_decoder = 0; i < 4; i++ )
1247     {
1248         p_owner->cc.pb_present[i] |= pb_present[i];
1249         if( p_owner->cc.pp_decoder[i] )
1250             i_cc_decoder++;
1251     }
1252
1253     for( i = 0; i < 4; i++ )
1254     {
1255         if( !p_owner->cc.pp_decoder[i] )
1256             continue;
1257
1258         block_FifoPut( p_owner->cc.pp_decoder[i]->p_owner->p_fifo,
1259             (i_cc_decoder > 1) ? block_Duplicate(p_cc) : p_cc);
1260
1261         i_cc_decoder--;
1262         b_processed = true;
1263     }
1264     vlc_mutex_unlock( &p_owner->lock );
1265
1266     if( !b_processed )
1267         block_Release( p_cc );
1268 }
1269
1270 static void DecoderPlayVideo( decoder_t *p_dec, picture_t *p_picture,
1271                               int *pi_played_sum, int *pi_lost_sum )
1272 {
1273     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1274     vout_thread_t  *p_vout = p_owner->p_vout;
1275
1276     if( p_picture->date <= VLC_TS_INVALID )
1277     {
1278         msg_Warn( p_dec, "non-dated video buffer received" );
1279         *pi_lost_sum += 1;
1280         picture_Release( p_picture );
1281         return;
1282     }
1283
1284     /* */
1285     vlc_mutex_lock( &p_owner->lock );
1286
1287     if( p_owner->b_waiting && !p_owner->b_first )
1288     {
1289         p_owner->b_has_data = true;
1290         vlc_cond_signal( &p_owner->wait_acknowledge );
1291     }
1292     bool b_first_after_wait = p_owner->b_waiting && p_owner->b_has_data;
1293
1294     bool b_reject = DecoderWaitUnblock( p_dec );
1295
1296     if( p_owner->b_waiting )
1297     {
1298         assert( p_owner->b_first );
1299         msg_Dbg( p_dec, "Received first picture" );
1300         p_owner->b_first = false;
1301         p_picture->b_force = true;
1302     }
1303
1304     const bool b_dated = p_picture->date > VLC_TS_INVALID;
1305     int i_rate = INPUT_RATE_DEFAULT;
1306     DecoderFixTs( p_dec, &p_picture->date, NULL, NULL,
1307                   &i_rate, DECODER_BOGUS_VIDEO_DELAY );
1308
1309     vlc_mutex_unlock( &p_owner->lock );
1310
1311     /* */
1312     if( !p_picture->b_force && p_picture->date <= VLC_TS_INVALID ) // FIXME --VLC_TS_INVALID verify video_output/*
1313         b_reject = true;
1314
1315     if( !b_reject )
1316     {
1317         if( i_rate != p_owner->i_last_rate || b_first_after_wait )
1318         {
1319             /* Be sure to not display old picture after our own */
1320             vout_Flush( p_vout, p_picture->date );
1321             p_owner->i_last_rate = i_rate;
1322         }
1323         vout_PutPicture( p_vout, p_picture );
1324     }
1325     else
1326     {
1327         if( b_dated )
1328             msg_Warn( p_dec, "early picture skipped" );
1329         else
1330             msg_Warn( p_dec, "non-dated video buffer received" );
1331
1332         *pi_lost_sum += 1;
1333         picture_Release( p_picture );
1334     }
1335     int i_tmp_display;
1336     int i_tmp_lost;
1337     vout_GetResetStatistic( p_vout, &i_tmp_display, &i_tmp_lost );
1338
1339     *pi_played_sum += i_tmp_display;
1340     *pi_lost_sum += i_tmp_lost;
1341 }
1342
1343 static void DecoderDecodeVideo( decoder_t *p_dec, block_t *p_block )
1344 {
1345     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1346     picture_t      *p_pic;
1347     int i_lost = 0;
1348     int i_decoded = 0;
1349     int i_displayed = 0;
1350
1351     while( (p_pic = p_dec->pf_decode_video( p_dec, &p_block )) )
1352     {
1353         vout_thread_t  *p_vout = p_owner->p_vout;
1354         if( DecoderIsExitRequested( p_dec ) )
1355         {
1356             /* It prevent freezing VLC in case of broken decoder */
1357             picture_Release( p_pic );
1358             if( p_block )
1359                 block_Release( p_block );
1360             break;
1361         }
1362
1363         i_decoded++;
1364
1365         if( p_owner->i_preroll_end > VLC_TS_INVALID && p_pic->date < p_owner->i_preroll_end )
1366         {
1367             picture_Release( p_pic );
1368             continue;
1369         }
1370
1371         if( p_owner->i_preroll_end > VLC_TS_INVALID )
1372         {
1373             msg_Dbg( p_dec, "End of video preroll" );
1374             if( p_vout )
1375                 vout_Flush( p_vout, VLC_TS_INVALID+1 );
1376             /* */
1377             p_owner->i_preroll_end = VLC_TS_INVALID;
1378         }
1379
1380         if( p_dec->pf_get_cc &&
1381             ( !p_owner->p_packetizer || !p_owner->p_packetizer->pf_get_cc ) )
1382             DecoderGetCc( p_dec, p_dec );
1383
1384         DecoderPlayVideo( p_dec, p_pic, &i_displayed, &i_lost );
1385     }
1386
1387     /* Update ugly stat */
1388     input_thread_t *p_input = p_owner->p_input;
1389
1390     if( p_input != NULL && (i_decoded > 0 || i_lost > 0 || i_displayed > 0) )
1391     {
1392         vlc_mutex_lock( &p_input->p->counters.counters_lock );
1393         stats_Update( p_input->p->counters.p_decoded_video, i_decoded, NULL );
1394         stats_Update( p_input->p->counters.p_lost_pictures, i_lost , NULL);
1395         stats_Update( p_input->p->counters.p_displayed_pictures,
1396                       i_displayed, NULL);
1397         vlc_mutex_unlock( &p_input->p->counters.counters_lock );
1398     }
1399 }
1400
1401 static void DecoderPlaySpu( decoder_t *p_dec, subpicture_t *p_subpic )
1402 {
1403     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1404     vout_thread_t *p_vout = p_owner->p_spu_vout;
1405
1406     /* */
1407     if( p_subpic->i_start <= VLC_TS_INVALID )
1408     {
1409         msg_Warn( p_dec, "non-dated spu buffer received" );
1410         subpicture_Delete( p_subpic );
1411         return;
1412     }
1413
1414     /* */
1415     vlc_mutex_lock( &p_owner->lock );
1416
1417     if( p_owner->b_waiting )
1418     {
1419         p_owner->b_has_data = true;
1420         vlc_cond_signal( &p_owner->wait_acknowledge );
1421     }
1422
1423     bool b_reject = DecoderWaitUnblock( p_dec );
1424
1425     DecoderFixTs( p_dec, &p_subpic->i_start, &p_subpic->i_stop, NULL,
1426                   NULL, INT64_MAX );
1427
1428     if( p_subpic->i_start <= VLC_TS_INVALID )
1429         b_reject = true;
1430
1431     DecoderWaitDate( p_dec, &b_reject,
1432                      p_subpic->i_start - SPU_MAX_PREPARE_TIME );
1433     vlc_mutex_unlock( &p_owner->lock );
1434
1435     if( !b_reject )
1436         vout_PutSubpicture( p_vout, p_subpic );
1437     else
1438         subpicture_Delete( p_subpic );
1439 }
1440
1441 #ifdef ENABLE_SOUT
1442 static int DecoderPlaySout( decoder_t *p_dec, block_t *p_sout_block )
1443 {
1444     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1445
1446     assert( p_owner->p_clock );
1447     assert( !p_sout_block->p_next );
1448
1449     vlc_mutex_lock( &p_owner->lock );
1450
1451     if( p_owner->b_waiting )
1452     {
1453         p_owner->b_has_data = true;
1454         vlc_cond_signal( &p_owner->wait_acknowledge );
1455     }
1456
1457     bool b_reject = DecoderWaitUnblock( p_dec );
1458
1459     DecoderFixTs( p_dec, &p_sout_block->i_dts, &p_sout_block->i_pts,
1460                   &p_sout_block->i_length, NULL, INT64_MAX );
1461
1462     vlc_mutex_unlock( &p_owner->lock );
1463
1464     if( !b_reject )
1465     {
1466         /* FIXME --VLC_TS_INVALID inspect stream_output*/
1467         return sout_InputSendBuffer( p_owner->p_sout_input, p_sout_block );
1468     }
1469     else
1470     {
1471         block_Release( p_sout_block );
1472         return VLC_EGENERIC;
1473     }
1474 }
1475 #endif
1476
1477 #ifdef ENABLE_SOUT
1478 /* This function process a block for sout
1479  */
1480 static void DecoderProcessSout( decoder_t *p_dec, block_t *p_block )
1481 {
1482     decoder_owner_sys_t *p_owner = (decoder_owner_sys_t *)p_dec->p_owner;
1483     block_t *p_sout_block;
1484
1485     while( ( p_sout_block =
1486                  p_dec->pf_packetize( p_dec, p_block ? &p_block : NULL ) ) )
1487     {
1488         if( p_owner->p_sout_input == NULL )
1489         {
1490             assert( !p_owner->b_fmt_description ); // no need for owner lock
1491             es_format_Clean( &p_owner->fmt );
1492             es_format_Copy( &p_owner->fmt, &p_dec->fmt_out );
1493
1494             p_owner->fmt.i_group = p_dec->fmt_in.i_group;
1495             p_owner->fmt.i_id = p_dec->fmt_in.i_id;
1496             if( p_dec->fmt_in.psz_language )
1497             {
1498                 free( p_owner->fmt.psz_language );
1499                 p_owner->fmt.psz_language =
1500                     strdup( p_dec->fmt_in.psz_language );
1501             }
1502
1503             p_owner->p_sout_input =
1504                 sout_InputNew( p_owner->p_sout, &p_owner->fmt );
1505
1506             if( p_owner->p_sout_input == NULL )
1507             {
1508                 msg_Err( p_dec, "cannot create packetizer output (%4.4s)",
1509                          (char *)&p_owner->fmt.i_codec );
1510                 p_dec->b_error = true;
1511
1512                 block_ChainRelease(p_sout_block);
1513                 break;
1514             }
1515         }
1516
1517         while( p_sout_block )
1518         {
1519             block_t *p_next = p_sout_block->p_next;
1520
1521             p_sout_block->p_next = NULL;
1522
1523             if( DecoderPlaySout( p_dec, p_sout_block ) == VLC_EGENERIC )
1524             {
1525                 msg_Err( p_dec, "cannot continue streaming due to errors" );
1526
1527                 p_dec->b_error = true;
1528
1529                 /* Cleanup */
1530                 block_ChainRelease( p_next );
1531                 return;
1532             }
1533
1534             p_sout_block = p_next;
1535         }
1536     }
1537 }
1538 #endif
1539
1540 /* This function process a video block
1541  */
1542 static void DecoderProcessVideo( decoder_t *p_dec, block_t *p_block, bool b_flush )
1543 {
1544     decoder_owner_sys_t *p_owner = (decoder_owner_sys_t *)p_dec->p_owner;
1545
1546     if( p_owner->p_packetizer )
1547     {
1548         block_t *p_packetized_block;
1549         decoder_t *p_packetizer = p_owner->p_packetizer;
1550
1551         while( (p_packetized_block =
1552                 p_packetizer->pf_packetize( p_packetizer, p_block ? &p_block : NULL )) )
1553         {
1554             if( p_packetizer->fmt_out.i_extra && !p_dec->fmt_in.i_extra )
1555             {
1556                 es_format_Clean( &p_dec->fmt_in );
1557                 es_format_Copy( &p_dec->fmt_in, &p_packetizer->fmt_out );
1558             }
1559
1560             /* If the packetizer provides aspect ratio information, pass it
1561              * to the decoder as a hint if the decoder itself can't provide
1562              * it. Copy it regardless of the current value of the decoder input
1563              * format aspect ratio, to properly propagate changes in aspect
1564              * ratio. */
1565             if( p_packetizer->fmt_out.video.i_sar_num > 0 &&
1566                     p_packetizer->fmt_out.video.i_sar_den > 0)
1567             {
1568                 p_dec->fmt_in.video.i_sar_num =
1569                     p_packetizer->fmt_out.video.i_sar_num;
1570                 p_dec->fmt_in.video.i_sar_den=
1571                     p_packetizer->fmt_out.video.i_sar_den;
1572             }
1573
1574             if( p_packetizer->pf_get_cc )
1575                 DecoderGetCc( p_dec, p_packetizer );
1576
1577             while( p_packetized_block )
1578             {
1579                 block_t *p_next = p_packetized_block->p_next;
1580                 p_packetized_block->p_next = NULL;
1581
1582                 DecoderDecodeVideo( p_dec, p_packetized_block );
1583
1584                 p_packetized_block = p_next;
1585             }
1586         }
1587         /* The packetizer does not output a block that tell the decoder to flush
1588          * do it ourself */
1589         if( b_flush )
1590         {
1591             block_t *p_null = DecoderBlockFlushNew();
1592             if( p_null )
1593                 DecoderDecodeVideo( p_dec, p_null );
1594         }
1595     }
1596     else
1597     {
1598         DecoderDecodeVideo( p_dec, p_block );
1599     }
1600
1601     if( b_flush && p_owner->p_vout )
1602         vout_Flush( p_owner->p_vout, VLC_TS_INVALID+1 );
1603 }
1604
1605 /* This function process a audio block
1606  */
1607 static void DecoderProcessAudio( decoder_t *p_dec, block_t *p_block, bool b_flush )
1608 {
1609     decoder_owner_sys_t *p_owner = (decoder_owner_sys_t *)p_dec->p_owner;
1610
1611     if( p_owner->p_packetizer )
1612     {
1613         block_t *p_packetized_block;
1614         decoder_t *p_packetizer = p_owner->p_packetizer;
1615
1616         while( (p_packetized_block =
1617                 p_packetizer->pf_packetize( p_packetizer, p_block ? &p_block : NULL )) )
1618         {
1619             if( p_packetizer->fmt_out.i_extra && !p_dec->fmt_in.i_extra )
1620             {
1621                 es_format_Clean( &p_dec->fmt_in );
1622                 es_format_Copy( &p_dec->fmt_in, &p_packetizer->fmt_out );
1623             }
1624
1625             while( p_packetized_block )
1626             {
1627                 block_t *p_next = p_packetized_block->p_next;
1628                 p_packetized_block->p_next = NULL;
1629
1630                 DecoderDecodeAudio( p_dec, p_packetized_block );
1631
1632                 p_packetized_block = p_next;
1633             }
1634         }
1635         /* The packetizer does not output a block that tell the decoder to flush
1636          * do it ourself */
1637         if( b_flush )
1638         {
1639             block_t *p_null = DecoderBlockFlushNew();
1640             if( p_null )
1641                 DecoderDecodeAudio( p_dec, p_null );
1642         }
1643     }
1644     else
1645     {
1646         DecoderDecodeAudio( p_dec, p_block );
1647     }
1648
1649     if( b_flush && p_owner->p_aout )
1650         aout_DecFlush( p_owner->p_aout );
1651 }
1652
1653 /* This function process a subtitle block
1654  */
1655 static void DecoderProcessSpu( decoder_t *p_dec, block_t *p_block, bool b_flush )
1656 {
1657     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1658
1659     input_thread_t *p_input = p_owner->p_input;
1660     vout_thread_t *p_vout;
1661     subpicture_t *p_spu;
1662
1663     while( (p_spu = p_dec->pf_decode_sub( p_dec, p_block ? &p_block : NULL ) ) )
1664     {
1665         if( p_input != NULL )
1666         {
1667             vlc_mutex_lock( &p_input->p->counters.counters_lock );
1668             stats_Update( p_input->p->counters.p_decoded_sub, 1, NULL );
1669             vlc_mutex_unlock( &p_input->p->counters.counters_lock );
1670         }
1671
1672         p_vout = input_resource_HoldVout( p_owner->p_resource );
1673         if( p_vout && p_owner->p_spu_vout == p_vout )
1674         {
1675             /* Preroll does not work very well with subtitle */
1676             if( p_spu->i_start > VLC_TS_INVALID &&
1677                 p_spu->i_start < p_owner->i_preroll_end &&
1678                 ( p_spu->i_stop <= VLC_TS_INVALID || p_spu->i_stop < p_owner->i_preroll_end ) )
1679             {
1680                 subpicture_Delete( p_spu );
1681             }
1682             else
1683             {
1684                 DecoderPlaySpu( p_dec, p_spu );
1685             }
1686         }
1687         else
1688         {
1689             subpicture_Delete( p_spu );
1690         }
1691         if( p_vout )
1692             vlc_object_release( p_vout );
1693     }
1694
1695     if( b_flush && p_owner->p_spu_vout )
1696     {
1697         p_vout = input_resource_HoldVout( p_owner->p_resource );
1698
1699         if( p_vout && p_owner->p_spu_vout == p_vout )
1700             vout_FlushSubpictureChannel( p_vout, p_owner->i_spu_channel );
1701
1702         if( p_vout )
1703             vlc_object_release( p_vout );
1704     }
1705 }
1706
1707 /* */
1708 static void DecoderProcessOnFlush( decoder_t *p_dec )
1709 {
1710     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1711
1712     vlc_mutex_lock( &p_owner->lock );
1713
1714     if( p_owner->b_flushing )
1715     {
1716         p_owner->b_flushing = false;
1717         vlc_cond_signal( &p_owner->wait_acknowledge );
1718     }
1719     vlc_mutex_unlock( &p_owner->lock );
1720 }
1721
1722 /**
1723  * Decode a block
1724  *
1725  * \param p_dec the decoder object
1726  * \param p_block the block to decode
1727  * \return VLC_SUCCESS or an error code
1728  */
1729 static void DecoderProcess( decoder_t *p_dec, block_t *p_block )
1730 {
1731     decoder_owner_sys_t *p_owner = (decoder_owner_sys_t *)p_dec->p_owner;
1732     const bool b_flush_request = p_block && (p_block->i_flags & BLOCK_FLAG_CORE_FLUSH);
1733
1734     if( p_dec->b_error )
1735     {
1736         if( p_block )
1737             block_Release( p_block );
1738         goto flush;
1739     }
1740
1741     if( p_block && p_block->i_buffer <= 0 )
1742     {
1743         assert( !b_flush_request );
1744         block_Release( p_block );
1745         return;
1746     }
1747
1748 #ifdef ENABLE_SOUT
1749     if( p_owner->b_packetizer )
1750     {
1751         if( p_block )
1752             p_block->i_flags &= ~BLOCK_FLAG_CORE_PRIVATE_MASK;
1753
1754         DecoderProcessSout( p_dec, p_block );
1755     }
1756     else
1757 #endif
1758     {
1759         bool b_flush = false;
1760
1761         if( p_block )
1762         {
1763             const bool b_flushing = p_owner->i_preroll_end == INT64_MAX;
1764             DecoderUpdatePreroll( &p_owner->i_preroll_end, p_block );
1765
1766             b_flush = !b_flushing && b_flush_request;
1767
1768             p_block->i_flags &= ~BLOCK_FLAG_CORE_PRIVATE_MASK;
1769         }
1770
1771         if( p_dec->fmt_out.i_cat == AUDIO_ES )
1772         {
1773             DecoderProcessAudio( p_dec, p_block, b_flush );
1774         }
1775         else if( p_dec->fmt_out.i_cat == VIDEO_ES )
1776         {
1777             DecoderProcessVideo( p_dec, p_block, b_flush );
1778         }
1779         else if( p_dec->fmt_out.i_cat == SPU_ES )
1780         {
1781             DecoderProcessSpu( p_dec, p_block, b_flush );
1782         }
1783         else
1784         {
1785             msg_Err( p_dec, "unknown ES format" );
1786             p_dec->b_error = true;
1787         }
1788     }
1789
1790     /* */
1791 flush:
1792     if( b_flush_request )
1793         DecoderProcessOnFlush( p_dec );
1794 }
1795
1796 /**
1797  * Destroys a decoder object
1798  *
1799  * \param p_dec the decoder object
1800  * \return nothing
1801  */
1802 static void DeleteDecoder( decoder_t * p_dec )
1803 {
1804     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1805
1806     msg_Dbg( p_dec, "killing decoder fourcc `%4.4s', %u PES in FIFO",
1807              (char*)&p_dec->fmt_in.i_codec,
1808              (unsigned)block_FifoCount( p_owner->p_fifo ) );
1809
1810     /* Free all packets still in the decoder fifo. */
1811     block_FifoRelease( p_owner->p_fifo );
1812
1813     /* Cleanup */
1814     if( p_owner->p_aout )
1815     {
1816         /* TODO: REVISIT gap-less audio */
1817         aout_DecFlush( p_owner->p_aout );
1818         aout_DecDelete( p_owner->p_aout );
1819         input_resource_PutAout( p_owner->p_resource, p_owner->p_aout );
1820         if( p_owner->p_input != NULL )
1821             input_SendEventAout( p_owner->p_input );
1822     }
1823     if( p_owner->p_vout )
1824     {
1825         /* Hack to make sure all the the pictures are freed by the decoder
1826          * and that the vout is not paused anymore */
1827         vout_Reset( p_owner->p_vout );
1828
1829         /* */
1830         input_resource_RequestVout( p_owner->p_resource, p_owner->p_vout, NULL,
1831                                     0, true );
1832         if( p_owner->p_input != NULL )
1833             input_SendEventVout( p_owner->p_input );
1834     }
1835
1836 #ifdef ENABLE_SOUT
1837     if( p_owner->p_sout_input )
1838     {
1839         sout_InputDelete( p_owner->p_sout_input );
1840     }
1841 #endif
1842     es_format_Clean( &p_owner->fmt );
1843
1844     if( p_dec->fmt_out.i_cat == SPU_ES )
1845     {
1846         vout_thread_t *p_vout = input_resource_HoldVout( p_owner->p_resource );
1847         if( p_vout )
1848         {
1849             if( p_owner->p_spu_vout == p_vout )
1850                 vout_FlushSubpictureChannel( p_vout, p_owner->i_spu_channel );
1851             vlc_object_release( p_vout );
1852         }
1853     }
1854
1855     es_format_Clean( &p_dec->fmt_in );
1856     es_format_Clean( &p_dec->fmt_out );
1857     if( p_dec->p_description )
1858         vlc_meta_Delete( p_dec->p_description );
1859     if( p_owner->p_description )
1860         vlc_meta_Delete( p_owner->p_description );
1861
1862     if( p_owner->p_packetizer )
1863     {
1864         module_unneed( p_owner->p_packetizer,
1865                        p_owner->p_packetizer->p_module );
1866         es_format_Clean( &p_owner->p_packetizer->fmt_in );
1867         es_format_Clean( &p_owner->p_packetizer->fmt_out );
1868         if( p_owner->p_packetizer->p_description )
1869             vlc_meta_Delete( p_owner->p_packetizer->p_description );
1870         vlc_object_release( p_owner->p_packetizer );
1871     }
1872
1873     vlc_cond_destroy( &p_owner->wait_acknowledge );
1874     vlc_cond_destroy( &p_owner->wait_request );
1875     vlc_mutex_destroy( &p_owner->lock );
1876
1877     vlc_object_release( p_dec );
1878
1879     free( p_owner );
1880 }
1881
1882 /*****************************************************************************
1883  * Buffers allocation callbacks for the decoders
1884  *****************************************************************************/
1885 static void DecoderUpdateFormatLocked( decoder_t *p_dec )
1886 {
1887     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1888
1889     vlc_assert_locked( &p_owner->lock );
1890
1891     p_owner->b_fmt_description = true;
1892
1893     /* Move p_description */
1894     if( p_owner->p_description && p_dec->p_description )
1895         vlc_meta_Delete( p_owner->p_description );
1896     p_owner->p_description = p_dec->p_description;
1897     p_dec->p_description = NULL;
1898 }
1899 static vout_thread_t *aout_request_vout( void *p_private,
1900                                          vout_thread_t *p_vout, video_format_t *p_fmt, bool b_recyle )
1901 {
1902     decoder_t *p_dec = p_private;
1903     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1904     input_thread_t *p_input = p_owner->p_input;
1905
1906     p_vout = input_resource_RequestVout( p_owner->p_resource, p_vout, p_fmt, 1,
1907                                          b_recyle );
1908     if( p_input != NULL )
1909         input_SendEventVout( p_input );
1910
1911     return p_vout;
1912 }
1913
1914 static int aout_update_format( decoder_t *p_dec )
1915 {
1916     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1917
1918     if( p_owner->p_aout
1919      && !AOUT_FMTS_IDENTICAL(&p_dec->fmt_out.audio, &p_owner->fmt.audio) )
1920     {
1921         audio_output_t *p_aout = p_owner->p_aout;
1922
1923         /* Parameters changed, restart the aout */
1924         vlc_mutex_lock( &p_owner->lock );
1925
1926         aout_DecDelete( p_owner->p_aout );
1927         p_owner->p_aout = NULL;
1928
1929         vlc_mutex_unlock( &p_owner->lock );
1930         input_resource_PutAout( p_owner->p_resource, p_aout );
1931     }
1932
1933     if( p_owner->p_aout == NULL )
1934     {
1935         p_dec->fmt_out.audio.i_format = p_dec->fmt_out.i_codec;
1936
1937         audio_sample_format_t format = p_dec->fmt_out.audio;
1938         aout_FormatPrepare( &format );
1939
1940         const int i_force_dolby = var_InheritInteger( p_dec, "force-dolby-surround" );
1941         if( i_force_dolby &&
1942             (format.i_original_channels&AOUT_CHAN_PHYSMASK) ==
1943                 (AOUT_CHAN_LEFT|AOUT_CHAN_RIGHT) )
1944         {
1945             if( i_force_dolby == 1 )
1946             {
1947                 format.i_original_channels = format.i_original_channels |
1948                                              AOUT_CHAN_DOLBYSTEREO;
1949             }
1950             else /* i_force_dolby == 2 */
1951             {
1952                 format.i_original_channels = format.i_original_channels &
1953                                              ~AOUT_CHAN_DOLBYSTEREO;
1954             }
1955         }
1956
1957         aout_request_vout_t request_vout = {
1958             .pf_request_vout = aout_request_vout,
1959             .p_private = p_dec,
1960         };
1961         audio_output_t *p_aout;
1962
1963         p_aout = input_resource_GetAout( p_owner->p_resource );
1964         if( p_aout )
1965         {
1966             if( aout_DecNew( p_aout, &format,
1967                              &p_dec->fmt_out.audio_replay_gain,
1968                              &request_vout ) )
1969             {
1970                 input_resource_PutAout( p_owner->p_resource, p_aout );
1971                 p_aout = NULL;
1972             }
1973         }
1974
1975         vlc_mutex_lock( &p_owner->lock );
1976
1977         p_owner->p_aout = p_aout;
1978
1979         es_format_Clean( &p_owner->fmt );
1980         es_format_Copy( &p_owner->fmt, &p_dec->fmt_out );
1981         aout_FormatPrepare( &p_owner->fmt.audio );
1982
1983         DecoderUpdateFormatLocked( p_dec );
1984
1985         if( unlikely(p_owner->b_paused) && p_aout != NULL )
1986             /* fake pause if needed */
1987             aout_DecChangePause( p_aout, true, mdate() );
1988
1989         vlc_mutex_unlock( &p_owner->lock );
1990
1991         if( p_owner->p_input != NULL )
1992             input_SendEventAout( p_owner->p_input );
1993
1994         if( p_aout == NULL )
1995         {
1996             msg_Err( p_dec, "failed to create audio output" );
1997             p_dec->b_error = true;
1998             return -1;
1999         }
2000
2001         p_dec->fmt_out.audio.i_bytes_per_frame =
2002             p_owner->fmt.audio.i_bytes_per_frame;
2003         p_dec->fmt_out.audio.i_frame_length =
2004             p_owner->fmt.audio.i_frame_length;
2005     }
2006     return 0;
2007 }
2008
2009 static int vout_update_format( decoder_t *p_dec )
2010 {
2011     decoder_owner_sys_t *p_owner = p_dec->p_owner;
2012
2013     if( p_owner->p_vout == NULL
2014      || p_dec->fmt_out.video.i_width != p_owner->fmt.video.i_width
2015      || p_dec->fmt_out.video.i_height != p_owner->fmt.video.i_height
2016      || p_dec->fmt_out.video.i_visible_width != p_owner->fmt.video.i_visible_width
2017      || p_dec->fmt_out.video.i_visible_height != p_owner->fmt.video.i_visible_height
2018      || p_dec->fmt_out.video.i_x_offset != p_owner->fmt.video.i_x_offset
2019      || p_dec->fmt_out.video.i_y_offset != p_owner->fmt.video.i_y_offset
2020      || p_dec->fmt_out.i_codec != p_owner->fmt.video.i_chroma
2021      || (int64_t)p_dec->fmt_out.video.i_sar_num * p_owner->fmt.video.i_sar_den !=
2022         (int64_t)p_dec->fmt_out.video.i_sar_den * p_owner->fmt.video.i_sar_num ||
2023         p_dec->fmt_out.video.orientation != p_owner->fmt.video.orientation )
2024     {
2025         vout_thread_t *p_vout;
2026
2027         if( !p_dec->fmt_out.video.i_width ||
2028             !p_dec->fmt_out.video.i_height )
2029         {
2030             /* Can't create a new vout without display size */
2031             return -1;
2032         }
2033
2034         video_format_t fmt = p_dec->fmt_out.video;
2035         fmt.i_chroma = p_dec->fmt_out.i_codec;
2036
2037         if( vlc_fourcc_IsYUV( fmt.i_chroma ) )
2038         {
2039             const vlc_chroma_description_t *dsc = vlc_fourcc_GetChromaDescription( fmt.i_chroma );
2040             for( unsigned int i = 0; dsc && i < dsc->plane_count; i++ )
2041             {
2042                 while( fmt.i_width % dsc->p[i].w.den )
2043                     fmt.i_width++;
2044                 while( fmt.i_height % dsc->p[i].h.den )
2045                     fmt.i_height++;
2046             }
2047         }
2048
2049         if( !fmt.i_visible_width || !fmt.i_visible_height )
2050         {
2051             if( p_dec->fmt_in.video.i_visible_width &&
2052                 p_dec->fmt_in.video.i_visible_height )
2053             {
2054                 fmt.i_visible_width  = p_dec->fmt_in.video.i_visible_width;
2055                 fmt.i_visible_height = p_dec->fmt_in.video.i_visible_height;
2056                 fmt.i_x_offset       = p_dec->fmt_in.video.i_x_offset;
2057                 fmt.i_y_offset       = p_dec->fmt_in.video.i_y_offset;
2058             }
2059             else
2060             {
2061                 fmt.i_visible_width  = fmt.i_width;
2062                 fmt.i_visible_height = fmt.i_height;
2063                 fmt.i_x_offset       = 0;
2064                 fmt.i_y_offset       = 0;
2065             }
2066         }
2067
2068         if( fmt.i_visible_height == 1088 &&
2069             var_CreateGetBool( p_dec, "hdtv-fix" ) )
2070         {
2071             fmt.i_visible_height = 1080;
2072             if( !(fmt.i_sar_num % 136))
2073             {
2074                 fmt.i_sar_num *= 135;
2075                 fmt.i_sar_den *= 136;
2076             }
2077             msg_Warn( p_dec, "Fixing broken HDTV stream (display_height=1088)");
2078         }
2079
2080         if( !fmt.i_sar_num || !fmt.i_sar_den )
2081         {
2082             fmt.i_sar_num = 1;
2083             fmt.i_sar_den = 1;
2084         }
2085
2086         vlc_ureduce( &fmt.i_sar_num, &fmt.i_sar_den,
2087                      fmt.i_sar_num, fmt.i_sar_den, 50000 );
2088
2089         vlc_mutex_lock( &p_owner->lock );
2090
2091         p_vout = p_owner->p_vout;
2092         p_owner->p_vout = NULL;
2093         vlc_mutex_unlock( &p_owner->lock );
2094
2095         unsigned dpb_size;
2096         switch( p_dec->fmt_in.i_codec )
2097         {
2098         case VLC_CODEC_HEVC:
2099         case VLC_CODEC_H264:
2100         case VLC_CODEC_DIRAC: /* FIXME valid ? */
2101             dpb_size = 18;
2102             break;
2103         case VLC_CODEC_VP5:
2104         case VLC_CODEC_VP6:
2105         case VLC_CODEC_VP6F:
2106         case VLC_CODEC_VP8:
2107             dpb_size = 3;
2108             break;
2109         default:
2110             dpb_size = 2;
2111             break;
2112         }
2113         p_vout = input_resource_RequestVout( p_owner->p_resource,
2114                                              p_vout, &fmt,
2115                                              dpb_size +
2116                                              p_dec->i_extra_picture_buffers + 1,
2117                                              true );
2118         vlc_mutex_lock( &p_owner->lock );
2119         p_owner->p_vout = p_vout;
2120
2121         es_format_Clean( &p_owner->fmt );
2122         es_format_Copy( &p_owner->fmt, &p_dec->fmt_out );
2123         p_owner->fmt.video.i_chroma = p_dec->fmt_out.i_codec;
2124
2125         DecoderUpdateFormatLocked( p_dec );
2126
2127         vlc_mutex_unlock( &p_owner->lock );
2128
2129         if( p_owner->p_input != NULL )
2130             input_SendEventVout( p_owner->p_input );
2131         if( p_vout == NULL )
2132         {
2133             msg_Err( p_dec, "failed to create video output" );
2134             p_dec->b_error = true;
2135             return -1;
2136         }
2137     }
2138     return 0;
2139 }
2140
2141 static picture_t *vout_new_buffer( decoder_t *p_dec )
2142 {
2143     decoder_owner_sys_t *p_owner = p_dec->p_owner;
2144
2145     for( ;; )
2146     {
2147         if( DecoderIsExitRequested( p_dec ) || p_dec->b_error )
2148             return NULL;
2149
2150         picture_t *p_picture = vout_GetPicture( p_owner->p_vout );
2151         if( p_picture )
2152             return p_picture;
2153
2154         if( DecoderIsFlushing( p_dec ) )
2155             return NULL;
2156
2157         /* */
2158         DecoderSignalWait( p_dec, true );
2159
2160         /* Check the decoder doesn't leak pictures */
2161         vout_FixLeaks( p_owner->p_vout );
2162
2163         /* FIXME add a vout_WaitPictureAvailable (timedwait) */
2164         msleep( VOUT_OUTMEM_SLEEP );
2165     }
2166 }
2167
2168 static subpicture_t *spu_new_buffer( decoder_t *p_dec,
2169                                      const subpicture_updater_t *p_updater )
2170 {
2171     decoder_owner_sys_t *p_owner = p_dec->p_owner;
2172     vout_thread_t *p_vout = NULL;
2173     subpicture_t *p_subpic;
2174     int i_attempts = 30;
2175
2176     while( i_attempts-- )
2177     {
2178         if( DecoderIsExitRequested( p_dec ) || p_dec->b_error )
2179             break;
2180
2181         p_vout = input_resource_HoldVout( p_owner->p_resource );
2182         if( p_vout )
2183             break;
2184
2185         msleep( DECODER_SPU_VOUT_WAIT_DURATION );
2186     }
2187
2188     if( !p_vout )
2189     {
2190         msg_Warn( p_dec, "no vout found, dropping subpicture" );
2191         return NULL;
2192     }
2193
2194     if( p_owner->p_spu_vout != p_vout )
2195     {
2196         p_owner->i_spu_channel = vout_RegisterSubpictureChannel( p_vout );
2197         p_owner->i_spu_order = 0;
2198         p_owner->p_spu_vout = p_vout;
2199     }
2200
2201     p_subpic = subpicture_New( p_updater );
2202     if( p_subpic )
2203     {
2204         p_subpic->i_channel = p_owner->i_spu_channel;
2205         p_subpic->i_order = p_owner->i_spu_order++;
2206         p_subpic->b_subtitle = true;
2207     }
2208
2209     vlc_object_release( p_vout );
2210
2211     return p_subpic;
2212 }