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