Correctly set order per subtitle decoder.
[vlc.git] / src / input / decoder.c
1 /*****************************************************************************
2  * decoder.c: Functions for the management of decoders
3  *****************************************************************************
4  * Copyright (C) 1999-2004 the VideoLAN team
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
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 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 General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, 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_osd.h>
42
43 #include <vlc_interface.h>
44 #include "audio_output/aout_internal.h"
45 #include "stream_output/stream_output.h"
46 #include "input_internal.h"
47
48 static decoder_t * CreateDecoder( input_thread_t *, es_format_t *, int, sout_instance_t *p_sout );
49 static void        DeleteDecoder( decoder_t * );
50
51 static void*        DecoderThread( vlc_object_t * );
52 static int         DecoderDecode( decoder_t * p_dec, block_t *p_block );
53
54 /* Buffers allocation callbacks for the decoders */
55 static aout_buffer_t *aout_new_buffer( decoder_t *, int );
56 static void aout_del_buffer( decoder_t *, aout_buffer_t * );
57
58 static picture_t *vout_new_buffer( decoder_t * );
59 static void vout_del_buffer( decoder_t *, picture_t * );
60 static void vout_link_picture( decoder_t *, picture_t * );
61 static void vout_unlink_picture( decoder_t *, picture_t * );
62
63 static subpicture_t *spu_new_buffer( decoder_t * );
64 static void spu_del_buffer( decoder_t *, subpicture_t * );
65
66 static es_format_t null_es_format;
67
68 struct decoder_owner_sys_t
69 {
70     bool      b_own_thread;
71
72     int64_t         i_preroll_end;
73
74     input_thread_t  *p_input;
75
76     aout_instance_t *p_aout;
77     aout_input_t    *p_aout_input;
78
79     vout_thread_t   *p_vout;
80
81     vout_thread_t   *p_spu_vout;
82     int              i_spu_channel;
83     int64_t          i_spu_order;
84
85     sout_instance_t         *p_sout;
86     sout_packetizer_input_t *p_sout_input;
87
88     /* Some decoders require already packetized data (ie. not truncated) */
89     decoder_t *p_packetizer;
90
91     /* Current format in use by the output */
92     video_format_t video;
93     audio_format_t audio;
94     es_format_t    sout;
95
96     /* fifo */
97     block_fifo_t *p_fifo;
98
99     /* CC */
100     bool b_cc_supported;
101     vlc_mutex_t lock_cc;
102     bool pb_cc_present[4];
103     decoder_t *pp_cc[4];
104 };
105
106 /* */
107 static void DecoderUnsupportedCodec( decoder_t *p_dec, vlc_fourcc_t codec )
108 {
109     msg_Err( p_dec, "no suitable decoder module for fourcc `%4.4s'.\n"
110              "VLC probably does not support this sound or video format.",
111              (char*)&codec );
112     intf_UserFatal( p_dec, false, _("No suitable decoder module"), 
113                     _("VLC does not support the audio or video format \"%4.4s\". "
114                       "Unfortunately there is no way for you to fix this."), (char*)&codec );
115 }
116
117 /* decoder_GetInputAttachment:
118  */
119 input_attachment_t *decoder_GetInputAttachment( decoder_t *p_dec,
120                                                 const char *psz_name )
121 {
122     input_attachment_t *p_attachment;
123     if( input_Control( p_dec->p_owner->p_input, INPUT_GET_ATTACHMENT, &p_attachment, psz_name ) )
124         return NULL;
125     return p_attachment;
126 }
127 /* decoder_GetInputAttachments:
128  */
129 int decoder_GetInputAttachments( decoder_t *p_dec,
130                                  input_attachment_t ***ppp_attachment,
131                                  int *pi_attachment )
132 {
133     return input_Control( p_dec->p_owner->p_input, INPUT_GET_ATTACHMENTS,
134                           ppp_attachment, pi_attachment );
135 }
136 /* decoder_GetDisplayDate:
137  */
138 mtime_t decoder_GetDisplayDate( decoder_t *p_dec, mtime_t i_ts )
139 {
140     VLC_UNUSED(p_dec);
141     return i_ts;
142 }
143
144 /**
145  * Spawns a new decoder thread
146  *
147  * \param p_input the input thread
148  * \param p_es the es descriptor
149  * \return the spawned decoder object
150  */
151 decoder_t *input_DecoderNew( input_thread_t *p_input,
152                              es_format_t *fmt, sout_instance_t *p_sout  )
153 {
154     decoder_t   *p_dec = NULL;
155     vlc_value_t val;
156
157 #ifndef ENABLE_SOUT
158     (void)b_force_decoder;
159 #else
160     /* If we are in sout mode, search for packetizer module */
161     if( p_sout )
162     {
163         /* Create the decoder configuration structure */
164         p_dec = CreateDecoder( p_input, fmt, VLC_OBJECT_PACKETIZER, p_sout );
165         if( p_dec == NULL )
166         {
167             msg_Err( p_input, "could not create packetizer" );
168             intf_UserFatal( p_input, false, _("Streaming / Transcoding failed"),
169                             _("VLC could not open the packetizer module.") );
170             return NULL;
171         }
172     }
173     else
174 #endif
175     {
176         /* Create the decoder configuration structure */
177         p_dec = CreateDecoder( p_input, fmt, VLC_OBJECT_DECODER, p_sout );
178         if( p_dec == NULL )
179         {
180             msg_Err( p_input, "could not create decoder" );
181             intf_UserFatal( p_input, false, _("Streaming / Transcoding failed"),
182                             _("VLC could not open the decoder module.") );
183             return NULL;
184         }
185     }
186
187     if( !p_dec->p_module )
188     {
189         DecoderUnsupportedCodec( p_dec, fmt->i_codec );
190
191         DeleteDecoder( p_dec );
192         vlc_object_release( p_dec );
193         return NULL;
194     }
195
196     if( p_sout && p_sout == p_input->p->p_sout && p_input->p->input.b_can_pace_control )
197     {
198         msg_Dbg( p_input, "stream out mode -> no decoder thread" );
199         p_dec->p_owner->b_own_thread = false;
200     }
201     else
202     {
203         var_Get( p_input, "minimize-threads", &val );
204         p_dec->p_owner->b_own_thread = !val.b_bool;
205     }
206
207     if( p_dec->p_owner->b_own_thread )
208     {
209         int i_priority;
210         if( fmt->i_cat == AUDIO_ES )
211             i_priority = VLC_THREAD_PRIORITY_AUDIO;
212         else
213             i_priority = VLC_THREAD_PRIORITY_VIDEO;
214
215         /* Spawn the decoder thread */
216         if( vlc_thread_create( p_dec, "decoder", DecoderThread,
217                                i_priority, false ) )
218         {
219             msg_Err( p_dec, "cannot spawn decoder thread" );
220             module_unneed( p_dec, p_dec->p_module );
221             DeleteDecoder( p_dec );
222             vlc_object_release( p_dec );
223             return NULL;
224         }
225     }
226
227     return p_dec;
228 }
229
230 /**
231  * Kills a decoder thread and waits until it's finished
232  *
233  * \param p_input the input thread
234  * \param p_es the es descriptor
235  * \return nothing
236  */
237 void input_DecoderDelete( decoder_t *p_dec )
238 {
239     vlc_object_kill( p_dec );
240
241     if( p_dec->p_owner->b_own_thread )
242     {
243         /* Make sure the thread leaves the function by
244          * sending it an empty block. */
245         block_t *p_block = block_New( p_dec, 0 );
246         input_DecoderDecode( p_dec, p_block );
247
248         vlc_thread_join( p_dec );
249
250         /* Don't module_unneed() here because of the dll loader that wants
251          * close() in the same thread than open()/decode() */
252     }
253     else
254     {
255         /* Flush */
256         input_DecoderDecode( p_dec, NULL );
257
258         module_unneed( p_dec, p_dec->p_module );
259     }
260
261     /* */
262     if( p_dec->p_owner->b_cc_supported )
263     {
264         int i;
265         for( i = 0; i < 4; i++ )
266             input_DecoderSetCcState( p_dec, false, i );
267     }
268
269     /* Delete decoder configuration */
270     DeleteDecoder( p_dec );
271
272     /* Delete the decoder */
273     vlc_object_release( p_dec );
274 }
275
276 /**
277  * Put a block_t in the decoder's fifo.
278  *
279  * \param p_dec the decoder object
280  * \param p_block the data block
281  */
282 void input_DecoderDecode( decoder_t * p_dec, block_t *p_block )
283 {
284     if( p_dec->p_owner->b_own_thread )
285     {
286         if( p_dec->p_owner->p_input->p->b_out_pace_control )
287         {
288             /* FIXME !!!!! */
289             while( !p_dec->b_die && !p_dec->b_error &&
290                    block_FifoCount( p_dec->p_owner->p_fifo ) > 10 )
291             {
292                 msleep( 1000 );
293             }
294         }
295         else if( block_FifoSize( p_dec->p_owner->p_fifo ) > 50000000 /* 50 MB */ )
296         {
297             /* FIXME: ideally we would check the time amount of data
298              * in the fifo instead of its size. */
299             msg_Warn( p_dec, "decoder/packetizer fifo full (data not "
300                       "consumed quickly enough), resetting fifo!" );
301             block_FifoEmpty( p_dec->p_owner->p_fifo );
302         }
303
304         block_FifoPut( p_dec->p_owner->p_fifo, p_block );
305     }
306     else
307     {
308         if( p_dec->b_error || (p_block && p_block->i_buffer <= 0) )
309         {
310             if( p_block ) block_Release( p_block );
311         }
312         else
313         {
314             DecoderDecode( p_dec, p_block );
315         }
316     }
317 }
318
319 void input_DecoderDiscontinuity( decoder_t * p_dec, bool b_flush )
320 {
321     block_t *p_null;
322
323     /* Empty the fifo */
324     if( p_dec->p_owner->b_own_thread && b_flush )
325         block_FifoEmpty( p_dec->p_owner->p_fifo );
326
327     /* Send a special block */
328     p_null = block_New( p_dec, 128 );
329     p_null->i_flags |= BLOCK_FLAG_DISCONTINUITY;
330     if( b_flush && p_dec->fmt_in.i_cat == SPU_ES )
331         p_null->i_flags |= BLOCK_FLAG_CORE_FLUSH;
332     /* FIXME check for p_packetizer or b_packitized from es_format_t of input ? */
333     if( p_dec->p_owner->p_packetizer && b_flush )
334         p_null->i_flags |= BLOCK_FLAG_CORRUPTED;
335     memset( p_null->p_buffer, 0, p_null->i_buffer );
336
337     input_DecoderDecode( p_dec, p_null );
338 }
339
340 bool input_DecoderEmpty( decoder_t * p_dec )
341 {
342     if( p_dec->p_owner->b_own_thread
343      && block_FifoCount( p_dec->p_owner->p_fifo ) > 0 )
344     {
345         return false;
346     }
347     return true;
348 }
349
350 void input_DecoderIsCcPresent( decoder_t *p_dec, bool pb_present[4] )
351 {
352     int i;
353
354     vlc_mutex_lock( &p_dec->p_owner->lock_cc );
355     for( i = 0; i < 4; i++ )
356         pb_present[i] =  p_dec->p_owner->pb_cc_present[i];
357     vlc_mutex_unlock( &p_dec->p_owner->lock_cc );
358 }
359 int input_DecoderSetCcState( decoder_t *p_dec, bool b_decode, int i_channel )
360 {
361     decoder_owner_sys_t *p_owner = p_dec->p_owner;
362
363     //msg_Warn( p_dec, "input_DecoderSetCcState: %d @%d", b_decode, i_channel );
364
365     if( i_channel < 0 || i_channel >= 4 || !p_owner->pb_cc_present[i_channel] )
366         return VLC_EGENERIC;
367
368     if( b_decode )
369     {
370         static const vlc_fourcc_t fcc[4] = {
371             VLC_FOURCC('c', 'c', '1', ' '),
372             VLC_FOURCC('c', 'c', '2', ' '),
373             VLC_FOURCC('c', 'c', '3', ' '),
374             VLC_FOURCC('c', 'c', '4', ' '),
375         };
376         decoder_t *p_cc;
377         es_format_t fmt;
378
379         es_format_Init( &fmt, SPU_ES, fcc[i_channel] );
380         p_cc = CreateDecoder( p_owner->p_input, &fmt, VLC_OBJECT_DECODER, p_dec->p_owner->p_sout );
381         if( !p_cc )
382         {
383             msg_Err( p_dec, "could not create decoder" );
384             intf_UserFatal( p_dec, false, _("Streaming / Transcoding failed"),
385                             _("VLC could not open the decoder module.") );
386             return VLC_EGENERIC;
387         }
388         else if( !p_cc->p_module )
389         {
390             DecoderUnsupportedCodec( p_dec, fcc[i_channel] );
391             DeleteDecoder( p_cc );
392             vlc_object_release( p_cc );
393             return VLC_EGENERIC;
394         }
395
396         vlc_mutex_lock( &p_owner->lock_cc );
397         p_dec->p_owner->pp_cc[i_channel] = p_cc;
398         vlc_mutex_unlock( &p_owner->lock_cc );
399     }
400     else
401     {
402         decoder_t *p_cc;
403
404         vlc_mutex_lock( &p_owner->lock_cc );
405         p_cc = p_dec->p_owner->pp_cc[i_channel];
406         p_dec->p_owner->pp_cc[i_channel] = NULL;
407         vlc_mutex_unlock( &p_dec->p_owner->lock_cc );
408
409         if( p_cc )
410         {
411             vlc_object_kill( p_cc );
412             module_unneed( p_cc, p_cc->p_module );
413             DeleteDecoder( p_cc );
414             vlc_object_release( p_cc );
415         }
416     }
417     return VLC_SUCCESS;
418 }
419 int input_DecoderGetCcState( decoder_t *p_dec, bool *pb_decode, int i_channel )
420 {
421     decoder_owner_sys_t *p_owner = p_dec->p_owner;
422
423     *pb_decode = false;
424     if( i_channel < 0 || i_channel >= 4 || !p_owner->pb_cc_present[i_channel] )
425         return VLC_EGENERIC;
426
427     vlc_mutex_lock( &p_owner->lock_cc );
428     *pb_decode = p_dec->p_owner->pp_cc[i_channel] != NULL;
429     vlc_mutex_unlock( &p_dec->p_owner->lock_cc );
430     return VLC_EGENERIC;
431 }
432
433 /**
434  * Create a decoder object
435  *
436  * \param p_input the input thread
437  * \param p_es the es descriptor
438  * \param i_object_type Object type as define in include/vlc_objects.h
439  * \return the decoder object
440  */
441 static decoder_t * CreateDecoder( input_thread_t *p_input,
442                                   es_format_t *fmt, int i_object_type, sout_instance_t *p_sout )
443 {
444     decoder_t *p_dec;
445     decoder_owner_sys_t *p_owner;
446     int i;
447
448     p_dec = vlc_object_create( p_input, i_object_type );
449     if( p_dec == NULL )
450         return NULL;
451
452     p_dec->pf_decode_audio = NULL;
453     p_dec->pf_decode_video = NULL;
454     p_dec->pf_decode_sub = NULL;
455     p_dec->pf_get_cc = NULL;
456     p_dec->pf_packetize = NULL;
457
458     /* Initialize the decoder fifo */
459     p_dec->p_module = NULL;
460
461     memset( &null_es_format, 0, sizeof(es_format_t) );
462     es_format_Copy( &p_dec->fmt_in, fmt );
463     es_format_Copy( &p_dec->fmt_out, &null_es_format );
464
465     /* Allocate our private structure for the decoder */
466     p_dec->p_owner = p_owner = malloc( sizeof( decoder_owner_sys_t ) );
467     if( p_dec->p_owner == NULL )
468     {
469         vlc_object_release( p_dec );
470         return NULL;
471     }
472     p_dec->p_owner->b_own_thread = true;
473     p_dec->p_owner->i_preroll_end = -1;
474     p_dec->p_owner->p_input = p_input;
475     p_dec->p_owner->p_aout = NULL;
476     p_dec->p_owner->p_aout_input = NULL;
477     p_dec->p_owner->p_vout = NULL;
478     p_dec->p_owner->p_spu_vout = NULL;
479     p_dec->p_owner->i_spu_channel = 0;
480     p_dec->p_owner->i_spu_order = 0;
481     p_dec->p_owner->p_sout = p_sout;
482     p_dec->p_owner->p_sout_input = NULL;
483     p_dec->p_owner->p_packetizer = NULL;
484
485     /* decoder fifo */
486     if( ( p_dec->p_owner->p_fifo = block_FifoNew() ) == NULL )
487     {
488         free( p_dec->p_owner );
489         vlc_object_release( p_dec );
490         return NULL;
491     }
492
493     /* Set buffers allocation callbacks for the decoders */
494     p_dec->pf_aout_buffer_new = aout_new_buffer;
495     p_dec->pf_aout_buffer_del = aout_del_buffer;
496     p_dec->pf_vout_buffer_new = vout_new_buffer;
497     p_dec->pf_vout_buffer_del = vout_del_buffer;
498     p_dec->pf_picture_link    = vout_link_picture;
499     p_dec->pf_picture_unlink  = vout_unlink_picture;
500     p_dec->pf_spu_buffer_new  = spu_new_buffer;
501     p_dec->pf_spu_buffer_del  = spu_del_buffer;
502
503     vlc_object_attach( p_dec, p_input );
504
505     /* Find a suitable decoder/packetizer module */
506     if( i_object_type == VLC_OBJECT_DECODER )
507         p_dec->p_module = module_need( p_dec, "decoder", "$codec", 0 );
508     else
509         p_dec->p_module = module_need( p_dec, "packetizer", "$packetizer", 0 );
510
511     /* Check if decoder requires already packetized data */
512     if( i_object_type == VLC_OBJECT_DECODER &&
513         p_dec->b_need_packetized && !p_dec->fmt_in.b_packetized )
514     {
515         p_dec->p_owner->p_packetizer =
516             vlc_object_create( p_input, VLC_OBJECT_PACKETIZER );
517         if( p_dec->p_owner->p_packetizer )
518         {
519             es_format_Copy( &p_dec->p_owner->p_packetizer->fmt_in,
520                             &p_dec->fmt_in );
521
522             es_format_Copy( &p_dec->p_owner->p_packetizer->fmt_out,
523                             &null_es_format );
524
525             vlc_object_attach( p_dec->p_owner->p_packetizer, p_input );
526
527             p_dec->p_owner->p_packetizer->p_module =
528                 module_need( p_dec->p_owner->p_packetizer,
529                              "packetizer", "$packetizer", 0 );
530
531             if( !p_dec->p_owner->p_packetizer->p_module )
532             {
533                 es_format_Clean( &p_dec->p_owner->p_packetizer->fmt_in );
534                 vlc_object_detach( p_dec->p_owner->p_packetizer );
535                 vlc_object_release( p_dec->p_owner->p_packetizer );
536             }
537         }
538     }
539
540     /* Copy ourself the input replay gain */
541     if( fmt->i_cat == AUDIO_ES )
542     {
543         for( i = 0; i < AUDIO_REPLAY_GAIN_MAX; i++ )
544         {
545             if( !p_dec->fmt_out.audio_replay_gain.pb_peak[i] )
546             {
547                 p_dec->fmt_out.audio_replay_gain.pb_peak[i] = fmt->audio_replay_gain.pb_peak[i];
548                 p_dec->fmt_out.audio_replay_gain.pf_peak[i] = fmt->audio_replay_gain.pf_peak[i];
549             }
550             if( !p_dec->fmt_out.audio_replay_gain.pb_gain[i] )
551             {
552                 p_dec->fmt_out.audio_replay_gain.pb_gain[i] = fmt->audio_replay_gain.pb_gain[i];
553                 p_dec->fmt_out.audio_replay_gain.pf_gain[i] = fmt->audio_replay_gain.pf_gain[i];
554             }
555         }
556     }
557     /* */
558     p_owner->b_cc_supported = false;
559     if( i_object_type == VLC_OBJECT_DECODER )
560     {
561         if( p_owner->p_packetizer && p_owner->p_packetizer->pf_get_cc )
562             p_owner->b_cc_supported = true;
563         if( p_dec->pf_get_cc )
564             p_owner->b_cc_supported = true;
565     }
566
567     vlc_mutex_init( &p_owner->lock_cc );
568     for( i = 0; i < 4; i++ )
569     {
570         p_owner->pb_cc_present[i] = false;
571         p_owner->pp_cc[i] = NULL;
572     }
573     return p_dec;
574 }
575
576 /**
577  * The decoding main loop
578  *
579  * \param p_dec the decoder
580  */
581 static void* DecoderThread( vlc_object_t *p_this )
582 {
583     decoder_t * p_dec = (decoder_t *)p_this;
584     block_t *p_block;
585     int canc = vlc_savecancel ();
586
587     /* The decoder's main loop */
588     while( !p_dec->b_die && !p_dec->b_error )
589     {
590         if( ( p_block = block_FifoGet( p_dec->p_owner->p_fifo ) ) == NULL )
591         {
592             p_dec->b_error = 1;
593             break;
594         }
595         if( DecoderDecode( p_dec, p_block ) != VLC_SUCCESS )
596         {
597             break;
598         }
599     }
600
601     while( !p_dec->b_die )
602     {
603         /* Trash all received PES packets */
604         p_block = block_FifoGet( p_dec->p_owner->p_fifo );
605         if( p_block ) block_Release( p_block );
606     }
607
608     /* We do it here because of the dll loader that wants close() in the
609      * same thread than open()/decode() */
610     module_unneed( p_dec, p_dec->p_module );
611     vlc_restorecancel (canc);
612     return NULL;
613 }
614
615 static inline void DecoderUpdatePreroll( int64_t *pi_preroll, const block_t *p )
616 {
617     if( p->i_flags & (BLOCK_FLAG_PREROLL|BLOCK_FLAG_DISCONTINUITY) )
618         *pi_preroll = INT64_MAX;
619     else if( p->i_pts > 0 )
620         *pi_preroll = __MIN( *pi_preroll, p->i_pts );
621     else if( p->i_dts > 0 )
622         *pi_preroll = __MIN( *pi_preroll, p->i_dts );
623 }
624 static void DecoderDecodeAudio( decoder_t *p_dec, block_t *p_block )
625 {
626     input_thread_t  *p_input = p_dec->p_owner->p_input;
627     const int       i_rate = p_block->i_rate;
628     aout_buffer_t   *p_aout_buf;
629
630     while( (p_aout_buf = p_dec->pf_decode_audio( p_dec, &p_block )) )
631     {
632         aout_instance_t *p_aout = p_dec->p_owner->p_aout;
633         aout_input_t    *p_aout_input = p_dec->p_owner->p_aout_input;
634
635         if( p_dec->b_die )
636         {
637             /* It prevent freezing VLC in case of broken decoder */
638             aout_DecDeleteBuffer( p_aout, p_aout_input, p_aout_buf );
639             if( p_block )
640                 block_Release( p_block );
641             break;
642         }
643         vlc_mutex_lock( &p_input->p->counters.counters_lock );
644         stats_UpdateInteger( p_dec, p_input->p->counters.p_decoded_audio, 1, NULL );
645         vlc_mutex_unlock( &p_input->p->counters.counters_lock );
646
647         if( p_aout_buf->start_date < p_dec->p_owner->i_preroll_end )
648         {
649             aout_DecDeleteBuffer( p_aout, p_aout_input, p_aout_buf );
650             continue;
651         }
652
653         if( p_dec->p_owner->i_preroll_end > 0 )
654         {
655             /* FIXME TODO flush audio output (don't know how to do that) */
656             msg_Dbg( p_dec, "End of audio preroll" );
657             p_dec->p_owner->i_preroll_end = -1;
658         }
659         aout_DecPlay( p_aout, p_aout_input, p_aout_buf, i_rate );
660     }
661 }
662 static void DecoderGetCc( decoder_t *p_dec, decoder_t *p_dec_cc )
663 {
664     block_t *p_cc;
665     bool pb_present[4];
666     int i;
667     int i_cc_decoder;
668
669     assert( p_dec_cc->pf_get_cc != NULL );
670
671     /* Do not try retreiving CC if not wanted (sout) or cannot be retreived */
672     if( !p_dec->p_owner->b_cc_supported )
673         return;
674
675     p_cc = p_dec_cc->pf_get_cc( p_dec_cc, pb_present );
676     if( !p_cc )
677         return;
678
679     vlc_mutex_lock( &p_dec->p_owner->lock_cc );
680     for( i = 0, i_cc_decoder = 0; i < 4; i++ )
681     {
682         p_dec->p_owner->pb_cc_present[i] |= pb_present[i];
683         if( p_dec->p_owner->pp_cc[i] )
684             i_cc_decoder++;
685     }
686
687     for( i = 0; i < 4; i++ )
688     {
689         if( !p_dec->p_owner->pp_cc[i] )
690             continue;
691
692         if( i_cc_decoder > 1 )
693             DecoderDecode( p_dec->p_owner->pp_cc[i], block_Duplicate( p_cc ) );
694         else
695             DecoderDecode( p_dec->p_owner->pp_cc[i], p_cc );
696         i_cc_decoder--;
697     }
698     vlc_mutex_unlock( &p_dec->p_owner->lock_cc );
699 }
700 static void VoutDisplayedPicture( vout_thread_t *p_vout, picture_t *p_pic )
701 {
702     vlc_mutex_lock( &p_vout->picture_lock );
703
704     if( p_pic->i_status == READY_PICTURE )
705     {
706         /* Grr cannot destroy ready picture by myself so be sure vout won't like it */
707         p_pic->date = 1;
708     }
709     else if( p_pic->i_refcount > 0 )
710     {
711         p_pic->i_status = DISPLAYED_PICTURE;
712     }
713     else
714     {
715         p_pic->i_status = DESTROYED_PICTURE;
716         picture_CleanupQuant( p_pic );
717         p_vout->i_heap_size--;
718     }
719
720     vlc_mutex_unlock( &p_vout->picture_lock );
721 }
722 static void VoutFlushPicture( vout_thread_t *p_vout )
723 {
724     int i;
725     vlc_mutex_lock( &p_vout->picture_lock );
726     for( i = 0; i < p_vout->render.i_pictures; i++ )
727     {
728         picture_t *p_pic = p_vout->render.pp_picture[i];
729
730         if( p_pic->i_status == READY_PICTURE ||
731             p_pic->i_status == DISPLAYED_PICTURE )
732         {
733             /* We cannot change picture status if it is in READY_PICTURE state,
734              * Just make sure they won't be displayed */
735             p_pic->date = 1;
736         }
737     }
738     vlc_mutex_unlock( &p_vout->picture_lock );
739 }
740
741 static void DecoderOptimizePtsDelay( decoder_t *p_dec )
742 {
743     input_thread_t *p_input = p_dec->p_owner->p_input;
744     vout_thread_t *p_vout = p_dec->p_owner->p_vout;
745     input_thread_private_t *p_priv = p_input->p;
746
747     picture_t *p_old = NULL;
748     picture_t *p_young = NULL;
749     int i;
750
751     /* Enable with --auto-adjust-pts-delay */
752     if( !p_priv->pts_adjust.b_auto_adjust )
753         return;
754
755     for( i = 0; i < I_RENDERPICTURES; i++ )
756     {
757         picture_t *p_pic = PP_RENDERPICTURE[i];
758
759         if( p_pic->i_status != READY_PICTURE )
760             continue;
761
762         if( !p_old || p_pic->date < p_old->date )
763             p_old = p_pic;
764         if( !p_young || p_pic->date > p_young->date )
765             p_young = p_pic;
766     }
767
768     if( !p_young || !p_old )
769         return;
770
771     /* Try to find if we can reduce the pts
772      * This first draft is way to simple, and we can't say if the
773      * algo will converge. It's also full of constants.
774      * But this simple algo allows to reduce the latency
775      * to the minimum.
776      * The whole point of this, is to bypass the pts_delay set
777      * by the access but also the delay arbitraly set by
778      * the remote server.
779      * Actually the remote server's muxer may set up a
780      * pts<->dts delay in the muxed stream. That is
781      * why we may end up in having a negative pts_delay,
782      * to compensate that artificial delay. */
783     const mtime_t i_buffer_length = p_young->date - p_old->date;
784     int64_t i_pts_slide = 0;
785     if( i_buffer_length < 10000 )
786     {
787         if( p_priv->pts_adjust.i_num_faulty > 10 )
788         {
789             i_pts_slide = __MAX(p_input->i_pts_delay *3 / 2, 10000);
790             p_priv->pts_adjust.i_num_faulty = 0;
791         }
792         if( p_priv->pts_adjust.b_to_high )
793         {
794             p_priv->pts_adjust.b_to_high = !p_priv->pts_adjust.b_to_high;
795             p_priv->pts_adjust.i_num_faulty = 0;
796         }
797         p_priv->pts_adjust.i_num_faulty++;
798     }
799     else if( i_buffer_length > 100000 )
800     {
801         if( p_priv->pts_adjust.i_num_faulty > 25 )
802         {
803             i_pts_slide = -i_buffer_length/2;
804             p_priv->pts_adjust.i_num_faulty = 0;
805         }
806         if( p_priv->pts_adjust.b_to_high )
807         {
808             p_priv->pts_adjust.b_to_high = !p_priv->pts_adjust.b_to_high;
809             p_priv->pts_adjust.i_num_faulty = 0;
810         }
811         p_priv->pts_adjust.i_num_faulty++;
812     }
813     if( i_pts_slide != 0 )
814     {
815         const mtime_t i_pts_delay_org = p_input->i_pts_delay;
816
817         p_input->i_pts_delay += i_pts_slide;
818
819         /* Don't play with the pts delay for more than -2<->3sec */
820         if( p_input->i_pts_delay < -2000000 )
821             p_input->i_pts_delay = -2000000;
822         else if( p_input->i_pts_delay > 3000000 )
823             p_input->i_pts_delay = 3000000;
824         i_pts_slide = p_input->i_pts_delay - i_pts_delay_org;
825
826         msg_Dbg( p_input, "Sliding the pts by %dms pts delay at %dms picture buffer was %dms",
827             (int)i_pts_slide/1000, (int)p_input->i_pts_delay/1000, (int)i_buffer_length/1000);
828
829         vlc_mutex_lock( &p_vout->picture_lock );
830         /* Slide all the picture */
831         for( i = 0; i < I_RENDERPICTURES; i++ )
832             PP_RENDERPICTURE[i]->date += i_pts_slide;
833         /* FIXME: slide aout/spu */
834         vlc_mutex_unlock( &p_vout->picture_lock );
835     }
836 }
837
838 static void DecoderDecodeVideo( decoder_t *p_dec, block_t *p_block )
839 {
840     input_thread_t *p_input = p_dec->p_owner->p_input;
841     picture_t      *p_pic;
842
843     while( (p_pic = p_dec->pf_decode_video( p_dec, &p_block )) )
844     {
845         vout_thread_t  *p_vout = p_dec->p_owner->p_vout;
846         if( p_dec->b_die )
847         {
848             /* It prevent freezing VLC in case of broken decoder */
849             VoutDisplayedPicture( p_vout, p_pic );
850             if( p_block )
851                 block_Release( p_block );
852             break;
853         }
854
855         vlc_mutex_lock( &p_input->p->counters.counters_lock );
856         stats_UpdateInteger( p_dec, p_input->p->counters.p_decoded_video, 1, NULL );
857         vlc_mutex_unlock( &p_input->p->counters.counters_lock );
858
859         if( p_pic->date < p_dec->p_owner->i_preroll_end )
860         {
861             VoutDisplayedPicture( p_vout, p_pic );
862             continue;
863         }
864
865         if( p_dec->p_owner->i_preroll_end > 0 )
866         {
867             msg_Dbg( p_dec, "End of video preroll" );
868             if( p_vout )
869                 VoutFlushPicture( p_vout );
870             /* */
871             p_dec->p_owner->i_preroll_end = -1;
872         }
873
874         if( ( !p_dec->p_owner->p_packetizer || !p_dec->p_owner->p_packetizer->pf_get_cc ) && p_dec->pf_get_cc )
875             DecoderGetCc( p_dec, p_dec );
876
877         vout_DatePicture( p_vout, p_pic, p_pic->date );
878
879         DecoderOptimizePtsDelay( p_dec );
880
881         vout_DisplayPicture( p_vout, p_pic );
882     }
883 }
884
885 /**
886  * Decode a block
887  *
888  * \param p_dec the decoder object
889  * \param p_block the block to decode
890  * \return VLC_SUCCESS or an error code
891  */
892 static int DecoderDecode( decoder_t *p_dec, block_t *p_block )
893 {
894     decoder_owner_sys_t *p_sys = (decoder_owner_sys_t *)p_dec->p_owner;
895     const int i_rate = p_block ? p_block->i_rate : INPUT_RATE_DEFAULT;
896
897     if( p_block && p_block->i_buffer <= 0 )
898     {
899         block_Release( p_block );
900         return VLC_SUCCESS;
901     }
902
903 #ifdef ENABLE_SOUT
904     if( p_dec->i_object_type == VLC_OBJECT_PACKETIZER )
905     {
906         block_t *p_sout_block;
907
908         while( ( p_sout_block =
909                      p_dec->pf_packetize( p_dec, p_block ? &p_block : NULL ) ) )
910         {
911             if( !p_dec->p_owner->p_sout_input )
912             {
913                 es_format_Copy( &p_dec->p_owner->sout, &p_dec->fmt_out );
914
915                 p_dec->p_owner->sout.i_group = p_dec->fmt_in.i_group;
916                 p_dec->p_owner->sout.i_id = p_dec->fmt_in.i_id;
917                 if( p_dec->fmt_in.psz_language )
918                 {
919                     if( p_dec->p_owner->sout.psz_language )
920                         free( p_dec->p_owner->sout.psz_language );
921                     p_dec->p_owner->sout.psz_language =
922                         strdup( p_dec->fmt_in.psz_language );
923                 }
924
925                 p_dec->p_owner->p_sout_input =
926                     sout_InputNew( p_dec->p_owner->p_sout,
927                                    &p_dec->p_owner->sout );
928
929                 if( p_dec->p_owner->p_sout_input == NULL )
930                 {
931                     msg_Err( p_dec, "cannot create packetizer output (%4.4s)",
932                              (char *)&p_dec->p_owner->sout.i_codec );
933                     p_dec->b_error = true;
934
935                     while( p_sout_block )
936                     {
937                         block_t *p_next = p_sout_block->p_next;
938                         block_Release( p_sout_block );
939                         p_sout_block = p_next;
940                     }
941                     break;
942                 }
943             }
944
945             while( p_sout_block )
946             {
947                 block_t *p_next = p_sout_block->p_next;
948
949                 p_sout_block->p_next = NULL;
950                 p_sout_block->i_rate = i_rate;
951
952                 sout_InputSendBuffer( p_dec->p_owner->p_sout_input,
953                                       p_sout_block );
954
955                 p_sout_block = p_next;
956             }
957
958             /* For now it's enough, as only sout impact on this flag */
959             if( p_dec->p_owner->p_sout->i_out_pace_nocontrol > 0 &&
960                 p_dec->p_owner->p_input->p->b_out_pace_control )
961             {
962                 msg_Dbg( p_dec, "switching to sync mode" );
963                 p_dec->p_owner->p_input->p->b_out_pace_control = false;
964             }
965             else if( p_dec->p_owner->p_sout->i_out_pace_nocontrol <= 0 &&
966                      !p_dec->p_owner->p_input->p->b_out_pace_control )
967             {
968                 msg_Dbg( p_dec, "switching to async mode" );
969                 p_dec->p_owner->p_input->p->b_out_pace_control = true;
970             }
971         }
972     }
973     else
974 #endif
975     if( p_dec->fmt_in.i_cat == AUDIO_ES )
976     {
977         if( p_block )
978             DecoderUpdatePreroll( &p_dec->p_owner->i_preroll_end, p_block );
979
980         if( p_dec->p_owner->p_packetizer )
981         {
982             block_t *p_packetized_block;
983             decoder_t *p_packetizer = p_dec->p_owner->p_packetizer;
984
985             while( (p_packetized_block =
986                     p_packetizer->pf_packetize( p_packetizer, p_block ? &p_block : NULL )) )
987             {
988                 if( p_packetizer->fmt_out.i_extra && !p_dec->fmt_in.i_extra )
989                 {
990                     es_format_Clean( &p_dec->fmt_in );
991                     es_format_Copy( &p_dec->fmt_in, &p_packetizer->fmt_out );
992                 }
993
994                 while( p_packetized_block )
995                 {
996                     block_t *p_next = p_packetized_block->p_next;
997                     p_packetized_block->p_next = NULL;
998                     p_packetized_block->i_rate = i_rate;
999
1000                     DecoderDecodeAudio( p_dec, p_packetized_block );
1001
1002                     p_packetized_block = p_next;
1003                 }
1004             }
1005         }
1006         else if( p_block )
1007         {
1008             DecoderDecodeAudio( p_dec, p_block );
1009         }
1010     }
1011     else if( p_dec->fmt_in.i_cat == VIDEO_ES )
1012     {
1013         if( p_block )
1014             DecoderUpdatePreroll( &p_dec->p_owner->i_preroll_end, p_block );
1015
1016         if( p_dec->p_owner->p_packetizer )
1017         {
1018             block_t *p_packetized_block;
1019             decoder_t *p_packetizer = p_dec->p_owner->p_packetizer;
1020
1021             while( (p_packetized_block =
1022                     p_packetizer->pf_packetize( p_packetizer, p_block ? &p_block : NULL )) )
1023             {
1024                 if( p_packetizer->fmt_out.i_extra && !p_dec->fmt_in.i_extra )
1025                 {
1026                     es_format_Clean( &p_dec->fmt_in );
1027                     es_format_Copy( &p_dec->fmt_in, &p_packetizer->fmt_out );
1028                 }
1029                 if( p_packetizer->pf_get_cc )
1030                     DecoderGetCc( p_dec, p_packetizer );
1031
1032                 while( p_packetized_block )
1033                 {
1034                     block_t *p_next = p_packetized_block->p_next;
1035                     p_packetized_block->p_next = NULL;
1036                     p_packetized_block->i_rate = i_rate;
1037
1038                     DecoderDecodeVideo( p_dec, p_packetized_block );
1039
1040                     p_packetized_block = p_next;
1041                 }
1042             }
1043         }
1044         else if( p_block )
1045         {
1046             DecoderDecodeVideo( p_dec, p_block );
1047         }
1048     }
1049     else if( p_dec->fmt_in.i_cat == SPU_ES )
1050     {
1051         input_thread_t *p_input = p_dec->p_owner->p_input;
1052         vout_thread_t *p_vout;
1053         subpicture_t *p_spu;
1054         bool b_flushing = p_dec->p_owner->i_preroll_end == INT64_MAX;
1055         bool b_flush = false;
1056
1057         if( p_block )
1058         {
1059             DecoderUpdatePreroll( &p_dec->p_owner->i_preroll_end, p_block );
1060             b_flush = (p_block->i_flags & BLOCK_FLAG_CORE_FLUSH) != 0;
1061         }
1062
1063         if( !b_flushing && b_flush && p_sys->p_spu_vout )
1064         {
1065             p_vout = vlc_object_find( p_dec, VLC_OBJECT_VOUT, FIND_ANYWHERE );
1066
1067             if( p_vout && p_sys->p_spu_vout == p_vout )
1068                 spu_Control( p_vout->p_spu, SPU_CHANNEL_CLEAR,
1069                              p_dec->p_owner->i_spu_channel );
1070
1071             if( p_vout )
1072                 vlc_object_release( p_vout );
1073         }
1074
1075         while( (p_spu = p_dec->pf_decode_sub( p_dec, p_block ? &p_block : NULL ) ) )
1076         {
1077             vlc_mutex_lock( &p_input->p->counters.counters_lock );
1078             stats_UpdateInteger( p_dec, p_input->p->counters.p_decoded_sub, 1, NULL );
1079             vlc_mutex_unlock( &p_input->p->counters.counters_lock );
1080
1081             p_vout = vlc_object_find( p_dec, VLC_OBJECT_VOUT, FIND_ANYWHERE );
1082             if( p_vout && p_sys->p_spu_vout == p_vout )
1083             {
1084                 /* Prerool does not work very well with subtitle */
1085                 if( p_spu->i_start < p_dec->p_owner->i_preroll_end &&
1086                     ( p_spu->i_stop <= 0 || p_spu->i_stop < p_dec->p_owner->i_preroll_end ) )
1087                 {
1088                     spu_DestroySubpicture( p_vout->p_spu, p_spu );
1089                 }
1090                 else
1091                     spu_DisplaySubpicture( p_vout->p_spu, p_spu );
1092             }
1093             else
1094             {
1095                 msg_Warn( p_dec, "no vout found, leaking subpicture" );
1096             }
1097             if( p_vout )
1098                 vlc_object_release( p_vout );
1099         }
1100     }
1101     else
1102     {
1103         msg_Err( p_dec, "unknown ES format" );
1104         p_dec->b_error = 1;
1105     }
1106
1107     return p_dec->b_error ? VLC_EGENERIC : VLC_SUCCESS;
1108 }
1109
1110 /**
1111  * Destroys a decoder object
1112  *
1113  * \param p_dec the decoder object
1114  * \return nothing
1115  */
1116 static void DeleteDecoder( decoder_t * p_dec )
1117 {
1118     msg_Dbg( p_dec, "killing decoder fourcc `%4.4s', %u PES in FIFO",
1119              (char*)&p_dec->fmt_in.i_codec,
1120              (unsigned)block_FifoCount( p_dec->p_owner->p_fifo ) );
1121
1122     /* Free all packets still in the decoder fifo. */
1123     block_FifoEmpty( p_dec->p_owner->p_fifo );
1124     block_FifoRelease( p_dec->p_owner->p_fifo );
1125
1126     /* Cleanup */
1127     if( p_dec->p_owner->p_aout_input )
1128         aout_DecDelete( p_dec->p_owner->p_aout, p_dec->p_owner->p_aout_input );
1129     if( p_dec->p_owner->p_aout )
1130     {
1131         vlc_object_release( p_dec->p_owner->p_aout );
1132         p_dec->p_owner->p_aout = NULL;
1133     }
1134     if( p_dec->p_owner->p_vout )
1135     {
1136         int i_pic;
1137
1138 #define p_pic p_dec->p_owner->p_vout->render.pp_picture[i_pic]
1139         /* Hack to make sure all the the pictures are freed by the decoder */
1140         for( i_pic = 0; i_pic < p_dec->p_owner->p_vout->render.i_pictures;
1141              i_pic++ )
1142         {
1143             if( p_pic->i_status == RESERVED_PICTURE )
1144                 vout_DestroyPicture( p_dec->p_owner->p_vout, p_pic );
1145             if( p_pic->i_refcount > 0 )
1146                 vout_UnlinkPicture( p_dec->p_owner->p_vout, p_pic );
1147         }
1148 #undef p_pic
1149
1150         /* We are about to die. Reattach video output to p_vlc. */
1151         vout_Request( p_dec, p_dec->p_owner->p_vout, NULL );
1152         var_SetBool( p_dec->p_owner->p_input, "intf-change-vout", true );
1153     }
1154
1155 #ifdef ENABLE_SOUT
1156     if( p_dec->p_owner->p_sout_input )
1157     {
1158         sout_InputDelete( p_dec->p_owner->p_sout_input );
1159         es_format_Clean( &p_dec->p_owner->sout );
1160     }
1161 #endif
1162
1163     if( p_dec->fmt_in.i_cat == SPU_ES )
1164     {
1165         vout_thread_t *p_vout;
1166
1167         p_vout = vlc_object_find( p_dec, VLC_OBJECT_VOUT, FIND_ANYWHERE );
1168         if( p_vout )
1169         {
1170             spu_Control( p_vout->p_spu, SPU_CHANNEL_CLEAR,
1171                          p_dec->p_owner->i_spu_channel );
1172             vlc_object_release( p_vout );
1173         }
1174     }
1175
1176     es_format_Clean( &p_dec->fmt_in );
1177     es_format_Clean( &p_dec->fmt_out );
1178
1179     if( p_dec->p_owner->p_packetizer )
1180     {
1181         module_unneed( p_dec->p_owner->p_packetizer,
1182                        p_dec->p_owner->p_packetizer->p_module );
1183         es_format_Clean( &p_dec->p_owner->p_packetizer->fmt_in );
1184         es_format_Clean( &p_dec->p_owner->p_packetizer->fmt_out );
1185         vlc_object_detach( p_dec->p_owner->p_packetizer );
1186         vlc_object_release( p_dec->p_owner->p_packetizer );
1187     }
1188
1189     vlc_mutex_destroy( &p_dec->p_owner->lock_cc );
1190
1191     vlc_object_detach( p_dec );
1192
1193     free( p_dec->p_owner );
1194 }
1195
1196 /*****************************************************************************
1197  * Buffers allocation callbacks for the decoders
1198  *****************************************************************************/
1199 static aout_buffer_t *aout_new_buffer( decoder_t *p_dec, int i_samples )
1200 {
1201     decoder_owner_sys_t *p_sys = (decoder_owner_sys_t *)p_dec->p_owner;
1202     aout_buffer_t *p_buffer;
1203
1204     if( p_sys->p_aout_input != NULL &&
1205         ( p_dec->fmt_out.audio.i_rate != p_sys->audio.i_rate ||
1206           p_dec->fmt_out.audio.i_original_channels !=
1207               p_sys->audio.i_original_channels ||
1208           p_dec->fmt_out.audio.i_bytes_per_frame !=
1209               p_sys->audio.i_bytes_per_frame ) )
1210     {
1211         /* Parameters changed, restart the aout */
1212         aout_DecDelete( p_sys->p_aout, p_sys->p_aout_input );
1213         p_sys->p_aout_input = NULL;
1214     }
1215
1216     if( p_sys->p_aout_input == NULL )
1217     {
1218         audio_sample_format_t format;
1219         int i_force_dolby = config_GetInt( p_dec, "force-dolby-surround" );
1220
1221         p_dec->fmt_out.audio.i_format = p_dec->fmt_out.i_codec;
1222         p_sys->audio = p_dec->fmt_out.audio;
1223
1224         memcpy( &format, &p_sys->audio, sizeof( audio_sample_format_t ) );
1225         if ( i_force_dolby && (format.i_original_channels&AOUT_CHAN_PHYSMASK)
1226                                     == (AOUT_CHAN_LEFT|AOUT_CHAN_RIGHT) )
1227         {
1228             if ( i_force_dolby == 1 )
1229             {
1230                 format.i_original_channels = format.i_original_channels |
1231                                              AOUT_CHAN_DOLBYSTEREO;
1232             }
1233             else /* i_force_dolby == 2 */
1234             {
1235                 format.i_original_channels = format.i_original_channels &
1236                                              ~AOUT_CHAN_DOLBYSTEREO;
1237             }
1238         }
1239
1240         p_sys->p_aout_input =
1241             aout_DecNew( p_dec, &p_sys->p_aout, &format, &p_dec->fmt_out.audio_replay_gain );
1242         if( p_sys->p_aout_input == NULL )
1243         {
1244             msg_Err( p_dec, "failed to create audio output" );
1245             p_dec->b_error = true;
1246             return NULL;
1247         }
1248         p_dec->fmt_out.audio.i_bytes_per_frame =
1249             p_sys->audio.i_bytes_per_frame;
1250     }
1251
1252     p_buffer = aout_DecNewBuffer( p_sys->p_aout_input, i_samples );
1253
1254     return p_buffer;
1255 }
1256
1257 static void aout_del_buffer( decoder_t *p_dec, aout_buffer_t *p_buffer )
1258 {
1259     aout_DecDeleteBuffer( p_dec->p_owner->p_aout,
1260                           p_dec->p_owner->p_aout_input, p_buffer );
1261 }
1262
1263
1264 int vout_CountPictureAvailable( vout_thread_t *p_vout );
1265
1266 static picture_t *vout_new_buffer( decoder_t *p_dec )
1267 {
1268     decoder_owner_sys_t *p_sys = (decoder_owner_sys_t *)p_dec->p_owner;
1269     picture_t *p_pic;
1270
1271     if( p_sys->p_vout == NULL ||
1272         p_dec->fmt_out.video.i_width != p_sys->video.i_width ||
1273         p_dec->fmt_out.video.i_height != p_sys->video.i_height ||
1274         p_dec->fmt_out.video.i_chroma != p_sys->video.i_chroma ||
1275         p_dec->fmt_out.video.i_aspect != p_sys->video.i_aspect )
1276     {
1277         if( !p_dec->fmt_out.video.i_width ||
1278             !p_dec->fmt_out.video.i_height )
1279         {
1280             /* Can't create a new vout without display size */
1281             return NULL;
1282         }
1283
1284         if( !p_dec->fmt_out.video.i_visible_width ||
1285             !p_dec->fmt_out.video.i_visible_height )
1286         {
1287             if( p_dec->fmt_in.video.i_visible_width &&
1288                 p_dec->fmt_in.video.i_visible_height )
1289             {
1290                 p_dec->fmt_out.video.i_visible_width =
1291                     p_dec->fmt_in.video.i_visible_width;
1292                 p_dec->fmt_out.video.i_visible_height =
1293                     p_dec->fmt_in.video.i_visible_height;
1294             }
1295             else
1296             {
1297                 p_dec->fmt_out.video.i_visible_width =
1298                     p_dec->fmt_out.video.i_width;
1299                 p_dec->fmt_out.video.i_visible_height =
1300                     p_dec->fmt_out.video.i_height;
1301             }
1302         }
1303
1304         if( p_dec->fmt_out.video.i_visible_height == 1088 &&
1305             var_CreateGetBool( p_dec, "hdtv-fix" ) )
1306         {
1307             p_dec->fmt_out.video.i_visible_height = 1080;
1308             p_dec->fmt_out.video.i_sar_num *= 135;
1309             p_dec->fmt_out.video.i_sar_den *= 136;
1310             msg_Warn( p_dec, "Fixing broken HDTV stream (display_height=1088)");
1311         }
1312
1313         if( !p_dec->fmt_out.video.i_sar_num ||
1314             !p_dec->fmt_out.video.i_sar_den )
1315         {
1316             p_dec->fmt_out.video.i_sar_num = p_dec->fmt_out.video.i_aspect *
1317               p_dec->fmt_out.video.i_visible_height;
1318
1319             p_dec->fmt_out.video.i_sar_den = VOUT_ASPECT_FACTOR *
1320               p_dec->fmt_out.video.i_visible_width;
1321         }
1322
1323         vlc_ureduce( &p_dec->fmt_out.video.i_sar_num,
1324                      &p_dec->fmt_out.video.i_sar_den,
1325                      p_dec->fmt_out.video.i_sar_num,
1326                      p_dec->fmt_out.video.i_sar_den, 50000 );
1327
1328         p_dec->fmt_out.video.i_chroma = p_dec->fmt_out.i_codec;
1329         p_sys->video = p_dec->fmt_out.video;
1330
1331         p_sys->p_vout = vout_Request( p_dec, p_sys->p_vout,
1332                                       &p_dec->fmt_out.video );
1333         var_SetBool( p_sys->p_input, "intf-change-vout", true );
1334         if( p_sys->p_vout == NULL )
1335         {
1336             msg_Err( p_dec, "failed to create video output" );
1337             p_dec->b_error = true;
1338             return NULL;
1339         }
1340
1341         if( p_sys->video.i_rmask )
1342             p_sys->p_vout->render.i_rmask = p_sys->video.i_rmask;
1343         if( p_sys->video.i_gmask )
1344             p_sys->p_vout->render.i_gmask = p_sys->video.i_gmask;
1345         if( p_sys->video.i_bmask )
1346             p_sys->p_vout->render.i_bmask = p_sys->video.i_bmask;
1347     }
1348
1349     /* Get a new picture
1350      */
1351     for( p_pic = NULL; ; )
1352     {
1353         int i_pic, i_ready_pic;
1354
1355         if( p_dec->b_die || p_dec->b_error )
1356             return NULL;
1357
1358         /* The video filter chain required that there is always 1 free buffer
1359          * that it will use as temporary one. It will release the temporary
1360          * buffer once its work is done, so this check is safe even if we don't
1361          * lock around both count() and create().
1362          */
1363         if( vout_CountPictureAvailable( p_sys->p_vout ) >= 2 )
1364         {
1365             p_pic = vout_CreatePicture( p_sys->p_vout, 0, 0, 0 );
1366             if( p_pic )
1367                 break;
1368         }
1369
1370 #define p_pic p_dec->p_owner->p_vout->render.pp_picture[i_pic]
1371         /* Check the decoder doesn't leak pictures */
1372         for( i_pic = 0, i_ready_pic = 0; i_pic < p_dec->p_owner->p_vout->render.i_pictures; i_pic++ )
1373         {
1374             if( p_pic->i_status == READY_PICTURE )
1375             {
1376                 i_ready_pic++;
1377                 /* If we have at least 2 ready pictures, wait for the vout thread to
1378                  * process one */
1379                 if( i_ready_pic >= 2 )
1380                     break;
1381
1382                 continue;
1383             }
1384
1385             if( p_pic->i_status == DISPLAYED_PICTURE )
1386             {
1387                 /* If at least one displayed picture is not referenced
1388                  * let vout free it */
1389                 if( p_pic->i_refcount == 0 )
1390                     break;
1391             }
1392         }
1393         if( i_pic == p_dec->p_owner->p_vout->render.i_pictures )
1394         {
1395             /* Too many pictures are still referenced, there is probably a bug
1396              * with the decoder */
1397             msg_Err( p_dec, "decoder is leaking pictures, resetting the heap" );
1398
1399             /* Just free all the pictures */
1400             for( i_pic = 0; i_pic < p_dec->p_owner->p_vout->render.i_pictures;
1401                  i_pic++ )
1402             {
1403                 if( p_pic->i_status == RESERVED_PICTURE )
1404                     vout_DestroyPicture( p_dec->p_owner->p_vout, p_pic );
1405                 if( p_pic->i_refcount > 0 )
1406                 vout_UnlinkPicture( p_dec->p_owner->p_vout, p_pic );
1407             }
1408         }
1409 #undef p_pic
1410
1411         msleep( VOUT_OUTMEM_SLEEP );
1412     }
1413
1414     return p_pic;
1415 }
1416
1417 static void vout_del_buffer( decoder_t *p_dec, picture_t *p_pic )
1418 {
1419     VoutDisplayedPicture( p_dec->p_owner->p_vout, p_pic );
1420 }
1421
1422 static void vout_link_picture( decoder_t *p_dec, picture_t *p_pic )
1423 {
1424     vout_LinkPicture( p_dec->p_owner->p_vout, p_pic );
1425 }
1426
1427 static void vout_unlink_picture( decoder_t *p_dec, picture_t *p_pic )
1428 {
1429     vout_UnlinkPicture( p_dec->p_owner->p_vout, p_pic );
1430 }
1431
1432 static subpicture_t *spu_new_buffer( decoder_t *p_dec )
1433 {
1434     decoder_owner_sys_t *p_sys = (decoder_owner_sys_t *)p_dec->p_owner;
1435     vout_thread_t *p_vout = NULL;
1436     subpicture_t *p_subpic;
1437     int i_attempts = 30;
1438
1439     while( i_attempts-- )
1440     {
1441         if( p_dec->b_die || p_dec->b_error ) break;
1442
1443         p_vout = vlc_object_find( p_dec, VLC_OBJECT_VOUT, FIND_ANYWHERE );
1444         if( p_vout ) break;
1445
1446         msleep( VOUT_DISPLAY_DELAY );
1447     }
1448
1449     if( !p_vout )
1450     {
1451         msg_Warn( p_dec, "no vout found, dropping subpicture" );
1452         return NULL;
1453     }
1454
1455     if( p_sys->p_spu_vout != p_vout )
1456     {
1457         spu_Control( p_vout->p_spu, SPU_CHANNEL_REGISTER,
1458                      &p_sys->i_spu_channel );
1459         p_sys->i_spu_order = 0;
1460         p_sys->p_spu_vout = p_vout;
1461     }
1462
1463     p_subpic = spu_CreateSubpicture( p_vout->p_spu );
1464     if( p_subpic )
1465     {
1466         p_subpic->i_channel = p_sys->i_spu_channel;
1467         p_subpic->i_order = p_sys->i_spu_order++;
1468         p_subpic->b_subtitle = true;
1469     }
1470
1471     vlc_object_release( p_vout );
1472
1473     return p_subpic;
1474 }
1475
1476 static void spu_del_buffer( decoder_t *p_dec, subpicture_t *p_subpic )
1477 {
1478     decoder_owner_sys_t *p_sys = (decoder_owner_sys_t *)p_dec->p_owner;
1479     vout_thread_t *p_vout = NULL;
1480
1481     p_vout = vlc_object_find( p_dec, VLC_OBJECT_VOUT, FIND_ANYWHERE );
1482     if( !p_vout || p_sys->p_spu_vout != p_vout )
1483     {
1484         if( p_vout )
1485             vlc_object_release( p_vout );
1486         msg_Warn( p_dec, "no vout found, leaking subpicture" );
1487         return;
1488     }
1489
1490     spu_DestroySubpicture( p_vout->p_spu, p_subpic );
1491
1492     vlc_object_release( p_vout );
1493 }
1494