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