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