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