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