Fix deadlock when the decoder return an error.
[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                 block_Release( p_block );
827             else
828                 DecoderProcess( p_dec, p_block );
829         }
830     }
831
832     DecoderSignalBuffering( p_dec, true );
833     return NULL;
834 }
835
836 static void DecoderFlush( decoder_t *p_dec )
837 {
838     decoder_owner_sys_t *p_owner = p_dec->p_owner;
839     block_t *p_null;
840
841     vlc_assert_locked( &p_owner->lock );
842
843     /* Empty the fifo */
844     block_FifoEmpty( p_owner->p_fifo );
845
846     /* Monitor for flush end */
847     p_owner->b_flushing = true;
848     vlc_cond_signal( &p_owner->wait );
849
850     /* Send a special block */
851     p_null = block_New( p_dec, 128 );
852     if( !p_null )
853         return;
854     p_null->i_flags |= BLOCK_FLAG_DISCONTINUITY;
855     p_null->i_flags |= BLOCK_FLAG_CORE_FLUSH;
856     if( !p_dec->fmt_in.b_packetized )
857         p_null->i_flags |= BLOCK_FLAG_CORRUPTED;
858     memset( p_null->p_buffer, 0, p_null->i_buffer );
859
860     input_DecoderDecode( p_dec, p_null );
861
862     /* */
863     while( vlc_object_alive( p_dec ) && p_owner->b_flushing )
864         vlc_cond_wait( &p_owner->wait, &p_owner->lock );
865 }
866
867 static void DecoderSignalFlushed( decoder_t *p_dec )
868 {
869     decoder_owner_sys_t *p_owner = p_dec->p_owner;
870
871     vlc_mutex_lock( &p_owner->lock );
872
873     if( p_owner->b_flushing )
874     {
875         p_owner->b_flushing = false;
876         vlc_cond_signal( &p_owner->wait );
877     }
878
879     vlc_mutex_unlock( &p_owner->lock );
880 }
881
882 static void DecoderSignalBuffering( decoder_t *p_dec, bool b_full )
883 {
884     decoder_owner_sys_t *p_owner = p_dec->p_owner;
885
886     vlc_mutex_lock( &p_owner->lock );
887
888     if( p_owner->b_buffering )
889     {
890         if( b_full )
891             p_owner->buffer.b_full = true;
892         vlc_cond_signal( &p_owner->wait );
893     }
894
895     vlc_mutex_unlock( &p_owner->lock );
896 }
897
898 static bool DecoderIsFlushing( decoder_t *p_dec )
899 {
900     decoder_owner_sys_t *p_owner = p_dec->p_owner;
901     bool b_flushing;
902
903     vlc_mutex_lock( &p_owner->lock );
904
905     b_flushing = p_owner->b_flushing;
906
907     vlc_mutex_unlock( &p_owner->lock );
908
909     return b_flushing;
910 }
911
912 static void DecoderWaitUnblock( decoder_t *p_dec, bool *pb_reject )
913 {
914     decoder_owner_sys_t *p_owner = p_dec->p_owner;
915
916     vlc_assert_locked( &p_owner->lock );
917
918     while( !p_owner->b_flushing )
919     {
920         if( p_owner->b_paused )
921         {
922             if( p_owner->b_buffering && !p_owner->buffer.b_full )
923                 break;
924             if( p_owner->pause.i_ignore > 0 )
925             {
926                 p_owner->pause.i_ignore--;
927                 break;
928             }
929         }
930         else
931         {
932             if( !p_owner->b_buffering || !p_owner->buffer.b_full )
933                 break;
934         }
935         vlc_cond_wait( &p_owner->wait, &p_owner->lock );
936     }
937
938     if( pb_reject )
939         *pb_reject = p_owner->b_flushing;
940 }
941
942 static void DecoderOutputChangePause( decoder_t *p_dec, bool b_paused, mtime_t i_date )
943 {
944     decoder_owner_sys_t *p_owner = p_dec->p_owner;
945
946     vlc_assert_locked( &p_owner->lock );
947
948     /* XXX only audio and video output have to be paused.
949      * - for sout it is useless
950      * - for subs, it is done by the vout
951      */
952     if( p_dec->fmt_in.i_cat == AUDIO_ES )
953     {
954         if( p_owner->p_aout && p_owner->p_aout_input )
955             aout_DecChangePause( p_owner->p_aout, p_owner->p_aout_input,
956                                  b_paused, i_date );
957     }
958     else if( p_dec->fmt_in.i_cat == VIDEO_ES )
959     {
960         if( p_owner->p_vout )
961             vout_ChangePause( p_owner->p_vout, b_paused, i_date );
962     }
963 }
964 static inline void DecoderUpdatePreroll( int64_t *pi_preroll, const block_t *p )
965 {
966     if( p->i_flags & (BLOCK_FLAG_PREROLL|BLOCK_FLAG_DISCONTINUITY) )
967         *pi_preroll = INT64_MAX;
968     else if( p->i_pts > 0 )
969         *pi_preroll = __MIN( *pi_preroll, p->i_pts );
970     else if( p->i_dts > 0 )
971         *pi_preroll = __MIN( *pi_preroll, p->i_dts );
972 }
973
974 static mtime_t DecoderTeletextFixTs( mtime_t i_ts, mtime_t i_ts_delay )
975 {
976     mtime_t current_date = mdate();
977
978     /* FIXME I don't really like that, es_out SHOULD do it using the video pts */
979     if( !i_ts || i_ts > current_date + 10000000 || i_ts < current_date )
980     {
981         /* ETSI EN 300 472 Annex A : do not take into account the PTS
982          * for teletext streams. */
983         return current_date + 400000 + i_ts_delay;
984     }
985     return i_ts;
986 }
987
988 static void DecoderFixTs( decoder_t *p_dec, mtime_t *pi_ts0, mtime_t *pi_ts1,
989                           mtime_t *pi_duration, int *pi_rate, mtime_t *pi_delay, bool b_telx )
990 {
991     decoder_owner_sys_t *p_owner = p_dec->p_owner;
992     input_clock_t   *p_clock = p_owner->p_clock;
993     int i_rate = 0;
994
995     vlc_assert_locked( &p_owner->lock );
996
997     const mtime_t i_ts_delay = p_owner->p_input->i_pts_delay;
998     const mtime_t i_es_delay = p_owner->i_ts_delay;
999
1000     if( p_clock )
1001     {
1002         const bool b_ephemere = pi_ts1 && *pi_ts0 == *pi_ts1;
1003
1004         if( *pi_ts0 > 0 )
1005             *pi_ts0 = input_clock_GetTS( p_clock, &i_rate, i_ts_delay,
1006                                          *pi_ts0 + i_es_delay );
1007         if( pi_ts1 && *pi_ts1 > 0 )
1008             *pi_ts1 = input_clock_GetTS( p_clock, &i_rate, i_ts_delay,
1009                                          *pi_ts1 + i_es_delay );
1010
1011         /* Do not create ephemere data because of rounding errors */
1012         if( !b_ephemere && pi_ts1 && *pi_ts0 == *pi_ts1 )
1013             *pi_ts1 += 1;
1014
1015         if( i_rate <= 0 )
1016             i_rate = input_clock_GetRate( p_clock ); 
1017
1018         if( pi_duration )
1019             *pi_duration = ( *pi_duration * i_rate +
1020                                     INPUT_RATE_DEFAULT-1 ) / INPUT_RATE_DEFAULT;
1021
1022         if( pi_rate )
1023             *pi_rate = i_rate;
1024
1025         if( b_telx )
1026         {
1027             *pi_ts0 = DecoderTeletextFixTs( *pi_ts0, i_ts_delay );
1028             if( pi_ts1 && *pi_ts1 <= 0 )
1029                 *pi_ts1 = *pi_ts0;
1030         }
1031     }
1032     if( pi_delay )
1033     {
1034         const int r = i_rate > 0 ? i_rate : INPUT_RATE_DEFAULT;
1035         *pi_delay = i_ts_delay + i_es_delay * r / INPUT_RATE_DEFAULT;
1036     }
1037 }
1038
1039 static void DecoderPlayAudio( decoder_t *p_dec, aout_buffer_t *p_audio,
1040                               int *pi_played_sum, int *pi_lost_sum )
1041 {
1042     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1043     aout_instance_t *p_aout = p_owner->p_aout;
1044     aout_input_t    *p_aout_input = p_owner->p_aout_input;
1045
1046     /* */
1047     if( p_audio->start_date <= 0 )
1048     {
1049         msg_Warn( p_dec, "non-dated audio buffer received" );
1050         *pi_lost_sum += 1;
1051         aout_BufferFree( p_audio );
1052         return;
1053     }
1054
1055     /* */
1056     vlc_mutex_lock( &p_owner->lock );
1057
1058     if( p_owner->b_buffering || p_owner->buffer.p_audio )
1059     {
1060         p_audio->p_next = NULL;
1061
1062         *p_owner->buffer.pp_audio_next = p_audio;
1063         p_owner->buffer.pp_audio_next = &p_audio->p_next;
1064
1065         p_owner->buffer.i_count++;
1066         if( p_owner->buffer.i_count > DECODER_MAX_BUFFERING_COUNT ||
1067             p_audio->start_date - p_owner->buffer.p_audio->start_date > DECODER_MAX_BUFFERING_AUDIO_DURATION )
1068         {
1069             p_owner->buffer.b_full = true;
1070             vlc_cond_signal( &p_owner->wait );
1071         }
1072     }
1073
1074     for( ;; )
1075     {
1076         bool b_has_more = false;
1077         bool b_reject;
1078         DecoderWaitUnblock( p_dec, &b_reject );
1079
1080         if( p_owner->b_buffering )
1081         {
1082             vlc_mutex_unlock( &p_owner->lock );
1083             return;
1084         }
1085
1086         /* */
1087         if( p_owner->buffer.p_audio )
1088         {
1089             p_audio = p_owner->buffer.p_audio;
1090
1091             p_owner->buffer.p_audio = p_audio->p_next;
1092             p_owner->buffer.i_count--;
1093
1094             b_has_more = p_owner->buffer.p_audio != NULL;
1095             if( !b_has_more )
1096                 p_owner->buffer.pp_audio_next = &p_owner->buffer.p_audio;
1097         }
1098
1099         /* */
1100         int i_rate = INPUT_RATE_DEFAULT;
1101         mtime_t i_delay;
1102
1103         DecoderFixTs( p_dec, &p_audio->start_date, &p_audio->end_date, NULL,
1104                       &i_rate, &i_delay, false );
1105
1106         vlc_mutex_unlock( &p_owner->lock );
1107
1108         /* */
1109         const mtime_t i_max_date = mdate() + i_delay + AOUT_MAX_ADVANCE_TIME;
1110
1111         if( !p_aout || !p_aout_input ||
1112             p_audio->start_date <= 0 || p_audio->start_date > i_max_date ||
1113             i_rate < INPUT_RATE_DEFAULT/AOUT_MAX_INPUT_RATE ||
1114             i_rate > INPUT_RATE_DEFAULT*AOUT_MAX_INPUT_RATE )
1115             b_reject = true;
1116
1117         if( !b_reject )
1118         {
1119             /* Wait if we are too early
1120              * FIXME that's plain ugly to do it here */
1121             mwait( p_audio->start_date - AOUT_MAX_PREPARE_TIME );
1122
1123             if( !aout_DecPlay( p_aout, p_aout_input, p_audio, i_rate ) )
1124                 *pi_played_sum += 1;
1125             *pi_lost_sum += aout_DecGetResetLost( p_aout, p_aout_input );
1126         }
1127         else
1128         {
1129             if( p_audio->start_date <= 0 )
1130             {
1131                 msg_Warn( p_dec, "non-dated audio buffer received" );
1132             }
1133             else if( p_audio->start_date > i_max_date )
1134             {
1135                 msg_Warn( p_aout, "received buffer in the future (%"PRId64")",
1136                           p_audio->start_date - mdate() );
1137             }
1138             *pi_lost_sum += 1;
1139             aout_BufferFree( p_audio );
1140         }
1141
1142         if( !b_has_more )
1143             break;
1144
1145         vlc_mutex_lock( &p_owner->lock );
1146         if( !p_owner->buffer.p_audio )
1147         {
1148             vlc_mutex_unlock( &p_owner->lock );
1149             break;
1150         }
1151     }
1152 }
1153
1154 static void DecoderDecodeAudio( decoder_t *p_dec, block_t *p_block )
1155 {
1156     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1157     input_thread_t  *p_input = p_owner->p_input;
1158     aout_buffer_t   *p_aout_buf;
1159     int i_decoded = 0;
1160     int i_lost = 0;
1161     int i_played = 0;
1162
1163     while( (p_aout_buf = p_dec->pf_decode_audio( p_dec, &p_block )) )
1164     {
1165         aout_instance_t *p_aout = p_owner->p_aout;
1166         aout_input_t    *p_aout_input = p_owner->p_aout_input;
1167         int i_lost = 0;
1168         int i_played;
1169
1170         if( p_dec->b_die )
1171         {
1172             /* It prevent freezing VLC in case of broken decoder */
1173             aout_DecDeleteBuffer( p_aout, p_aout_input, p_aout_buf );
1174             if( p_block )
1175                 block_Release( p_block );
1176             break;
1177         }
1178         i_decoded++;
1179
1180         if( p_aout_buf->start_date < p_owner->i_preroll_end )
1181         {
1182             aout_DecDeleteBuffer( p_aout, p_aout_input, p_aout_buf );
1183             continue;
1184         }
1185
1186         if( p_owner->i_preroll_end > 0 )
1187         {
1188             msg_Dbg( p_dec, "End of audio preroll" );
1189             if( p_owner->p_aout && p_owner->p_aout_input )
1190                 aout_DecFlush( p_owner->p_aout, p_owner->p_aout_input );
1191             /* */
1192             p_owner->i_preroll_end = -1;
1193         }
1194
1195         DecoderPlayAudio( p_dec, p_aout_buf, &i_played, &i_lost );
1196     }
1197
1198     /* Update ugly stat */
1199     if( i_decoded > 0 || i_lost > 0 || i_played > 0 )
1200     {
1201         vlc_mutex_lock( &p_input->p->counters.counters_lock);
1202
1203         stats_UpdateInteger( p_dec, p_input->p->counters.p_lost_abuffers,
1204                              i_lost, NULL );
1205         stats_UpdateInteger( p_dec, p_input->p->counters.p_played_abuffers,
1206                              i_played, NULL );
1207         stats_UpdateInteger( p_dec, p_input->p->counters.p_decoded_audio,
1208                              i_decoded, NULL );
1209
1210         vlc_mutex_unlock( &p_input->p->counters.counters_lock);
1211     }
1212 }
1213 static void DecoderGetCc( decoder_t *p_dec, decoder_t *p_dec_cc )
1214 {
1215     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1216     block_t *p_cc;
1217     bool pb_present[4];
1218     int i;
1219     int i_cc_decoder;
1220
1221     assert( p_dec_cc->pf_get_cc != NULL );
1222
1223     /* Do not try retreiving CC if not wanted (sout) or cannot be retreived */
1224     if( !p_owner->cc.b_supported )
1225         return;
1226
1227     p_cc = p_dec_cc->pf_get_cc( p_dec_cc, pb_present );
1228     if( !p_cc )
1229         return;
1230
1231     vlc_mutex_lock( &p_owner->lock );
1232     for( i = 0, i_cc_decoder = 0; i < 4; i++ )
1233     {
1234         p_owner->cc.pb_present[i] |= pb_present[i];
1235         if( p_owner->cc.pp_decoder[i] )
1236             i_cc_decoder++;
1237     }
1238
1239     for( i = 0; i < 4; i++ )
1240     {
1241         if( !p_owner->cc.pp_decoder[i] )
1242             continue;
1243
1244         if( i_cc_decoder > 1 )
1245             DecoderProcess( p_owner->cc.pp_decoder[i], block_Duplicate( p_cc ) );
1246         else
1247             DecoderProcess( p_owner->cc.pp_decoder[i], p_cc );
1248         i_cc_decoder--;
1249     }
1250     vlc_mutex_unlock( &p_owner->lock );
1251 }
1252
1253 static void DecoderPlayVideo( decoder_t *p_dec, picture_t *p_picture,
1254                               int *pi_played_sum, int *pi_lost_sum )
1255 {
1256     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1257     vout_thread_t  *p_vout = p_owner->p_vout;
1258     bool b_first_buffered;
1259
1260     if( p_picture->date <= 0 )
1261     {
1262         msg_Warn( p_vout, "non-dated video buffer received" );
1263         *pi_lost_sum += 1;
1264         vout_DropPicture( p_vout, p_picture );
1265         return;
1266     }
1267
1268     /* */
1269     vlc_mutex_lock( &p_owner->lock );
1270
1271     if( ( p_owner->b_buffering && !p_owner->buffer.b_first ) || p_owner->buffer.p_picture )
1272     {
1273         p_picture->p_next = NULL;
1274
1275         *p_owner->buffer.pp_picture_next = p_picture;
1276         p_owner->buffer.pp_picture_next = &p_picture->p_next;
1277
1278         p_owner->buffer.i_count++;
1279         if( p_owner->buffer.i_count > DECODER_MAX_BUFFERING_COUNT ||
1280             p_picture->date - p_owner->buffer.p_picture->date > DECODER_MAX_BUFFERING_VIDEO_DURATION )
1281         {
1282             p_owner->buffer.b_full = true;
1283             vlc_cond_signal( &p_owner->wait );
1284         }
1285     }
1286     b_first_buffered = p_owner->buffer.p_picture != NULL;
1287
1288     for( ;; b_first_buffered = false )
1289     {
1290         bool b_has_more = false;
1291
1292         bool b_reject;
1293
1294         DecoderWaitUnblock( p_dec, &b_reject );
1295
1296         if( p_owner->b_buffering && !p_owner->buffer.b_first )
1297         {
1298             vlc_mutex_unlock( &p_owner->lock );
1299             return;
1300         }
1301         bool b_buffering_first = p_owner->b_buffering;
1302
1303         /* */
1304         if( p_owner->buffer.p_picture )
1305         {
1306             p_picture = p_owner->buffer.p_picture;
1307
1308             p_owner->buffer.p_picture = p_picture->p_next;
1309             p_owner->buffer.i_count--;
1310
1311             b_has_more = p_owner->buffer.p_picture != NULL;
1312             if( !b_has_more )
1313                 p_owner->buffer.pp_picture_next = &p_owner->buffer.p_picture;
1314         }
1315
1316         /* */
1317         int i_rate = INPUT_RATE_DEFAULT;
1318         mtime_t i_delay;
1319
1320         if( b_buffering_first )
1321         {
1322             assert( p_owner->buffer.b_first );
1323             assert( !p_owner->buffer.i_count );
1324             msg_Dbg( p_dec, "Received first picture" );
1325             p_owner->buffer.b_first = false;
1326             p_picture->b_force = true;
1327             i_delay = 0;
1328             if( p_owner->p_clock )
1329                 i_rate = input_clock_GetRate( p_owner->p_clock );
1330         }
1331         DecoderFixTs( p_dec, &p_picture->date, NULL, NULL,
1332                       &i_rate, &i_delay, false );
1333
1334         vlc_mutex_unlock( &p_owner->lock );
1335
1336         /* */
1337         const mtime_t i_max_date = mdate() + i_delay + DECODER_BOGUS_VIDEO_DELAY;
1338
1339         if( !p_picture->b_force && ( p_picture->date <= 0 || p_picture->date >= i_max_date ) )
1340             b_reject = true;
1341
1342         if( !b_reject )
1343         {
1344             if( i_rate != p_owner->i_last_rate || b_first_buffered )
1345             {
1346                 /* Be sure to not display old picture after our own */
1347                 vout_Flush( p_vout, p_picture->date );
1348                 p_owner->i_last_rate = i_rate;
1349             }
1350             vout_DisplayPicture( p_vout, p_picture );
1351         }
1352         else
1353         {
1354             if( p_picture->date <= 0 )
1355             {
1356                 msg_Warn( p_vout, "non-dated video buffer received" );
1357             }
1358             else
1359             {
1360                 msg_Warn( p_vout, "early picture skipped (%"PRId64")",
1361                           p_picture->date - mdate() );
1362             }
1363             *pi_lost_sum += 1;
1364             vout_DropPicture( p_vout, p_picture );
1365         }
1366         int i_tmp_display;
1367         int i_tmp_lost;
1368         vout_GetResetStatistic( p_vout, &i_tmp_display, &i_tmp_lost );
1369
1370         *pi_played_sum += i_tmp_display;
1371         *pi_lost_sum += i_tmp_lost;
1372
1373         if( !b_has_more || b_buffering_first )
1374             break;
1375
1376         vlc_mutex_lock( &p_owner->lock );
1377         if( !p_owner->buffer.p_picture )
1378         {
1379             vlc_mutex_unlock( &p_owner->lock );
1380             break;
1381         }
1382     }
1383 }
1384
1385 static void DecoderDecodeVideo( decoder_t *p_dec, block_t *p_block )
1386 {
1387     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1388     input_thread_t *p_input = p_owner->p_input;
1389     picture_t      *p_pic;
1390     int i_lost = 0;
1391     int i_decoded = 0;
1392     int i_displayed = 0;
1393
1394     while( (p_pic = p_dec->pf_decode_video( p_dec, &p_block )) )
1395     {
1396         vout_thread_t  *p_vout = p_owner->p_vout;
1397         if( p_dec->b_die )
1398         {
1399             /* It prevent freezing VLC in case of broken decoder */
1400             vout_DropPicture( p_vout, p_pic );
1401             if( p_block )
1402                 block_Release( p_block );
1403             break;
1404         }
1405
1406         i_decoded++;
1407
1408         if( p_pic->date < p_owner->i_preroll_end )
1409         {
1410             vout_DropPicture( p_vout, p_pic );
1411             continue;
1412         }
1413
1414         if( p_owner->i_preroll_end > 0 )
1415         {
1416             msg_Dbg( p_dec, "End of video preroll" );
1417             if( p_vout )
1418                 vout_Flush( p_vout, 1 );
1419             /* */
1420             p_owner->i_preroll_end = -1;
1421         }
1422
1423         if( p_dec->pf_get_cc &&
1424             ( !p_owner->p_packetizer || !p_owner->p_packetizer->pf_get_cc ) )
1425             DecoderGetCc( p_dec, p_dec );
1426
1427         DecoderPlayVideo( p_dec, p_pic, &i_displayed, &i_lost );
1428     }
1429     if( i_decoded > 0 || i_lost > 0 || i_displayed > 0 )
1430     {
1431         vlc_mutex_lock( &p_input->p->counters.counters_lock );
1432
1433         stats_UpdateInteger( p_dec, p_input->p->counters.p_decoded_video,
1434                              i_decoded, NULL );
1435         stats_UpdateInteger( p_dec, p_input->p->counters.p_lost_pictures,
1436                              i_lost , NULL);
1437
1438         stats_UpdateInteger( p_dec, p_input->p->counters.p_displayed_pictures,
1439                              i_displayed, NULL);
1440
1441         vlc_mutex_unlock( &p_input->p->counters.counters_lock );
1442     }
1443 }
1444
1445 static void DecoderPlaySpu( decoder_t *p_dec, subpicture_t *p_subpic,
1446                             bool b_telx )
1447 {
1448     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1449     vout_thread_t *p_vout = p_owner->p_spu_vout;
1450
1451     /* */
1452     if( p_subpic->i_start <= 0 )
1453     {
1454         msg_Warn( p_dec, "non-dated spu buffer received" );
1455         subpicture_Delete( p_subpic );
1456         return;
1457     }
1458
1459     /* */
1460     vlc_mutex_lock( &p_owner->lock );
1461
1462     if( p_owner->b_buffering || p_owner->buffer.p_subpic )
1463     {
1464         p_subpic->p_next = NULL;
1465
1466         *p_owner->buffer.pp_subpic_next = p_subpic;
1467         p_owner->buffer.pp_subpic_next = &p_subpic->p_next;
1468
1469         p_owner->buffer.i_count++;
1470         /* XXX it is important to be full after the first one */
1471         if( p_owner->buffer.i_count > 0 )
1472         {
1473             p_owner->buffer.b_full = true;
1474             vlc_cond_signal( &p_owner->wait );
1475         }
1476     }
1477
1478     for( ;; )
1479     {
1480         bool b_has_more = false;
1481         bool b_reject;
1482         DecoderWaitUnblock( p_dec, &b_reject );
1483
1484         if( p_owner->b_buffering )
1485         {
1486             vlc_mutex_unlock( &p_owner->lock );
1487             return;
1488         }
1489
1490         /* */
1491         if( p_owner->buffer.p_subpic )
1492         {
1493             p_subpic = p_owner->buffer.p_subpic;
1494
1495             p_owner->buffer.p_subpic = p_subpic->p_next;
1496             p_owner->buffer.i_count--;
1497
1498             b_has_more = p_owner->buffer.p_subpic != NULL;
1499             if( !b_has_more )
1500                 p_owner->buffer.pp_subpic_next = &p_owner->buffer.p_subpic;
1501         }
1502
1503         /* */
1504         DecoderFixTs( p_dec, &p_subpic->i_start, &p_subpic->i_stop, NULL,
1505                       NULL, NULL, b_telx );
1506
1507         vlc_mutex_unlock( &p_owner->lock );
1508
1509         if( !b_reject )
1510             spu_DisplaySubpicture( p_vout->p_spu, p_subpic );
1511         else
1512             subpicture_Delete( p_subpic );
1513
1514         if( !b_has_more )
1515             break;
1516         vlc_mutex_lock( &p_owner->lock );
1517         if( !p_owner->buffer.p_subpic )
1518         {
1519             vlc_mutex_unlock( &p_owner->lock );
1520             break;
1521         }
1522     }
1523 }
1524
1525 static void DecoderPlaySout( decoder_t *p_dec, block_t *p_sout_block,
1526                              bool b_telx )
1527 {
1528     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1529
1530     assert( p_owner->p_clock );
1531     assert( !p_sout_block->p_next );
1532
1533     vlc_mutex_lock( &p_owner->lock );
1534
1535     if( p_owner->b_buffering || p_owner->buffer.p_block )
1536     {
1537         block_ChainLastAppend( &p_owner->buffer.pp_block_next, p_sout_block );
1538
1539         p_owner->buffer.i_count++;
1540         /* XXX it is important to be full after the first one */
1541         if( p_owner->buffer.i_count > 0 )
1542         {
1543             p_owner->buffer.b_full = true;
1544             vlc_cond_signal( &p_owner->wait );
1545         }
1546     }
1547
1548     for( ;; )
1549     {
1550         bool b_has_more = false;
1551         bool b_reject;
1552         DecoderWaitUnblock( p_dec, &b_reject );
1553
1554         if( p_owner->b_buffering )
1555         {
1556             vlc_mutex_unlock( &p_owner->lock );
1557             return;
1558         }
1559
1560         /* */
1561         if( p_owner->buffer.p_block )
1562         {
1563             p_sout_block = p_owner->buffer.p_block;
1564
1565             p_owner->buffer.p_block = p_sout_block->p_next;
1566             p_owner->buffer.i_count--;
1567
1568             b_has_more = p_owner->buffer.p_block != NULL;
1569             if( !b_has_more )
1570                 p_owner->buffer.pp_block_next = &p_owner->buffer.p_block;
1571         }
1572         p_sout_block->p_next = NULL;
1573
1574         DecoderFixTs( p_dec, &p_sout_block->i_dts, &p_sout_block->i_pts,
1575                       &p_sout_block->i_length,
1576                       &p_sout_block->i_rate, NULL, b_telx );
1577
1578         vlc_mutex_unlock( &p_owner->lock );
1579
1580         if( !b_reject )
1581             sout_InputSendBuffer( p_owner->p_sout_input, p_sout_block );
1582         else
1583             block_Release( p_sout_block );
1584
1585         if( !b_has_more )
1586             break;
1587         vlc_mutex_lock( &p_owner->lock );
1588         if( !p_owner->buffer.p_block )
1589         {
1590             vlc_mutex_unlock( &p_owner->lock );
1591             break;
1592         }
1593     }
1594 }
1595
1596 /* */
1597 static void DecoderFlushBuffering( decoder_t *p_dec )
1598 {
1599     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1600
1601     vlc_assert_locked( &p_owner->lock );
1602
1603     while( p_owner->buffer.p_picture )
1604     {
1605         picture_t *p_picture = p_owner->buffer.p_picture;
1606
1607         p_owner->buffer.p_picture = p_picture->p_next;
1608         p_owner->buffer.i_count--;
1609
1610         if( p_owner->p_vout )
1611             vout_DropPicture( p_owner->p_vout, p_picture );
1612
1613         if( !p_owner->buffer.p_picture )
1614             p_owner->buffer.pp_picture_next = &p_owner->buffer.p_picture;
1615     }
1616     while( p_owner->buffer.p_audio )
1617     {
1618         aout_buffer_t *p_audio = p_owner->buffer.p_audio;
1619
1620         p_owner->buffer.p_audio = p_audio->p_next;
1621         p_owner->buffer.i_count--;
1622
1623         aout_BufferFree( p_audio );
1624
1625         if( !p_owner->buffer.p_audio )
1626             p_owner->buffer.pp_audio_next = &p_owner->buffer.p_audio;
1627     }
1628     while( p_owner->buffer.p_subpic )
1629     {
1630         subpicture_t *p_subpic = p_owner->buffer.p_subpic;
1631
1632         p_owner->buffer.p_subpic = p_subpic->p_next;
1633         p_owner->buffer.i_count--;
1634
1635         subpicture_Delete( p_subpic );
1636
1637         if( !p_owner->buffer.p_subpic )
1638             p_owner->buffer.pp_subpic_next = &p_owner->buffer.p_subpic;
1639     }
1640     if( p_owner->buffer.p_block )
1641     {
1642         block_ChainRelease( p_owner->buffer.p_block );
1643
1644         p_owner->buffer.i_count = 0;
1645         p_owner->buffer.p_block = NULL;
1646         p_owner->buffer.pp_block_next = &p_owner->buffer.p_block;
1647     }
1648 }
1649
1650 /* This function process a block for sout
1651  */
1652 static void DecoderProcessSout( decoder_t *p_dec, block_t *p_block )
1653 {
1654     decoder_owner_sys_t *p_owner = (decoder_owner_sys_t *)p_dec->p_owner;
1655     const bool b_telx = p_dec->fmt_in.i_codec == VLC_FOURCC('t','e','l','x');
1656     block_t *p_sout_block;
1657
1658     while( ( p_sout_block =
1659                  p_dec->pf_packetize( p_dec, p_block ? &p_block : NULL ) ) )
1660     {
1661         if( !p_owner->p_sout_input )
1662         {
1663             es_format_Copy( &p_owner->sout, &p_dec->fmt_out );
1664
1665             p_owner->sout.i_group = p_dec->fmt_in.i_group;
1666             p_owner->sout.i_id = p_dec->fmt_in.i_id;
1667             if( p_dec->fmt_in.psz_language )
1668             {
1669                 if( p_owner->sout.psz_language )
1670                     free( p_owner->sout.psz_language );
1671                 p_owner->sout.psz_language =
1672                     strdup( p_dec->fmt_in.psz_language );
1673             }
1674
1675             p_owner->p_sout_input =
1676                 sout_InputNew( p_owner->p_sout,
1677                                &p_owner->sout );
1678
1679             if( p_owner->p_sout_input == NULL )
1680             {
1681                 msg_Err( p_dec, "cannot create packetizer output (%4.4s)",
1682                          (char *)&p_owner->sout.i_codec );
1683                 p_dec->b_error = true;
1684
1685                 while( p_sout_block )
1686                 {
1687                     block_t *p_next = p_sout_block->p_next;
1688                     block_Release( p_sout_block );
1689                     p_sout_block = p_next;
1690                 }
1691                 break;
1692             }
1693         }
1694
1695         while( p_sout_block )
1696         {
1697             block_t *p_next = p_sout_block->p_next;
1698
1699             p_sout_block->p_next = NULL;
1700
1701             DecoderPlaySout( p_dec, p_sout_block, b_telx );
1702
1703             p_sout_block = p_next;
1704         }
1705
1706         /* For now it's enough, as only sout impact on this flag */
1707         if( p_owner->p_sout->i_out_pace_nocontrol > 0 &&
1708             p_owner->p_input->p->b_out_pace_control )
1709         {
1710             msg_Dbg( p_dec, "switching to sync mode" );
1711             p_owner->p_input->p->b_out_pace_control = false;
1712         }
1713         else if( p_owner->p_sout->i_out_pace_nocontrol <= 0 &&
1714                  !p_owner->p_input->p->b_out_pace_control )
1715         {
1716             msg_Dbg( p_dec, "switching to async mode" );
1717             p_owner->p_input->p->b_out_pace_control = true;
1718         }
1719     }
1720 }
1721
1722 /* This function process a video block
1723  */
1724 static void DecoderProcessVideo( decoder_t *p_dec, block_t *p_block, bool b_flush )
1725 {
1726     decoder_owner_sys_t *p_owner = (decoder_owner_sys_t *)p_dec->p_owner;
1727
1728     if( p_owner->p_packetizer )
1729     {
1730         block_t *p_packetized_block;
1731         decoder_t *p_packetizer = p_owner->p_packetizer;
1732
1733         while( (p_packetized_block =
1734                 p_packetizer->pf_packetize( p_packetizer, p_block ? &p_block : NULL )) )
1735         {
1736             if( p_packetizer->fmt_out.i_extra && !p_dec->fmt_in.i_extra )
1737             {
1738                 es_format_Clean( &p_dec->fmt_in );
1739                 es_format_Copy( &p_dec->fmt_in, &p_packetizer->fmt_out );
1740             }
1741             if( p_packetizer->pf_get_cc )
1742                 DecoderGetCc( p_dec, p_packetizer );
1743
1744             while( p_packetized_block )
1745             {
1746                 block_t *p_next = p_packetized_block->p_next;
1747                 p_packetized_block->p_next = NULL;
1748
1749                 DecoderDecodeVideo( p_dec, p_packetized_block );
1750
1751                 p_packetized_block = p_next;
1752             }
1753         }
1754     }
1755     else if( p_block )
1756     {
1757         DecoderDecodeVideo( p_dec, p_block );
1758     }
1759
1760     if( b_flush && p_owner->p_vout )
1761         vout_Flush( p_owner->p_vout, 1 );
1762 }
1763
1764 /* This function process a audio block
1765  */
1766 static void DecoderProcessAudio( decoder_t *p_dec, block_t *p_block, bool b_flush )
1767 {
1768     decoder_owner_sys_t *p_owner = (decoder_owner_sys_t *)p_dec->p_owner;
1769
1770     if( p_owner->p_packetizer )
1771     {
1772         block_t *p_packetized_block;
1773         decoder_t *p_packetizer = p_owner->p_packetizer;
1774
1775         while( (p_packetized_block =
1776                 p_packetizer->pf_packetize( p_packetizer, p_block ? &p_block : NULL )) )
1777         {
1778             if( p_packetizer->fmt_out.i_extra && !p_dec->fmt_in.i_extra )
1779             {
1780                 es_format_Clean( &p_dec->fmt_in );
1781                 es_format_Copy( &p_dec->fmt_in, &p_packetizer->fmt_out );
1782             }
1783
1784             while( p_packetized_block )
1785             {
1786                 block_t *p_next = p_packetized_block->p_next;
1787                 p_packetized_block->p_next = NULL;
1788
1789                 DecoderDecodeAudio( p_dec, p_packetized_block );
1790
1791                 p_packetized_block = p_next;
1792             }
1793         }
1794     }
1795     else if( p_block )
1796     {
1797         DecoderDecodeAudio( p_dec, p_block );
1798     }
1799
1800     if( b_flush && p_owner->p_aout && p_owner->p_aout_input )
1801         aout_DecFlush( p_owner->p_aout, p_owner->p_aout_input );
1802 }
1803
1804 /* This function process a subtitle block
1805  */
1806 static void DecoderProcessSpu( decoder_t *p_dec, block_t *p_block, bool b_flush )
1807 {
1808     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1809     const bool b_telx = p_dec->fmt_in.i_codec == VLC_FOURCC('t','e','l','x');
1810
1811     input_thread_t *p_input = p_owner->p_input;
1812     vout_thread_t *p_vout;
1813     subpicture_t *p_spu;
1814
1815     while( (p_spu = p_dec->pf_decode_sub( p_dec, p_block ? &p_block : NULL ) ) )
1816     {
1817         vlc_mutex_lock( &p_input->p->counters.counters_lock );
1818         stats_UpdateInteger( p_dec, p_input->p->counters.p_decoded_sub, 1, NULL );
1819         vlc_mutex_unlock( &p_input->p->counters.counters_lock );
1820
1821         p_vout = vlc_object_find( p_dec, VLC_OBJECT_VOUT, FIND_ANYWHERE );
1822         if( p_vout && p_owner->p_spu_vout == p_vout )
1823         {
1824             /* Preroll does not work very well with subtitle */
1825             if( p_spu->i_start > 0 &&
1826                 p_spu->i_start < p_owner->i_preroll_end &&
1827                 ( p_spu->i_stop <= 0 || p_spu->i_stop < p_owner->i_preroll_end ) )
1828             {
1829                 subpicture_Delete( p_spu );
1830             }
1831             else
1832             {
1833                 DecoderPlaySpu( p_dec, p_spu, b_telx );
1834             }
1835         }
1836         else
1837         {
1838             subpicture_Delete( p_spu );
1839         }
1840         if( p_vout )
1841             vlc_object_release( p_vout );
1842     }
1843
1844     if( b_flush && p_owner->p_spu_vout )
1845     {
1846         p_vout = vlc_object_find( p_dec, VLC_OBJECT_VOUT, FIND_ANYWHERE );
1847
1848         if( p_vout && p_owner->p_spu_vout == p_vout )
1849             spu_Control( p_vout->p_spu, SPU_CHANNEL_CLEAR,
1850                          p_owner->i_spu_channel );
1851
1852         if( p_vout )
1853             vlc_object_release( p_vout );
1854     }
1855 }
1856
1857 /**
1858  * Decode a block
1859  *
1860  * \param p_dec the decoder object
1861  * \param p_block the block to decode
1862  * \return VLC_SUCCESS or an error code
1863  */
1864 static int DecoderProcess( decoder_t *p_dec, block_t *p_block )
1865 {
1866     decoder_owner_sys_t *p_owner = (decoder_owner_sys_t *)p_dec->p_owner;
1867     const bool b_flush_request = p_block && (p_block->i_flags & BLOCK_FLAG_CORE_FLUSH);
1868
1869     if( p_block && p_block->i_buffer <= 0 )
1870     {
1871         assert( !b_flush_request );
1872         block_Release( p_block );
1873         return VLC_SUCCESS;
1874     }
1875
1876     int canc = vlc_savecancel();
1877 #ifdef ENABLE_SOUT
1878     if( p_dec->i_object_type == VLC_OBJECT_PACKETIZER )
1879     {
1880         if( p_block )
1881             p_block->i_flags &= ~BLOCK_FLAG_CORE_PRIVATE_MASK;
1882
1883         DecoderProcessSout( p_dec, p_block );
1884     }
1885     else
1886 #endif
1887     {
1888         bool b_flush = false;
1889
1890         if( p_block )
1891         {
1892             const bool b_flushing = p_owner->i_preroll_end == INT64_MAX;
1893             DecoderUpdatePreroll( &p_owner->i_preroll_end, p_block );
1894
1895             b_flush = !b_flushing && b_flush_request;
1896
1897             p_block->i_flags &= ~BLOCK_FLAG_CORE_PRIVATE_MASK;
1898         }
1899
1900         if( p_dec->fmt_in.i_cat == AUDIO_ES )
1901         {
1902             DecoderProcessAudio( p_dec, p_block, b_flush );
1903         }
1904         else if( p_dec->fmt_in.i_cat == VIDEO_ES )
1905         {
1906             DecoderProcessVideo( p_dec, p_block, b_flush );
1907         }
1908         else if( p_dec->fmt_in.i_cat == SPU_ES )
1909         {
1910             DecoderProcessSpu( p_dec, p_block, b_flush );
1911         }
1912         else
1913         {
1914             msg_Err( p_dec, "unknown ES format" );
1915             p_dec->b_error = true;
1916         }
1917     }
1918
1919     /* */
1920     if( b_flush_request )
1921     {
1922         vlc_mutex_lock( &p_owner->lock );
1923         DecoderFlushBuffering( p_dec );
1924         vlc_mutex_unlock( &p_owner->lock );
1925
1926         DecoderSignalFlushed( p_dec );
1927     }
1928     vlc_restorecancel( canc );
1929
1930     return p_dec->b_error ? VLC_EGENERIC : VLC_SUCCESS;
1931 }
1932
1933 /**
1934  * Destroys a decoder object
1935  *
1936  * \param p_dec the decoder object
1937  * \return nothing
1938  */
1939 static void DeleteDecoder( decoder_t * p_dec )
1940 {
1941     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1942
1943     msg_Dbg( p_dec, "killing decoder fourcc `%4.4s', %u PES in FIFO",
1944              (char*)&p_dec->fmt_in.i_codec,
1945              (unsigned)block_FifoCount( p_owner->p_fifo ) );
1946
1947     /* Free all packets still in the decoder fifo. */
1948     block_FifoEmpty( p_owner->p_fifo );
1949     block_FifoRelease( p_owner->p_fifo );
1950
1951     /* */
1952     vlc_mutex_lock( &p_owner->lock );
1953     DecoderFlushBuffering( p_dec );
1954     vlc_mutex_unlock( &p_owner->lock );
1955
1956     /* Cleanup */
1957     if( p_owner->p_aout_input )
1958         aout_DecDelete( p_owner->p_aout, p_owner->p_aout_input );
1959     if( p_owner->p_aout )
1960     {
1961         vlc_object_release( p_owner->p_aout );
1962         p_owner->p_aout = NULL;
1963     }
1964     if( p_owner->p_vout )
1965     {
1966         /* Hack to make sure all the the pictures are freed by the decoder */
1967         vout_FixLeaks( p_owner->p_vout, true );
1968
1969         /* We are about to die. Reattach video output to p_vlc. */
1970         vout_Request( p_dec, p_owner->p_vout, NULL );
1971         var_SetBool( p_owner->p_input, "intf-change-vout", true );
1972     }
1973
1974 #ifdef ENABLE_SOUT
1975     if( p_owner->p_sout_input )
1976     {
1977         sout_InputDelete( p_owner->p_sout_input );
1978         es_format_Clean( &p_owner->sout );
1979     }
1980 #endif
1981
1982     if( p_dec->fmt_in.i_cat == SPU_ES )
1983     {
1984         vout_thread_t *p_vout;
1985
1986         p_vout = vlc_object_find( p_dec, VLC_OBJECT_VOUT, FIND_ANYWHERE );
1987         if( p_vout && p_owner->p_spu_vout == p_vout )
1988         {
1989             spu_Control( p_vout->p_spu, SPU_CHANNEL_CLEAR,
1990                          p_owner->i_spu_channel );
1991             vlc_object_release( p_vout );
1992         }
1993     }
1994
1995     es_format_Clean( &p_dec->fmt_in );
1996     es_format_Clean( &p_dec->fmt_out );
1997
1998     if( p_owner->p_packetizer )
1999     {
2000         module_unneed( p_owner->p_packetizer,
2001                        p_owner->p_packetizer->p_module );
2002         es_format_Clean( &p_owner->p_packetizer->fmt_in );
2003         es_format_Clean( &p_owner->p_packetizer->fmt_out );
2004         vlc_object_detach( p_owner->p_packetizer );
2005         vlc_object_release( p_owner->p_packetizer );
2006     }
2007
2008     vlc_cond_destroy( &p_owner->wait );
2009     vlc_mutex_destroy( &p_owner->lock );
2010
2011     vlc_object_detach( p_dec );
2012
2013     free( p_owner );
2014 }
2015
2016 /*****************************************************************************
2017  * Buffers allocation callbacks for the decoders
2018  *****************************************************************************/
2019 static aout_buffer_t *aout_new_buffer( decoder_t *p_dec, int i_samples )
2020 {
2021     decoder_owner_sys_t *p_owner = p_dec->p_owner;
2022     aout_buffer_t *p_buffer;
2023
2024     if( p_owner->p_aout_input != NULL &&
2025         ( p_dec->fmt_out.audio.i_rate != p_owner->audio.i_rate ||
2026           p_dec->fmt_out.audio.i_original_channels !=
2027               p_owner->audio.i_original_channels ||
2028           p_dec->fmt_out.audio.i_bytes_per_frame !=
2029               p_owner->audio.i_bytes_per_frame ) )
2030     {
2031         aout_input_t *p_aout_input = p_owner->p_aout_input;
2032
2033         /* Parameters changed, restart the aout */
2034         vlc_mutex_lock( &p_owner->lock );
2035
2036         DecoderFlushBuffering( p_dec );
2037
2038         p_owner->p_aout_input = NULL;
2039         aout_DecDelete( p_owner->p_aout, p_aout_input );
2040
2041         vlc_mutex_unlock( &p_owner->lock );
2042     }
2043
2044     if( p_owner->p_aout_input == NULL )
2045     {
2046         const int i_force_dolby = config_GetInt( p_dec, "force-dolby-surround" );
2047         audio_sample_format_t format;
2048         aout_input_t *p_aout_input;
2049         aout_instance_t *p_aout;
2050
2051         p_dec->fmt_out.audio.i_format = p_dec->fmt_out.i_codec;
2052         p_owner->audio = p_dec->fmt_out.audio;
2053
2054         memcpy( &format, &p_owner->audio, sizeof( audio_sample_format_t ) );
2055         if( i_force_dolby &&
2056             (format.i_original_channels&AOUT_CHAN_PHYSMASK) ==
2057                 (AOUT_CHAN_LEFT|AOUT_CHAN_RIGHT) )
2058         {
2059             if( i_force_dolby == 1 )
2060             {
2061                 format.i_original_channels = format.i_original_channels |
2062                                              AOUT_CHAN_DOLBYSTEREO;
2063             }
2064             else /* i_force_dolby == 2 */
2065             {
2066                 format.i_original_channels = format.i_original_channels &
2067                                              ~AOUT_CHAN_DOLBYSTEREO;
2068             }
2069         }
2070
2071         p_aout = p_owner->p_aout;
2072         p_aout_input = aout_DecNew( p_dec, &p_aout,
2073                                     &format, &p_dec->fmt_out.audio_replay_gain );
2074
2075         vlc_mutex_lock( &p_owner->lock );
2076         p_owner->p_aout = p_aout;
2077         p_owner->p_aout_input = p_aout_input;
2078         vlc_mutex_unlock( &p_owner->lock );
2079
2080         if( p_owner->p_aout_input == NULL )
2081         {
2082             msg_Err( p_dec, "failed to create audio output" );
2083             p_dec->b_error = true;
2084             return NULL;
2085         }
2086         p_dec->fmt_out.audio.i_bytes_per_frame =
2087             p_owner->audio.i_bytes_per_frame;
2088     }
2089
2090     p_buffer = aout_DecNewBuffer( p_owner->p_aout_input, i_samples );
2091
2092     return p_buffer;
2093 }
2094
2095 static void aout_del_buffer( decoder_t *p_dec, aout_buffer_t *p_buffer )
2096 {
2097     decoder_owner_sys_t *p_owner = p_dec->p_owner;
2098
2099     aout_DecDeleteBuffer( p_owner->p_aout,
2100                           p_owner->p_aout_input, p_buffer );
2101 }
2102
2103
2104 int vout_CountPictureAvailable( vout_thread_t *p_vout );
2105
2106 static picture_t *vout_new_buffer( decoder_t *p_dec )
2107 {
2108     decoder_owner_sys_t *p_owner = p_dec->p_owner;
2109
2110     if( p_owner->p_vout == NULL ||
2111         p_dec->fmt_out.video.i_width != p_owner->video.i_width ||
2112         p_dec->fmt_out.video.i_height != p_owner->video.i_height ||
2113         p_dec->fmt_out.video.i_chroma != p_owner->video.i_chroma ||
2114         p_dec->fmt_out.video.i_aspect != p_owner->video.i_aspect )
2115     {
2116         vout_thread_t *p_vout;
2117
2118         if( !p_dec->fmt_out.video.i_width ||
2119             !p_dec->fmt_out.video.i_height )
2120         {
2121             /* Can't create a new vout without display size */
2122             return NULL;
2123         }
2124
2125         if( !p_dec->fmt_out.video.i_visible_width ||
2126             !p_dec->fmt_out.video.i_visible_height )
2127         {
2128             if( p_dec->fmt_in.video.i_visible_width &&
2129                 p_dec->fmt_in.video.i_visible_height )
2130             {
2131                 p_dec->fmt_out.video.i_visible_width =
2132                     p_dec->fmt_in.video.i_visible_width;
2133                 p_dec->fmt_out.video.i_visible_height =
2134                     p_dec->fmt_in.video.i_visible_height;
2135             }
2136             else
2137             {
2138                 p_dec->fmt_out.video.i_visible_width =
2139                     p_dec->fmt_out.video.i_width;
2140                 p_dec->fmt_out.video.i_visible_height =
2141                     p_dec->fmt_out.video.i_height;
2142             }
2143         }
2144
2145         if( p_dec->fmt_out.video.i_visible_height == 1088 &&
2146             var_CreateGetBool( p_dec, "hdtv-fix" ) )
2147         {
2148             p_dec->fmt_out.video.i_visible_height = 1080;
2149             p_dec->fmt_out.video.i_sar_num *= 135;
2150             p_dec->fmt_out.video.i_sar_den *= 136;
2151             msg_Warn( p_dec, "Fixing broken HDTV stream (display_height=1088)");
2152         }
2153
2154         if( !p_dec->fmt_out.video.i_sar_num ||
2155             !p_dec->fmt_out.video.i_sar_den )
2156         {
2157             p_dec->fmt_out.video.i_sar_num = p_dec->fmt_out.video.i_aspect *
2158               p_dec->fmt_out.video.i_visible_height;
2159
2160             p_dec->fmt_out.video.i_sar_den = VOUT_ASPECT_FACTOR *
2161               p_dec->fmt_out.video.i_visible_width;
2162         }
2163
2164         vlc_ureduce( &p_dec->fmt_out.video.i_sar_num,
2165                      &p_dec->fmt_out.video.i_sar_den,
2166                      p_dec->fmt_out.video.i_sar_num,
2167                      p_dec->fmt_out.video.i_sar_den, 50000 );
2168
2169         p_dec->fmt_out.video.i_chroma = p_dec->fmt_out.i_codec;
2170         p_owner->video = p_dec->fmt_out.video;
2171
2172         vlc_mutex_lock( &p_owner->lock );
2173
2174         DecoderFlushBuffering( p_dec );
2175
2176         p_vout = p_owner->p_vout;
2177         p_owner->p_vout = NULL;
2178         vlc_mutex_unlock( &p_owner->lock );
2179
2180         p_vout = vout_Request( p_dec, p_vout, &p_dec->fmt_out.video );
2181
2182         vlc_mutex_lock( &p_owner->lock );
2183         p_owner->p_vout = p_vout;
2184         vlc_mutex_unlock( &p_owner->lock );
2185
2186         var_SetBool( p_owner->p_input, "intf-change-vout", true );
2187         if( p_vout == NULL )
2188         {
2189             msg_Err( p_dec, "failed to create video output" );
2190             p_dec->b_error = true;
2191             return NULL;
2192         }
2193
2194         if( p_owner->video.i_rmask )
2195             p_owner->p_vout->render.i_rmask = p_owner->video.i_rmask;
2196         if( p_owner->video.i_gmask )
2197             p_owner->p_vout->render.i_gmask = p_owner->video.i_gmask;
2198         if( p_owner->video.i_bmask )
2199             p_owner->p_vout->render.i_bmask = p_owner->video.i_bmask;
2200     }
2201
2202     /* Get a new picture
2203      */
2204     for( ;; )
2205     {
2206         picture_t *p_picture;
2207
2208         if( p_dec->b_die || p_dec->b_error )
2209             return NULL;
2210
2211         /* The video filter chain required that there is always 1 free buffer
2212          * that it will use as temporary one. It will release the temporary
2213          * buffer once its work is done, so this check is safe even if we don't
2214          * lock around both count() and create().
2215          */
2216         if( vout_CountPictureAvailable( p_owner->p_vout ) >= 2 )
2217         {
2218             p_picture = vout_CreatePicture( p_owner->p_vout, 0, 0, 0 );
2219             if( p_picture )
2220                 return p_picture;
2221         }
2222
2223         if( DecoderIsFlushing( p_dec ) )
2224             return NULL;
2225
2226         /* */
2227         DecoderSignalBuffering( p_dec, true );
2228
2229         /* Check the decoder doesn't leak pictures */
2230         vout_FixLeaks( p_owner->p_vout, false );
2231
2232         /* FIXME add a vout_WaitPictureAvailable (timedwait) */
2233         msleep( VOUT_OUTMEM_SLEEP );
2234     }
2235 }
2236
2237 static void vout_del_buffer( decoder_t *p_dec, picture_t *p_pic )
2238 {
2239     vout_DropPicture( p_dec->p_owner->p_vout, p_pic );
2240 }
2241
2242 static void vout_link_picture( decoder_t *p_dec, picture_t *p_pic )
2243 {
2244     vout_LinkPicture( p_dec->p_owner->p_vout, p_pic );
2245 }
2246
2247 static void vout_unlink_picture( decoder_t *p_dec, picture_t *p_pic )
2248 {
2249     vout_UnlinkPicture( p_dec->p_owner->p_vout, p_pic );
2250 }
2251
2252 static subpicture_t *spu_new_buffer( decoder_t *p_dec )
2253 {
2254     decoder_owner_sys_t *p_owner = p_dec->p_owner;
2255     vout_thread_t *p_vout = NULL;
2256     subpicture_t *p_subpic;
2257     int i_attempts = 30;
2258
2259     while( i_attempts-- )
2260     {
2261         if( p_dec->b_die || p_dec->b_error )
2262             break;
2263
2264         p_vout = vlc_object_find( p_dec, VLC_OBJECT_VOUT, FIND_ANYWHERE );
2265         if( p_vout )
2266             break;
2267
2268         msleep( DECODER_SPU_VOUT_WAIT_DURATION );
2269     }
2270
2271     if( !p_vout )
2272     {
2273         msg_Warn( p_dec, "no vout found, dropping subpicture" );
2274         return NULL;
2275     }
2276
2277     if( p_owner->p_spu_vout != p_vout )
2278     {
2279         vlc_mutex_lock( &p_owner->lock );
2280
2281         DecoderFlushBuffering( p_dec );
2282
2283         vlc_mutex_unlock( &p_owner->lock );
2284
2285         spu_Control( p_vout->p_spu, SPU_CHANNEL_REGISTER,
2286                      &p_owner->i_spu_channel );
2287         p_owner->i_spu_order = 0;
2288         p_owner->p_spu_vout = p_vout;
2289     }
2290
2291     p_subpic = subpicture_New();
2292     if( p_subpic )
2293     {
2294         p_subpic->i_channel = p_owner->i_spu_channel;
2295         p_subpic->i_order = p_owner->i_spu_order++;
2296         p_subpic->b_subtitle = true;
2297     }
2298
2299     vlc_object_release( p_vout );
2300
2301     return p_subpic;
2302 }
2303
2304 static void spu_del_buffer( decoder_t *p_dec, subpicture_t *p_subpic )
2305 {
2306     decoder_owner_sys_t *p_owner = p_dec->p_owner;
2307     vout_thread_t *p_vout = NULL;
2308
2309     p_vout = vlc_object_find( p_dec, VLC_OBJECT_VOUT, FIND_ANYWHERE );
2310     if( !p_vout || p_owner->p_spu_vout != p_vout )
2311     {
2312         if( p_vout )
2313             vlc_object_release( p_vout );
2314         msg_Warn( p_dec, "no vout found, leaking subpicture" );
2315         return;
2316     }
2317
2318     subpicture_Delete( p_subpic );
2319
2320     vlc_object_release( p_vout );
2321 }
2322