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