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