Prepare for safe (sout)/vout/aout recycling.
[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 #include <vlc_meta.h>
43
44 #include <vlc_interface.h>
45 #include "audio_output/aout_internal.h"
46 #include "stream_output/stream_output.h"
47 #include "input_internal.h"
48 #include "clock.h"
49 #include "decoder.h"
50 #include "event.h"
51 #include "ressource.h"
52
53 #include "../video_output/vout_control.h"
54
55 static decoder_t *CreateDecoder( input_thread_t *, es_format_t *, int, sout_instance_t *p_sout );
56 static void       DeleteDecoder( decoder_t * );
57
58 static void      *DecoderThread( vlc_object_t * );
59 static void       DecoderProcess( decoder_t *, block_t * );
60 static void       DecoderError( decoder_t *p_dec, block_t *p_block );
61 static void       DecoderOutputChangePause( decoder_t *, bool b_paused, mtime_t i_date );
62 static void       DecoderFlush( decoder_t * );
63 static void       DecoderSignalBuffering( decoder_t *, bool );
64 static void       DecoderFlushBuffering( decoder_t * );
65
66 static void       DecoderUnsupportedCodec( decoder_t *, vlc_fourcc_t );
67
68 /* Buffers allocation callbacks for the decoders */
69 static aout_buffer_t *aout_new_buffer( decoder_t *, int );
70 static void aout_del_buffer( decoder_t *, aout_buffer_t * );
71
72 static picture_t *vout_new_buffer( decoder_t * );
73 static void vout_del_buffer( decoder_t *, picture_t * );
74 static void vout_link_picture( decoder_t *, picture_t * );
75 static void vout_unlink_picture( decoder_t *, picture_t * );
76
77 static subpicture_t *spu_new_buffer( decoder_t * );
78 static void spu_del_buffer( decoder_t *, subpicture_t * );
79
80 static es_format_t null_es_format;
81
82 struct decoder_owner_sys_t
83 {
84     int64_t         i_preroll_end;
85
86     input_thread_t  *p_input;
87     input_clock_t   *p_clock;
88     int             i_last_rate;
89
90     vout_thread_t   *p_spu_vout;
91     int              i_spu_channel;
92     int64_t          i_spu_order;
93
94     sout_instance_t         *p_sout;
95     sout_packetizer_input_t *p_sout_input;
96
97     /* Some decoders require already packetized data (ie. not truncated) */
98     decoder_t *p_packetizer;
99
100     /* Current format in use by the output */
101     video_format_t video;
102     audio_format_t audio;
103     es_format_t    sout;
104
105     /* */
106     bool           b_fmt_description;
107     es_format_t    fmt_description;
108     vlc_meta_t     *p_description;
109
110     /* fifo */
111     block_fifo_t *p_fifo;
112
113     /* Lock for communication with decoder thread */
114     vlc_mutex_t lock;
115     vlc_cond_t  wait;
116
117     /* -- These variables need locking on write(only) -- */
118     aout_instance_t *p_aout;
119     aout_input_t    *p_aout_input;
120
121     vout_thread_t   *p_vout;
122
123     /* -- Theses variables need locking on read *and* write -- */
124     /* */
125     /* Pause */
126     bool b_paused;
127     struct
128     {
129         mtime_t i_date;
130         int     i_ignore;
131     } pause;
132
133     /* Buffering */
134     bool b_buffering;
135     struct
136     {
137         bool b_first;
138         bool b_full;
139         int  i_count;
140
141         picture_t     *p_picture;
142         picture_t     **pp_picture_next;
143
144         subpicture_t  *p_subpic;
145         subpicture_t  **pp_subpic_next;
146
147         aout_buffer_t *p_audio;
148         aout_buffer_t **pp_audio_next;
149
150         block_t       *p_block;
151         block_t       **pp_block_next;
152     } buffer;
153
154     /* Flushing */
155     bool b_flushing;
156
157     /* CC */
158     struct
159     {
160         bool b_supported;
161         bool pb_present[4];
162         decoder_t *pp_decoder[4];
163     } cc;
164
165     /* Delay */
166     mtime_t i_ts_delay;
167 };
168
169 #define DECODER_MAX_BUFFERING_COUNT (4)
170 #define DECODER_MAX_BUFFERING_AUDIO_DURATION (AOUT_MAX_PREPARE_TIME)
171 #define DECODER_MAX_BUFFERING_VIDEO_DURATION (1*CLOCK_FREQ)
172
173 /* Pictures which are DECODER_BOGUS_VIDEO_DELAY or more in advance probably have
174  * a bogus PTS and won't be displayed */
175 #define DECODER_BOGUS_VIDEO_DELAY                ((mtime_t)(DEFAULT_PTS_DELAY * 30))
176
177 /* */
178 #define DECODER_SPU_VOUT_WAIT_DURATION ((int)(0.200*CLOCK_FREQ))
179
180
181 /*****************************************************************************
182  * Public functions
183  *****************************************************************************/
184 picture_t *decoder_NewPicture( decoder_t *p_decoder )
185 {
186     picture_t *p_picture = p_decoder->pf_vout_buffer_new( p_decoder );
187     if( !p_picture )
188         msg_Warn( p_decoder, "can't get output picture" );
189     return p_picture;
190 }
191 void decoder_DeletePicture( decoder_t *p_decoder, picture_t *p_picture )
192 {
193     p_decoder->pf_vout_buffer_del( p_decoder, p_picture );
194 }
195 void decoder_LinkPicture( decoder_t *p_decoder, picture_t *p_picture )
196 {
197     p_decoder->pf_picture_link( p_decoder, p_picture );
198 }
199 void decoder_UnlinkPicture( decoder_t *p_decoder, picture_t *p_picture )
200 {
201     p_decoder->pf_picture_unlink( p_decoder, p_picture );
202 }
203
204 aout_buffer_t *decoder_NewAudioBuffer( decoder_t *p_decoder, int i_size )
205 {
206     if( !p_decoder->pf_aout_buffer_new )
207         return NULL;
208     return p_decoder->pf_aout_buffer_new( p_decoder, i_size );
209 }
210 void decoder_DeleteAudioBuffer( decoder_t *p_decoder, aout_buffer_t *p_buffer )
211 {
212     p_decoder->pf_aout_buffer_del( p_decoder, p_buffer );
213 }
214
215 subpicture_t *decoder_NewSubpicture( decoder_t *p_decoder )
216 {
217     subpicture_t *p_subpicture = p_decoder->pf_spu_buffer_new( p_decoder );
218     if( !p_subpicture )
219         msg_Warn( p_decoder, "can't get output subpicture" );
220     return p_subpicture;
221 }
222 void decoder_DeleteSubpicture( decoder_t *p_decoder, subpicture_t *p_subpicture )
223 {
224     p_decoder->pf_spu_buffer_del( p_decoder, p_subpicture );
225 }
226
227 /* decoder_GetInputAttachments:
228  */
229 int decoder_GetInputAttachments( decoder_t *p_dec,
230                                  input_attachment_t ***ppp_attachment,
231                                  int *pi_attachment )
232 {
233     if( !p_dec->pf_get_attachments )
234         return VLC_EGENERIC;
235
236     return p_dec->pf_get_attachments( p_dec, ppp_attachment, pi_attachment );
237 }
238 /* decoder_GetDisplayDate:
239  */
240 mtime_t decoder_GetDisplayDate( decoder_t *p_dec, mtime_t i_ts )
241 {
242     if( !p_dec->pf_get_display_date )
243         return 0;
244
245     return p_dec->pf_get_display_date( p_dec, i_ts );
246 }
247 /* decoder_GetDisplayRate:
248  */
249 int decoder_GetDisplayRate( decoder_t *p_dec )
250 {
251     if( !p_dec->pf_get_display_rate )
252         return INPUT_RATE_DEFAULT;
253
254     return p_dec->pf_get_display_rate( p_dec );
255 }
256
257 /**
258  * Spawns a new decoder thread
259  *
260  * \param p_input the input thread
261  * \param p_es the es descriptor
262  * \return the spawned decoder object
263  */
264 decoder_t *input_DecoderNew( input_thread_t *p_input,
265                              es_format_t *fmt, input_clock_t *p_clock, sout_instance_t *p_sout  )
266 {
267     decoder_t *p_dec = NULL;
268     int i_priority;
269
270 #ifdef ENABLE_SOUT
271     /* If we are in sout mode, search for packetizer module */
272     if( p_sout )
273     {
274         /* Create the decoder configuration structure */
275         p_dec = CreateDecoder( p_input, fmt, VLC_OBJECT_PACKETIZER, p_sout );
276         if( p_dec == NULL )
277         {
278             msg_Err( p_input, "could not create packetizer" );
279             intf_UserFatal( p_input, false, _("Streaming / Transcoding failed"),
280                             _("VLC could not open the packetizer module.") );
281             return NULL;
282         }
283     }
284     else
285 #endif
286     {
287         /* Create the decoder configuration structure */
288         p_dec = CreateDecoder( p_input, fmt, VLC_OBJECT_DECODER, p_sout );
289         if( p_dec == NULL )
290         {
291             msg_Err( p_input, "could not create decoder" );
292             intf_UserFatal( p_input, false, _("Streaming / Transcoding failed"),
293                             _("VLC could not open the decoder module.") );
294             return NULL;
295         }
296     }
297
298     if( !p_dec->p_module )
299     {
300         DecoderUnsupportedCodec( p_dec, fmt->i_codec );
301
302         DeleteDecoder( p_dec );
303         vlc_object_release( p_dec );
304         return NULL;
305     }
306
307     p_dec->p_owner->p_clock = p_clock;
308
309     if( fmt->i_cat == AUDIO_ES )
310         i_priority = VLC_THREAD_PRIORITY_AUDIO;
311     else
312         i_priority = VLC_THREAD_PRIORITY_VIDEO;
313
314     /* Spawn the decoder thread */
315     if( vlc_thread_create( p_dec, "decoder", DecoderThread,
316                            i_priority, false ) )
317     {
318         msg_Err( p_dec, "cannot spawn decoder thread" );
319         module_unneed( p_dec, p_dec->p_module );
320         DeleteDecoder( p_dec );
321         vlc_object_release( p_dec );
322         return NULL;
323     }
324
325     return p_dec;
326 }
327
328 /**
329  * Kills a decoder thread and waits until it's finished
330  *
331  * \param p_input the input thread
332  * \param p_es the es descriptor
333  * \return nothing
334  */
335 void input_DecoderDelete( decoder_t *p_dec )
336 {
337     decoder_owner_sys_t *p_owner = p_dec->p_owner;
338
339     vlc_object_kill( p_dec );
340
341     /* Make sure we aren't paused/buffering/waiting anymore */
342     vlc_mutex_lock( &p_owner->lock );
343     p_owner->b_paused = false;
344     p_owner->b_buffering = false;
345     p_owner->b_flushing = true;
346     vlc_cond_signal( &p_owner->wait );
347     vlc_mutex_unlock( &p_owner->lock );
348
349     vlc_thread_join( p_dec );
350     module_unneed( p_dec, p_dec->p_module );
351
352     /* */
353     if( p_dec->p_owner->cc.b_supported )
354     {
355         int i;
356         for( i = 0; i < 4; i++ )
357             input_DecoderSetCcState( p_dec, false, i );
358     }
359
360     /* Delete decoder configuration */
361     DeleteDecoder( p_dec );
362
363     /* Delete the decoder */
364     vlc_object_release( p_dec );
365 }
366
367 /**
368  * Put a block_t in the decoder's fifo.
369  * Thread-safe w.r.t. the decoder. May be a cancellation point.
370  *
371  * \param p_dec the decoder object
372  * \param p_block the data block
373  */
374 void input_DecoderDecode( decoder_t *p_dec, block_t *p_block )
375 {
376     decoder_owner_sys_t *p_owner = p_dec->p_owner;
377
378     if( p_owner->p_input->p->b_out_pace_control )
379     {
380         /* The fifo is not consummed when buffering and so will
381          * deadlock vlc.
382          * There is no need to lock as b_buffering is never modify
383          * inside decoder thread. */
384         if( !p_owner->b_buffering )
385             block_FifoPace( p_owner->p_fifo, 10, SIZE_MAX );
386     }
387     else if( block_FifoSize( p_owner->p_fifo ) > 50000000 /* 50 MB */ )
388     {
389         /* FIXME: ideally we would check the time amount of data
390          * in the FIFO instead of its size. */
391         msg_Warn( p_dec, "decoder/packetizer fifo full (data not "
392                   "consumed quickly enough), resetting fifo!" );
393         block_FifoEmpty( p_owner->p_fifo );
394     }
395
396     block_FifoPut( p_owner->p_fifo, p_block );
397 }
398
399 bool input_DecoderIsEmpty( decoder_t * p_dec )
400 {
401     assert( !p_dec->p_owner->b_buffering );
402
403     /* FIXME that's not really true */
404     return block_FifoCount( p_dec->p_owner->p_fifo ) <= 0;
405 }
406
407 void input_DecoderIsCcPresent( decoder_t *p_dec, bool pb_present[4] )
408 {
409     decoder_owner_sys_t *p_owner = p_dec->p_owner;
410     int i;
411
412     vlc_mutex_lock( &p_owner->lock );
413     for( i = 0; i < 4; i++ )
414         pb_present[i] =  p_owner->cc.pb_present[i];
415     vlc_mutex_unlock( &p_owner->lock );
416 }
417 int input_DecoderSetCcState( decoder_t *p_dec, bool b_decode, int i_channel )
418 {
419     decoder_owner_sys_t *p_owner = p_dec->p_owner;
420
421     //msg_Warn( p_dec, "input_DecoderSetCcState: %d @%d", b_decode, i_channel );
422
423     if( i_channel < 0 || i_channel >= 4 || !p_owner->cc.pb_present[i_channel] )
424         return VLC_EGENERIC;
425
426     if( b_decode )
427     {
428         static const vlc_fourcc_t fcc[4] = {
429             VLC_FOURCC('c', 'c', '1', ' '),
430             VLC_FOURCC('c', 'c', '2', ' '),
431             VLC_FOURCC('c', 'c', '3', ' '),
432             VLC_FOURCC('c', 'c', '4', ' '),
433         };
434         decoder_t *p_cc;
435         es_format_t fmt;
436
437         es_format_Init( &fmt, SPU_ES, fcc[i_channel] );
438         p_cc = CreateDecoder( p_owner->p_input, &fmt, VLC_OBJECT_DECODER, p_owner->p_sout );
439         if( !p_cc )
440         {
441             msg_Err( p_dec, "could not create decoder" );
442             intf_UserFatal( p_dec, false, _("Streaming / Transcoding failed"),
443                             _("VLC could not open the decoder module.") );
444             return VLC_EGENERIC;
445         }
446         else if( !p_cc->p_module )
447         {
448             DecoderUnsupportedCodec( p_dec, fcc[i_channel] );
449             DeleteDecoder( p_cc );
450             vlc_object_release( p_cc );
451             return VLC_EGENERIC;
452         }
453         p_cc->p_owner->p_clock = p_owner->p_clock;
454
455         vlc_mutex_lock( &p_owner->lock );
456         p_owner->cc.pp_decoder[i_channel] = p_cc;
457         vlc_mutex_unlock( &p_owner->lock );
458     }
459     else
460     {
461         decoder_t *p_cc;
462
463         vlc_mutex_lock( &p_owner->lock );
464         p_cc = p_owner->cc.pp_decoder[i_channel];
465         p_owner->cc.pp_decoder[i_channel] = NULL;
466         vlc_mutex_unlock( &p_owner->lock );
467
468         if( p_cc )
469         {
470             vlc_object_kill( p_cc );
471             module_unneed( p_cc, p_cc->p_module );
472             DeleteDecoder( p_cc );
473             vlc_object_release( p_cc );
474         }
475     }
476     return VLC_SUCCESS;
477 }
478 int input_DecoderGetCcState( decoder_t *p_dec, bool *pb_decode, int i_channel )
479 {
480     decoder_owner_sys_t *p_owner = p_dec->p_owner;
481
482     *pb_decode = false;
483     if( i_channel < 0 || i_channel >= 4 || !p_owner->cc.pb_present[i_channel] )
484         return VLC_EGENERIC;
485
486     vlc_mutex_lock( &p_owner->lock );
487     *pb_decode = p_owner->cc.pp_decoder[i_channel] != NULL;
488     vlc_mutex_unlock( &p_owner->lock );
489     return VLC_EGENERIC;
490 }
491
492 void input_DecoderChangePause( decoder_t *p_dec, bool b_paused, mtime_t i_date )
493 {
494     decoder_owner_sys_t *p_owner = p_dec->p_owner;
495
496     vlc_mutex_lock( &p_owner->lock );
497
498     assert( !p_owner->b_paused || !b_paused );
499
500     p_owner->b_paused = b_paused;
501     p_owner->pause.i_date = i_date;
502     p_owner->pause.i_ignore = 0;
503     vlc_cond_signal( &p_owner->wait );
504
505     DecoderOutputChangePause( p_dec, b_paused, i_date );
506
507     vlc_mutex_unlock( &p_owner->lock );
508 }
509
510 void input_DecoderChangeDelay( decoder_t *p_dec, mtime_t i_delay )
511 {
512     decoder_owner_sys_t *p_owner = p_dec->p_owner;
513
514     vlc_mutex_lock( &p_owner->lock );
515     p_owner->i_ts_delay = i_delay;
516     vlc_mutex_unlock( &p_owner->lock );
517 }
518
519 void input_DecoderStartBuffering( decoder_t *p_dec )
520 {
521     decoder_owner_sys_t *p_owner = p_dec->p_owner;
522
523     vlc_mutex_lock( &p_owner->lock );
524
525     DecoderFlush( p_dec );
526
527     p_owner->buffer.b_first = true;
528     p_owner->buffer.b_full = false;
529     p_owner->buffer.i_count = 0;
530
531     assert( !p_owner->buffer.p_picture && !p_owner->buffer.p_subpic &&
532             !p_owner->buffer.p_audio && !p_owner->buffer.p_block );
533
534     p_owner->buffer.p_picture = NULL;
535     p_owner->buffer.pp_picture_next = &p_owner->buffer.p_picture;
536
537     p_owner->buffer.p_subpic = NULL;
538     p_owner->buffer.pp_subpic_next = &p_owner->buffer.p_subpic;
539
540     p_owner->buffer.p_audio = NULL;
541     p_owner->buffer.pp_audio_next = &p_owner->buffer.p_audio;
542
543     p_owner->buffer.p_block = NULL;
544     p_owner->buffer.pp_block_next = &p_owner->buffer.p_block;
545
546
547     p_owner->b_buffering = true;
548
549     vlc_cond_signal( &p_owner->wait );
550
551     vlc_mutex_unlock( &p_owner->lock );
552 }
553
554 void input_DecoderStopBuffering( decoder_t *p_dec )
555 {
556     decoder_owner_sys_t *p_owner = p_dec->p_owner;
557
558     vlc_mutex_lock( &p_owner->lock );
559
560     p_owner->b_buffering = false;
561
562     vlc_cond_signal( &p_owner->wait );
563
564     vlc_mutex_unlock( &p_owner->lock );
565 }
566
567 void input_DecoderWaitBuffering( decoder_t *p_dec )
568 {
569     decoder_owner_sys_t *p_owner = p_dec->p_owner;
570
571     vlc_mutex_lock( &p_owner->lock );
572
573     while( vlc_object_alive( p_dec ) && p_owner->b_buffering && !p_owner->buffer.b_full )
574     {
575         block_FifoWake( p_owner->p_fifo );
576         vlc_cond_wait( &p_owner->wait, &p_owner->lock );
577     }
578
579     vlc_mutex_unlock( &p_owner->lock );
580 }
581
582 void input_DecoderFrameNext( decoder_t *p_dec, mtime_t *pi_duration )
583 {
584     decoder_owner_sys_t *p_owner = p_dec->p_owner;
585
586     *pi_duration = 0;
587
588     vlc_mutex_lock( &p_owner->lock );
589     if( p_dec->fmt_in.i_cat == VIDEO_ES )
590     {
591         if( p_owner->b_paused && p_owner->p_vout )
592         {
593             vout_NextPicture( p_owner->p_vout, pi_duration );
594             p_owner->pause.i_ignore++;
595             vlc_cond_signal( &p_owner->wait );
596         }
597     }
598     else
599     {
600         /* TODO subtitle should not be flushed */
601         DecoderFlush( p_dec );
602     }
603     vlc_mutex_unlock( &p_owner->lock );
604 }
605
606 bool input_DecoderHasFormatChanged( decoder_t *p_dec, es_format_t *p_fmt, vlc_meta_t **pp_meta )
607 {
608     decoder_owner_sys_t *p_owner = p_dec->p_owner;
609     bool b_changed;
610
611     vlc_mutex_lock( &p_owner->lock );
612     b_changed = p_owner->b_fmt_description;
613     if( b_changed )
614     {
615         if( p_fmt )
616             es_format_Copy( p_fmt, &p_owner->fmt_description );
617
618         if( pp_meta )
619         {
620             *pp_meta = NULL;
621             if( p_owner->p_description )
622             {
623                 *pp_meta = vlc_meta_New();
624                 if( *pp_meta )
625                     vlc_meta_Merge( *pp_meta, p_owner->p_description );
626             }
627         }
628         p_owner->b_fmt_description = false;
629     }
630     vlc_mutex_unlock( &p_owner->lock );
631     return b_changed;
632 }
633
634 /*****************************************************************************
635  * Internal functions
636  *****************************************************************************/
637 static int DecoderGetInputAttachments( decoder_t *p_dec,
638                                        input_attachment_t ***ppp_attachment,
639                                        int *pi_attachment )
640 {
641     return input_Control( p_dec->p_owner->p_input, INPUT_GET_ATTACHMENTS,
642                           ppp_attachment, pi_attachment );
643 }
644 static mtime_t DecoderGetDisplayDate( decoder_t *p_dec, mtime_t i_ts )
645 {
646     decoder_owner_sys_t *p_owner = p_dec->p_owner;
647
648     vlc_mutex_lock( &p_owner->lock );
649     if( p_owner->b_buffering || p_owner->b_paused )
650         i_ts = 0;
651     vlc_mutex_unlock( &p_owner->lock );
652
653     if( !p_owner->p_clock || !i_ts )
654         return i_ts;
655
656     return input_clock_GetTS( p_owner->p_clock, NULL, p_owner->p_input->i_pts_delay, i_ts );
657 }
658 static int DecoderGetDisplayRate( decoder_t *p_dec )
659 {
660     decoder_owner_sys_t *p_owner = p_dec->p_owner;
661
662     if( !p_owner->p_clock )
663         return INPUT_RATE_DEFAULT;
664     return input_clock_GetRate( p_owner->p_clock );
665 }
666
667 /* */
668 static void DecoderUnsupportedCodec( decoder_t *p_dec, vlc_fourcc_t codec )
669 {
670     msg_Err( p_dec, "no suitable decoder module for fourcc `%4.4s'.\n"
671              "VLC probably does not support this sound or video format.",
672              (char*)&codec );
673     intf_UserFatal( p_dec, false, _("No suitable decoder module"), 
674                     _("VLC does not support the audio or video format \"%4.4s\". "
675                       "Unfortunately there is no way for you to fix this."), (char*)&codec );
676 }
677
678
679 /**
680  * Create a decoder object
681  *
682  * \param p_input the input thread
683  * \param p_es the es descriptor
684  * \param i_object_type Object type as define in include/vlc_objects.h
685  * \return the decoder object
686  */
687 static decoder_t * CreateDecoder( input_thread_t *p_input,
688                                   es_format_t *fmt, int i_object_type, sout_instance_t *p_sout )
689 {
690     decoder_t *p_dec;
691     decoder_owner_sys_t *p_owner;
692     int i;
693
694     p_dec = vlc_object_create( p_input, i_object_type );
695     if( p_dec == NULL )
696         return NULL;
697
698     p_dec->pf_decode_audio = NULL;
699     p_dec->pf_decode_video = NULL;
700     p_dec->pf_decode_sub = NULL;
701     p_dec->pf_get_cc = NULL;
702     p_dec->pf_packetize = NULL;
703
704     /* Initialize the decoder */
705     p_dec->p_module = NULL;
706
707     memset( &null_es_format, 0, sizeof(es_format_t) );
708     es_format_Copy( &p_dec->fmt_in, fmt );
709     es_format_Copy( &p_dec->fmt_out, &null_es_format );
710
711     p_dec->p_description = NULL;
712
713     /* Allocate our private structure for the decoder */
714     p_dec->p_owner = p_owner = malloc( sizeof( decoder_owner_sys_t ) );
715     if( p_dec->p_owner == NULL )
716     {
717         vlc_object_release( p_dec );
718         return NULL;
719     }
720     p_dec->p_owner->i_preroll_end = -1;
721     p_dec->p_owner->i_last_rate = INPUT_RATE_DEFAULT;
722     p_dec->p_owner->p_input = p_input;
723     p_dec->p_owner->p_aout = NULL;
724     p_dec->p_owner->p_aout_input = NULL;
725     p_dec->p_owner->p_vout = NULL;
726     p_dec->p_owner->p_spu_vout = NULL;
727     p_dec->p_owner->i_spu_channel = 0;
728     p_dec->p_owner->i_spu_order = 0;
729     p_dec->p_owner->p_sout = p_sout;
730     p_dec->p_owner->p_sout_input = NULL;
731     p_dec->p_owner->p_packetizer = NULL;
732
733     /* decoder fifo */
734     if( ( p_dec->p_owner->p_fifo = block_FifoNew() ) == NULL )
735     {
736         free( p_dec->p_owner );
737         vlc_object_release( p_dec );
738         return NULL;
739     }
740
741     /* Set buffers allocation callbacks for the decoders */
742     p_dec->pf_aout_buffer_new = aout_new_buffer;
743     p_dec->pf_aout_buffer_del = aout_del_buffer;
744     p_dec->pf_vout_buffer_new = vout_new_buffer;
745     p_dec->pf_vout_buffer_del = vout_del_buffer;
746     p_dec->pf_picture_link    = vout_link_picture;
747     p_dec->pf_picture_unlink  = vout_unlink_picture;
748     p_dec->pf_spu_buffer_new  = spu_new_buffer;
749     p_dec->pf_spu_buffer_del  = spu_del_buffer;
750     /* */
751     p_dec->pf_get_attachments  = DecoderGetInputAttachments;
752     p_dec->pf_get_display_date = DecoderGetDisplayDate;
753     p_dec->pf_get_display_rate = DecoderGetDisplayRate;
754
755     vlc_object_attach( p_dec, p_input );
756
757     /* Find a suitable decoder/packetizer module */
758     if( i_object_type == VLC_OBJECT_DECODER )
759         p_dec->p_module = module_need( p_dec, "decoder", "$codec", false );
760     else
761         p_dec->p_module = module_need( p_dec, "packetizer", "$packetizer", false );
762
763     /* Check if decoder requires already packetized data */
764     if( i_object_type == VLC_OBJECT_DECODER &&
765         p_dec->b_need_packetized && !p_dec->fmt_in.b_packetized )
766     {
767         p_dec->p_owner->p_packetizer =
768             vlc_object_create( p_input, VLC_OBJECT_PACKETIZER );
769         if( p_dec->p_owner->p_packetizer )
770         {
771             es_format_Copy( &p_dec->p_owner->p_packetizer->fmt_in,
772                             &p_dec->fmt_in );
773
774             es_format_Copy( &p_dec->p_owner->p_packetizer->fmt_out,
775                             &null_es_format );
776
777             vlc_object_attach( p_dec->p_owner->p_packetizer, p_input );
778
779             p_dec->p_owner->p_packetizer->p_module =
780                 module_need( p_dec->p_owner->p_packetizer,
781                              "packetizer", "$packetizer", false );
782
783             if( !p_dec->p_owner->p_packetizer->p_module )
784             {
785                 es_format_Clean( &p_dec->p_owner->p_packetizer->fmt_in );
786                 vlc_object_detach( p_dec->p_owner->p_packetizer );
787                 vlc_object_release( p_dec->p_owner->p_packetizer );
788             }
789         }
790     }
791
792     /* Copy ourself the input replay gain */
793     if( fmt->i_cat == AUDIO_ES )
794     {
795         for( i = 0; i < AUDIO_REPLAY_GAIN_MAX; i++ )
796         {
797             if( !p_dec->fmt_out.audio_replay_gain.pb_peak[i] )
798             {
799                 p_dec->fmt_out.audio_replay_gain.pb_peak[i] = fmt->audio_replay_gain.pb_peak[i];
800                 p_dec->fmt_out.audio_replay_gain.pf_peak[i] = fmt->audio_replay_gain.pf_peak[i];
801             }
802             if( !p_dec->fmt_out.audio_replay_gain.pb_gain[i] )
803             {
804                 p_dec->fmt_out.audio_replay_gain.pb_gain[i] = fmt->audio_replay_gain.pb_gain[i];
805                 p_dec->fmt_out.audio_replay_gain.pf_gain[i] = fmt->audio_replay_gain.pf_gain[i];
806             }
807         }
808     }
809
810     /* */
811     vlc_mutex_init( &p_owner->lock );
812     vlc_cond_init( &p_owner->wait );
813
814     p_owner->b_fmt_description = false;
815     es_format_Init( &p_owner->fmt_description, UNKNOWN_ES, 0 );
816     p_owner->p_description = NULL;
817
818     p_owner->b_paused = false;
819     p_owner->pause.i_date = 0;
820     p_owner->pause.i_ignore = 0;
821
822     p_owner->b_buffering = false;
823     p_owner->buffer.b_first = true;
824     p_owner->buffer.b_full = false;
825     p_owner->buffer.i_count = 0;
826     p_owner->buffer.p_picture = NULL;
827     p_owner->buffer.p_subpic = NULL;
828     p_owner->buffer.p_audio = NULL;
829     p_owner->buffer.p_block = NULL;
830
831     p_owner->b_flushing = false;
832
833     /* */
834     p_owner->cc.b_supported = false;
835     if( i_object_type == VLC_OBJECT_DECODER )
836     {
837         if( p_owner->p_packetizer && p_owner->p_packetizer->pf_get_cc )
838             p_owner->cc.b_supported = true;
839         if( p_dec->pf_get_cc )
840             p_owner->cc.b_supported = true;
841     }
842
843     for( i = 0; i < 4; i++ )
844     {
845         p_owner->cc.pb_present[i] = false;
846         p_owner->cc.pp_decoder[i] = NULL;
847     }
848     p_owner->i_ts_delay = 0;
849     return p_dec;
850 }
851
852 /**
853  * The decoding main loop
854  *
855  * \param p_dec the decoder
856  */
857 static void *DecoderThread( vlc_object_t *p_this )
858 {
859     decoder_t *p_dec = (decoder_t *)p_this;
860     decoder_owner_sys_t *p_owner = p_dec->p_owner;
861
862     /* The decoder's main loop */
863     for( ;; )
864     {
865         block_t *p_block = block_FifoGet( p_owner->p_fifo );
866
867         /* Make sure there is no cancellation point other than this one^^.
868          * If you need one, be sure to push cleanup of p_block. */
869         DecoderSignalBuffering( p_dec, p_block == NULL );
870
871         if( p_block )
872         {
873             int canc = vlc_savecancel();
874
875             if( p_dec->b_error )
876                 DecoderError( p_dec, p_block );
877             else
878                 DecoderProcess( p_dec, p_block );
879
880             vlc_restorecancel( canc );
881         }
882         /* Ensure fast cancellation in case the fifo is not empty */
883         vlc_testcancel();
884     }
885     return NULL;
886 }
887
888 static void DecoderFlush( decoder_t *p_dec )
889 {
890     decoder_owner_sys_t *p_owner = p_dec->p_owner;
891     block_t *p_null;
892
893     vlc_assert_locked( &p_owner->lock );
894
895     /* Empty the fifo */
896     block_FifoEmpty( p_owner->p_fifo );
897
898     /* Monitor for flush end */
899     p_owner->b_flushing = true;
900     vlc_cond_signal( &p_owner->wait );
901
902     /* Send a special block */
903     p_null = block_New( p_dec, 128 );
904     if( !p_null )
905         return;
906     p_null->i_flags |= BLOCK_FLAG_DISCONTINUITY;
907     p_null->i_flags |= BLOCK_FLAG_CORE_FLUSH;
908     if( !p_dec->fmt_in.b_packetized )
909         p_null->i_flags |= BLOCK_FLAG_CORRUPTED;
910     memset( p_null->p_buffer, 0, p_null->i_buffer );
911
912     input_DecoderDecode( p_dec, p_null );
913
914     /* */
915     while( vlc_object_alive( p_dec ) && p_owner->b_flushing )
916         vlc_cond_wait( &p_owner->wait, &p_owner->lock );
917 }
918
919 static void DecoderSignalFlushed( decoder_t *p_dec )
920 {
921     decoder_owner_sys_t *p_owner = p_dec->p_owner;
922
923     vlc_mutex_lock( &p_owner->lock );
924
925     if( p_owner->b_flushing )
926     {
927         p_owner->b_flushing = false;
928         vlc_cond_signal( &p_owner->wait );
929     }
930
931     vlc_mutex_unlock( &p_owner->lock );
932 }
933
934 static void DecoderSignalBuffering( decoder_t *p_dec, bool b_full )
935 {
936     decoder_owner_sys_t *p_owner = p_dec->p_owner;
937
938     vlc_mutex_lock( &p_owner->lock );
939
940     if( p_owner->b_buffering )
941     {
942         if( b_full )
943             p_owner->buffer.b_full = true;
944         vlc_cond_signal( &p_owner->wait );
945     }
946
947     vlc_mutex_unlock( &p_owner->lock );
948 }
949
950 static bool DecoderIsFlushing( decoder_t *p_dec )
951 {
952     decoder_owner_sys_t *p_owner = p_dec->p_owner;
953     bool b_flushing;
954
955     vlc_mutex_lock( &p_owner->lock );
956
957     b_flushing = p_owner->b_flushing;
958
959     vlc_mutex_unlock( &p_owner->lock );
960
961     return b_flushing;
962 }
963
964 static void DecoderWaitUnblock( decoder_t *p_dec, bool *pb_reject )
965 {
966     decoder_owner_sys_t *p_owner = p_dec->p_owner;
967
968     vlc_assert_locked( &p_owner->lock );
969
970     while( !p_owner->b_flushing )
971     {
972         if( p_owner->b_paused )
973         {
974             if( p_owner->b_buffering && !p_owner->buffer.b_full )
975                 break;
976             if( p_owner->pause.i_ignore > 0 )
977             {
978                 p_owner->pause.i_ignore--;
979                 break;
980             }
981         }
982         else
983         {
984             if( !p_owner->b_buffering || !p_owner->buffer.b_full )
985                 break;
986         }
987         vlc_cond_wait( &p_owner->wait, &p_owner->lock );
988     }
989
990     if( pb_reject )
991         *pb_reject = p_owner->b_flushing;
992 }
993
994 static void DecoderOutputChangePause( decoder_t *p_dec, bool b_paused, mtime_t i_date )
995 {
996     decoder_owner_sys_t *p_owner = p_dec->p_owner;
997
998     vlc_assert_locked( &p_owner->lock );
999
1000     /* XXX only audio and video output have to be paused.
1001      * - for sout it is useless
1002      * - for subs, it is done by the vout
1003      */
1004     if( p_dec->fmt_in.i_cat == AUDIO_ES )
1005     {
1006         if( p_owner->p_aout && p_owner->p_aout_input )
1007             aout_DecChangePause( p_owner->p_aout, p_owner->p_aout_input,
1008                                  b_paused, i_date );
1009     }
1010     else if( p_dec->fmt_in.i_cat == VIDEO_ES )
1011     {
1012         if( p_owner->p_vout )
1013             vout_ChangePause( p_owner->p_vout, b_paused, i_date );
1014     }
1015 }
1016 static inline void DecoderUpdatePreroll( int64_t *pi_preroll, const block_t *p )
1017 {
1018     if( p->i_flags & (BLOCK_FLAG_PREROLL|BLOCK_FLAG_DISCONTINUITY) )
1019         *pi_preroll = INT64_MAX;
1020     else if( p->i_pts > 0 )
1021         *pi_preroll = __MIN( *pi_preroll, p->i_pts );
1022     else if( p->i_dts > 0 )
1023         *pi_preroll = __MIN( *pi_preroll, p->i_dts );
1024 }
1025
1026 static mtime_t DecoderTeletextFixTs( mtime_t i_ts, mtime_t i_ts_delay )
1027 {
1028     mtime_t current_date = mdate();
1029
1030     /* FIXME I don't really like that, es_out SHOULD do it using the video pts */
1031     if( !i_ts || i_ts > current_date + 10000000 || i_ts < current_date )
1032     {
1033         /* ETSI EN 300 472 Annex A : do not take into account the PTS
1034          * for teletext streams. */
1035         return current_date + 400000 + i_ts_delay;
1036     }
1037     return i_ts;
1038 }
1039
1040 static void DecoderFixTs( decoder_t *p_dec, mtime_t *pi_ts0, mtime_t *pi_ts1,
1041                           mtime_t *pi_duration, int *pi_rate, mtime_t *pi_delay, bool b_telx )
1042 {
1043     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1044     input_clock_t   *p_clock = p_owner->p_clock;
1045     int i_rate = 0;
1046
1047     vlc_assert_locked( &p_owner->lock );
1048
1049     const mtime_t i_ts_delay = p_owner->p_input->i_pts_delay;
1050     const mtime_t i_es_delay = p_owner->i_ts_delay;
1051
1052     if( p_clock )
1053     {
1054         const bool b_ephemere = pi_ts1 && *pi_ts0 == *pi_ts1;
1055
1056         if( *pi_ts0 > 0 )
1057             *pi_ts0 = input_clock_GetTS( p_clock, &i_rate, i_ts_delay,
1058                                          *pi_ts0 + i_es_delay );
1059         if( pi_ts1 && *pi_ts1 > 0 )
1060             *pi_ts1 = input_clock_GetTS( p_clock, &i_rate, i_ts_delay,
1061                                          *pi_ts1 + i_es_delay );
1062
1063         /* Do not create ephemere data because of rounding errors */
1064         if( !b_ephemere && pi_ts1 && *pi_ts0 == *pi_ts1 )
1065             *pi_ts1 += 1;
1066
1067         if( i_rate <= 0 )
1068             i_rate = input_clock_GetRate( p_clock ); 
1069
1070         if( pi_duration )
1071             *pi_duration = ( *pi_duration * i_rate +
1072                                     INPUT_RATE_DEFAULT-1 ) / INPUT_RATE_DEFAULT;
1073
1074         if( pi_rate )
1075             *pi_rate = i_rate;
1076
1077         if( b_telx )
1078         {
1079             *pi_ts0 = DecoderTeletextFixTs( *pi_ts0, i_ts_delay );
1080             if( pi_ts1 && *pi_ts1 <= 0 )
1081                 *pi_ts1 = *pi_ts0;
1082         }
1083     }
1084     if( pi_delay )
1085     {
1086         const int r = i_rate > 0 ? i_rate : INPUT_RATE_DEFAULT;
1087         *pi_delay = i_ts_delay + i_es_delay * r / INPUT_RATE_DEFAULT;
1088     }
1089 }
1090
1091 static void DecoderPlayAudio( decoder_t *p_dec, aout_buffer_t *p_audio,
1092                               int *pi_played_sum, int *pi_lost_sum )
1093 {
1094     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1095     aout_instance_t *p_aout = p_owner->p_aout;
1096     aout_input_t    *p_aout_input = p_owner->p_aout_input;
1097
1098     /* */
1099     if( p_audio->start_date <= 0 )
1100     {
1101         msg_Warn( p_dec, "non-dated audio buffer received" );
1102         *pi_lost_sum += 1;
1103         aout_BufferFree( p_audio );
1104         return;
1105     }
1106
1107     /* */
1108     vlc_mutex_lock( &p_owner->lock );
1109
1110     if( p_owner->b_buffering || p_owner->buffer.p_audio )
1111     {
1112         p_audio->p_next = NULL;
1113
1114         *p_owner->buffer.pp_audio_next = p_audio;
1115         p_owner->buffer.pp_audio_next = &p_audio->p_next;
1116
1117         p_owner->buffer.i_count++;
1118         if( p_owner->buffer.i_count > DECODER_MAX_BUFFERING_COUNT ||
1119             p_audio->start_date - p_owner->buffer.p_audio->start_date > DECODER_MAX_BUFFERING_AUDIO_DURATION )
1120         {
1121             p_owner->buffer.b_full = true;
1122             vlc_cond_signal( &p_owner->wait );
1123         }
1124     }
1125
1126     for( ;; )
1127     {
1128         bool b_has_more = false;
1129         bool b_reject;
1130         DecoderWaitUnblock( p_dec, &b_reject );
1131
1132         if( p_owner->b_buffering )
1133         {
1134             vlc_mutex_unlock( &p_owner->lock );
1135             return;
1136         }
1137
1138         /* */
1139         if( p_owner->buffer.p_audio )
1140         {
1141             p_audio = p_owner->buffer.p_audio;
1142
1143             p_owner->buffer.p_audio = p_audio->p_next;
1144             p_owner->buffer.i_count--;
1145
1146             b_has_more = p_owner->buffer.p_audio != NULL;
1147             if( !b_has_more )
1148                 p_owner->buffer.pp_audio_next = &p_owner->buffer.p_audio;
1149         }
1150
1151         /* */
1152         int i_rate = INPUT_RATE_DEFAULT;
1153         mtime_t i_delay;
1154
1155         DecoderFixTs( p_dec, &p_audio->start_date, &p_audio->end_date, NULL,
1156                       &i_rate, &i_delay, false );
1157
1158         vlc_mutex_unlock( &p_owner->lock );
1159
1160         /* */
1161         const mtime_t i_max_date = mdate() + i_delay + AOUT_MAX_ADVANCE_TIME;
1162
1163         if( !p_aout || !p_aout_input ||
1164             p_audio->start_date <= 0 || p_audio->start_date > i_max_date ||
1165             i_rate < INPUT_RATE_DEFAULT/AOUT_MAX_INPUT_RATE ||
1166             i_rate > INPUT_RATE_DEFAULT*AOUT_MAX_INPUT_RATE )
1167             b_reject = true;
1168
1169         /* Do not wait against unprotected date */
1170         const mtime_t i_deadline = p_audio->start_date - AOUT_MAX_PREPARE_TIME;
1171         while( !b_reject && i_deadline > mdate() )
1172         {
1173             vlc_mutex_lock( &p_owner->lock );
1174             if( p_owner->b_flushing || p_dec->b_die )
1175             {
1176                 b_reject = true;
1177                 vlc_mutex_unlock( &p_owner->lock );
1178                 break;
1179             }
1180             vlc_cond_timedwait( &p_owner->wait, &p_owner->lock, i_deadline );
1181             vlc_mutex_unlock( &p_owner->lock );
1182         }
1183
1184         if( !b_reject )
1185         {
1186             if( !aout_DecPlay( p_aout, p_aout_input, p_audio, i_rate ) )
1187                 *pi_played_sum += 1;
1188             *pi_lost_sum += aout_DecGetResetLost( p_aout, p_aout_input );
1189         }
1190         else
1191         {
1192             if( p_audio->start_date <= 0 )
1193             {
1194                 msg_Warn( p_dec, "non-dated audio buffer received" );
1195             }
1196             else if( p_audio->start_date > i_max_date )
1197             {
1198                 msg_Warn( p_aout, "received buffer in the future (%"PRId64")",
1199                           p_audio->start_date - mdate() );
1200             }
1201             *pi_lost_sum += 1;
1202             aout_BufferFree( p_audio );
1203         }
1204
1205         if( !b_has_more )
1206             break;
1207
1208         vlc_mutex_lock( &p_owner->lock );
1209         if( !p_owner->buffer.p_audio )
1210         {
1211             vlc_mutex_unlock( &p_owner->lock );
1212             break;
1213         }
1214     }
1215 }
1216
1217 static void DecoderDecodeAudio( decoder_t *p_dec, block_t *p_block )
1218 {
1219     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1220     input_thread_t  *p_input = p_owner->p_input;
1221     aout_buffer_t   *p_aout_buf;
1222     int i_decoded = 0;
1223     int i_lost = 0;
1224     int i_played = 0;
1225
1226     while( (p_aout_buf = p_dec->pf_decode_audio( p_dec, &p_block )) )
1227     {
1228         aout_instance_t *p_aout = p_owner->p_aout;
1229         aout_input_t    *p_aout_input = p_owner->p_aout_input;
1230
1231         if( p_dec->b_die )
1232         {
1233             /* It prevent freezing VLC in case of broken decoder */
1234             aout_DecDeleteBuffer( p_aout, p_aout_input, p_aout_buf );
1235             if( p_block )
1236                 block_Release( p_block );
1237             break;
1238         }
1239         i_decoded++;
1240
1241         if( p_aout_buf->start_date < p_owner->i_preroll_end )
1242         {
1243             aout_DecDeleteBuffer( p_aout, p_aout_input, p_aout_buf );
1244             continue;
1245         }
1246
1247         if( p_owner->i_preroll_end > 0 )
1248         {
1249             msg_Dbg( p_dec, "End of audio preroll" );
1250             if( p_owner->p_aout && p_owner->p_aout_input )
1251                 aout_DecFlush( p_owner->p_aout, p_owner->p_aout_input );
1252             /* */
1253             p_owner->i_preroll_end = -1;
1254         }
1255
1256         DecoderPlayAudio( p_dec, p_aout_buf, &i_played, &i_lost );
1257     }
1258
1259     /* Update ugly stat */
1260     if( i_decoded > 0 || i_lost > 0 || i_played > 0 )
1261     {
1262         vlc_mutex_lock( &p_input->p->counters.counters_lock);
1263
1264         stats_UpdateInteger( p_dec, p_input->p->counters.p_lost_abuffers,
1265                              i_lost, NULL );
1266         stats_UpdateInteger( p_dec, p_input->p->counters.p_played_abuffers,
1267                              i_played, NULL );
1268         stats_UpdateInteger( p_dec, p_input->p->counters.p_decoded_audio,
1269                              i_decoded, NULL );
1270
1271         vlc_mutex_unlock( &p_input->p->counters.counters_lock);
1272     }
1273 }
1274 static void DecoderGetCc( decoder_t *p_dec, decoder_t *p_dec_cc )
1275 {
1276     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1277     block_t *p_cc;
1278     bool pb_present[4];
1279     int i;
1280     int i_cc_decoder;
1281
1282     assert( p_dec_cc->pf_get_cc != NULL );
1283
1284     /* Do not try retreiving CC if not wanted (sout) or cannot be retreived */
1285     if( !p_owner->cc.b_supported )
1286         return;
1287
1288     p_cc = p_dec_cc->pf_get_cc( p_dec_cc, pb_present );
1289     if( !p_cc )
1290         return;
1291
1292     vlc_mutex_lock( &p_owner->lock );
1293     for( i = 0, i_cc_decoder = 0; i < 4; i++ )
1294     {
1295         p_owner->cc.pb_present[i] |= pb_present[i];
1296         if( p_owner->cc.pp_decoder[i] )
1297             i_cc_decoder++;
1298     }
1299
1300     for( i = 0; i < 4; i++ )
1301     {
1302         if( !p_owner->cc.pp_decoder[i] )
1303             continue;
1304
1305         if( i_cc_decoder > 1 )
1306             DecoderProcess( p_owner->cc.pp_decoder[i], block_Duplicate( p_cc ) );
1307         else
1308             DecoderProcess( p_owner->cc.pp_decoder[i], p_cc );
1309         i_cc_decoder--;
1310     }
1311     vlc_mutex_unlock( &p_owner->lock );
1312 }
1313
1314 static void DecoderPlayVideo( decoder_t *p_dec, picture_t *p_picture,
1315                               int *pi_played_sum, int *pi_lost_sum )
1316 {
1317     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1318     vout_thread_t  *p_vout = p_owner->p_vout;
1319     bool b_first_buffered;
1320
1321     if( p_picture->date <= 0 )
1322     {
1323         msg_Warn( p_vout, "non-dated video buffer received" );
1324         *pi_lost_sum += 1;
1325         vout_DropPicture( p_vout, p_picture );
1326         return;
1327     }
1328
1329     /* */
1330     vlc_mutex_lock( &p_owner->lock );
1331
1332     if( ( p_owner->b_buffering && !p_owner->buffer.b_first ) || p_owner->buffer.p_picture )
1333     {
1334         p_picture->p_next = NULL;
1335
1336         *p_owner->buffer.pp_picture_next = p_picture;
1337         p_owner->buffer.pp_picture_next = &p_picture->p_next;
1338
1339         p_owner->buffer.i_count++;
1340         if( p_owner->buffer.i_count > DECODER_MAX_BUFFERING_COUNT ||
1341             p_picture->date - p_owner->buffer.p_picture->date > DECODER_MAX_BUFFERING_VIDEO_DURATION )
1342         {
1343             p_owner->buffer.b_full = true;
1344             vlc_cond_signal( &p_owner->wait );
1345         }
1346     }
1347     b_first_buffered = p_owner->buffer.p_picture != NULL;
1348
1349     for( ;; b_first_buffered = false )
1350     {
1351         bool b_has_more = false;
1352
1353         bool b_reject;
1354
1355         DecoderWaitUnblock( p_dec, &b_reject );
1356
1357         if( p_owner->b_buffering && !p_owner->buffer.b_first )
1358         {
1359             vlc_mutex_unlock( &p_owner->lock );
1360             return;
1361         }
1362         bool b_buffering_first = p_owner->b_buffering;
1363
1364         /* */
1365         if( p_owner->buffer.p_picture )
1366         {
1367             p_picture = p_owner->buffer.p_picture;
1368
1369             p_owner->buffer.p_picture = p_picture->p_next;
1370             p_owner->buffer.i_count--;
1371
1372             b_has_more = p_owner->buffer.p_picture != NULL;
1373             if( !b_has_more )
1374                 p_owner->buffer.pp_picture_next = &p_owner->buffer.p_picture;
1375         }
1376
1377         /* */
1378         if( b_buffering_first )
1379         {
1380             assert( p_owner->buffer.b_first );
1381             assert( !p_owner->buffer.i_count );
1382             msg_Dbg( p_dec, "Received first picture" );
1383             p_owner->buffer.b_first = false;
1384             p_picture->b_force = true;
1385         }
1386
1387         int i_rate = INPUT_RATE_DEFAULT;
1388         mtime_t i_delay;
1389         DecoderFixTs( p_dec, &p_picture->date, NULL, NULL,
1390                       &i_rate, &i_delay, false );
1391
1392         vlc_mutex_unlock( &p_owner->lock );
1393
1394         /* */
1395         const mtime_t i_max_date = mdate() + i_delay + DECODER_BOGUS_VIDEO_DELAY;
1396
1397         if( !p_picture->b_force && ( p_picture->date <= 0 || p_picture->date >= i_max_date ) )
1398             b_reject = true;
1399
1400         if( !b_reject )
1401         {
1402             if( i_rate != p_owner->i_last_rate || b_first_buffered )
1403             {
1404                 /* Be sure to not display old picture after our own */
1405                 vout_Flush( p_vout, p_picture->date );
1406                 p_owner->i_last_rate = i_rate;
1407             }
1408             vout_DisplayPicture( p_vout, p_picture );
1409         }
1410         else
1411         {
1412             if( p_picture->date <= 0 )
1413             {
1414                 msg_Warn( p_vout, "non-dated video buffer received" );
1415             }
1416             else
1417             {
1418                 msg_Warn( p_vout, "early picture skipped (%"PRId64")",
1419                           p_picture->date - mdate() );
1420             }
1421             *pi_lost_sum += 1;
1422             vout_DropPicture( p_vout, p_picture );
1423         }
1424         int i_tmp_display;
1425         int i_tmp_lost;
1426         vout_GetResetStatistic( p_vout, &i_tmp_display, &i_tmp_lost );
1427
1428         *pi_played_sum += i_tmp_display;
1429         *pi_lost_sum += i_tmp_lost;
1430
1431         if( !b_has_more || b_buffering_first )
1432             break;
1433
1434         vlc_mutex_lock( &p_owner->lock );
1435         if( !p_owner->buffer.p_picture )
1436         {
1437             vlc_mutex_unlock( &p_owner->lock );
1438             break;
1439         }
1440     }
1441 }
1442
1443 static void DecoderDecodeVideo( decoder_t *p_dec, block_t *p_block )
1444 {
1445     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1446     input_thread_t *p_input = p_owner->p_input;
1447     picture_t      *p_pic;
1448     int i_lost = 0;
1449     int i_decoded = 0;
1450     int i_displayed = 0;
1451
1452     while( (p_pic = p_dec->pf_decode_video( p_dec, &p_block )) )
1453     {
1454         vout_thread_t  *p_vout = p_owner->p_vout;
1455         if( p_dec->b_die )
1456         {
1457             /* It prevent freezing VLC in case of broken decoder */
1458             vout_DropPicture( p_vout, p_pic );
1459             if( p_block )
1460                 block_Release( p_block );
1461             break;
1462         }
1463
1464         i_decoded++;
1465
1466         if( p_pic->date < p_owner->i_preroll_end )
1467         {
1468             vout_DropPicture( p_vout, p_pic );
1469             continue;
1470         }
1471
1472         if( p_owner->i_preroll_end > 0 )
1473         {
1474             msg_Dbg( p_dec, "End of video preroll" );
1475             if( p_vout )
1476                 vout_Flush( p_vout, 1 );
1477             /* */
1478             p_owner->i_preroll_end = -1;
1479         }
1480
1481         if( p_dec->pf_get_cc &&
1482             ( !p_owner->p_packetizer || !p_owner->p_packetizer->pf_get_cc ) )
1483             DecoderGetCc( p_dec, p_dec );
1484
1485         DecoderPlayVideo( p_dec, p_pic, &i_displayed, &i_lost );
1486     }
1487     if( i_decoded > 0 || i_lost > 0 || i_displayed > 0 )
1488     {
1489         vlc_mutex_lock( &p_input->p->counters.counters_lock );
1490
1491         stats_UpdateInteger( p_dec, p_input->p->counters.p_decoded_video,
1492                              i_decoded, NULL );
1493         stats_UpdateInteger( p_dec, p_input->p->counters.p_lost_pictures,
1494                              i_lost , NULL);
1495
1496         stats_UpdateInteger( p_dec, p_input->p->counters.p_displayed_pictures,
1497                              i_displayed, NULL);
1498
1499         vlc_mutex_unlock( &p_input->p->counters.counters_lock );
1500     }
1501 }
1502
1503 static void DecoderPlaySpu( decoder_t *p_dec, subpicture_t *p_subpic,
1504                             bool b_telx )
1505 {
1506     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1507     vout_thread_t *p_vout = p_owner->p_spu_vout;
1508
1509     /* */
1510     if( p_subpic->i_start <= 0 )
1511     {
1512         msg_Warn( p_dec, "non-dated spu buffer received" );
1513         subpicture_Delete( p_subpic );
1514         return;
1515     }
1516
1517     /* */
1518     vlc_mutex_lock( &p_owner->lock );
1519
1520     if( p_owner->b_buffering || p_owner->buffer.p_subpic )
1521     {
1522         p_subpic->p_next = NULL;
1523
1524         *p_owner->buffer.pp_subpic_next = p_subpic;
1525         p_owner->buffer.pp_subpic_next = &p_subpic->p_next;
1526
1527         p_owner->buffer.i_count++;
1528         /* XXX it is important to be full after the first one */
1529         if( p_owner->buffer.i_count > 0 )
1530         {
1531             p_owner->buffer.b_full = true;
1532             vlc_cond_signal( &p_owner->wait );
1533         }
1534     }
1535
1536     for( ;; )
1537     {
1538         bool b_has_more = false;
1539         bool b_reject;
1540         DecoderWaitUnblock( p_dec, &b_reject );
1541
1542         if( p_owner->b_buffering )
1543         {
1544             vlc_mutex_unlock( &p_owner->lock );
1545             return;
1546         }
1547
1548         /* */
1549         if( p_owner->buffer.p_subpic )
1550         {
1551             p_subpic = p_owner->buffer.p_subpic;
1552
1553             p_owner->buffer.p_subpic = p_subpic->p_next;
1554             p_owner->buffer.i_count--;
1555
1556             b_has_more = p_owner->buffer.p_subpic != NULL;
1557             if( !b_has_more )
1558                 p_owner->buffer.pp_subpic_next = &p_owner->buffer.p_subpic;
1559         }
1560
1561         /* */
1562         DecoderFixTs( p_dec, &p_subpic->i_start, &p_subpic->i_stop, NULL,
1563                       NULL, NULL, b_telx );
1564
1565         vlc_mutex_unlock( &p_owner->lock );
1566
1567         if( !b_reject )
1568             spu_DisplaySubpicture( p_vout->p_spu, p_subpic );
1569         else
1570             subpicture_Delete( p_subpic );
1571
1572         if( !b_has_more )
1573             break;
1574         vlc_mutex_lock( &p_owner->lock );
1575         if( !p_owner->buffer.p_subpic )
1576         {
1577             vlc_mutex_unlock( &p_owner->lock );
1578             break;
1579         }
1580     }
1581 }
1582
1583 static void DecoderPlaySout( decoder_t *p_dec, block_t *p_sout_block,
1584                              bool b_telx )
1585 {
1586     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1587
1588     assert( p_owner->p_clock );
1589     assert( !p_sout_block->p_next );
1590
1591     vlc_mutex_lock( &p_owner->lock );
1592
1593     if( p_owner->b_buffering || p_owner->buffer.p_block )
1594     {
1595         block_ChainLastAppend( &p_owner->buffer.pp_block_next, p_sout_block );
1596
1597         p_owner->buffer.i_count++;
1598         /* XXX it is important to be full after the first one */
1599         if( p_owner->buffer.i_count > 0 )
1600         {
1601             p_owner->buffer.b_full = true;
1602             vlc_cond_signal( &p_owner->wait );
1603         }
1604     }
1605
1606     for( ;; )
1607     {
1608         bool b_has_more = false;
1609         bool b_reject;
1610         DecoderWaitUnblock( p_dec, &b_reject );
1611
1612         if( p_owner->b_buffering )
1613         {
1614             vlc_mutex_unlock( &p_owner->lock );
1615             return;
1616         }
1617
1618         /* */
1619         if( p_owner->buffer.p_block )
1620         {
1621             p_sout_block = p_owner->buffer.p_block;
1622
1623             p_owner->buffer.p_block = p_sout_block->p_next;
1624             p_owner->buffer.i_count--;
1625
1626             b_has_more = p_owner->buffer.p_block != NULL;
1627             if( !b_has_more )
1628                 p_owner->buffer.pp_block_next = &p_owner->buffer.p_block;
1629         }
1630         p_sout_block->p_next = NULL;
1631
1632         DecoderFixTs( p_dec, &p_sout_block->i_dts, &p_sout_block->i_pts,
1633                       &p_sout_block->i_length,
1634                       &p_sout_block->i_rate, NULL, b_telx );
1635
1636         vlc_mutex_unlock( &p_owner->lock );
1637
1638         if( !b_reject )
1639             sout_InputSendBuffer( p_owner->p_sout_input, p_sout_block );
1640         else
1641             block_Release( p_sout_block );
1642
1643         if( !b_has_more )
1644             break;
1645         vlc_mutex_lock( &p_owner->lock );
1646         if( !p_owner->buffer.p_block )
1647         {
1648             vlc_mutex_unlock( &p_owner->lock );
1649             break;
1650         }
1651     }
1652 }
1653
1654 /* */
1655 static void DecoderFlushBuffering( decoder_t *p_dec )
1656 {
1657     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1658
1659     vlc_assert_locked( &p_owner->lock );
1660
1661     while( p_owner->buffer.p_picture )
1662     {
1663         picture_t *p_picture = p_owner->buffer.p_picture;
1664
1665         p_owner->buffer.p_picture = p_picture->p_next;
1666         p_owner->buffer.i_count--;
1667
1668         if( p_owner->p_vout )
1669             vout_DropPicture( p_owner->p_vout, p_picture );
1670
1671         if( !p_owner->buffer.p_picture )
1672             p_owner->buffer.pp_picture_next = &p_owner->buffer.p_picture;
1673     }
1674     while( p_owner->buffer.p_audio )
1675     {
1676         aout_buffer_t *p_audio = p_owner->buffer.p_audio;
1677
1678         p_owner->buffer.p_audio = p_audio->p_next;
1679         p_owner->buffer.i_count--;
1680
1681         aout_BufferFree( p_audio );
1682
1683         if( !p_owner->buffer.p_audio )
1684             p_owner->buffer.pp_audio_next = &p_owner->buffer.p_audio;
1685     }
1686     while( p_owner->buffer.p_subpic )
1687     {
1688         subpicture_t *p_subpic = p_owner->buffer.p_subpic;
1689
1690         p_owner->buffer.p_subpic = p_subpic->p_next;
1691         p_owner->buffer.i_count--;
1692
1693         subpicture_Delete( p_subpic );
1694
1695         if( !p_owner->buffer.p_subpic )
1696             p_owner->buffer.pp_subpic_next = &p_owner->buffer.p_subpic;
1697     }
1698     if( p_owner->buffer.p_block )
1699     {
1700         block_ChainRelease( p_owner->buffer.p_block );
1701
1702         p_owner->buffer.i_count = 0;
1703         p_owner->buffer.p_block = NULL;
1704         p_owner->buffer.pp_block_next = &p_owner->buffer.p_block;
1705     }
1706 }
1707
1708 /* This function process a block for sout
1709  */
1710 static void DecoderProcessSout( decoder_t *p_dec, block_t *p_block )
1711 {
1712     decoder_owner_sys_t *p_owner = (decoder_owner_sys_t *)p_dec->p_owner;
1713     const bool b_telx = p_dec->fmt_in.i_codec == VLC_FOURCC('t','e','l','x');
1714     block_t *p_sout_block;
1715
1716     while( ( p_sout_block =
1717                  p_dec->pf_packetize( p_dec, p_block ? &p_block : NULL ) ) )
1718     {
1719         if( !p_owner->p_sout_input )
1720         {
1721             es_format_Copy( &p_owner->sout, &p_dec->fmt_out );
1722
1723             p_owner->sout.i_group = p_dec->fmt_in.i_group;
1724             p_owner->sout.i_id = p_dec->fmt_in.i_id;
1725             if( p_dec->fmt_in.psz_language )
1726             {
1727                 if( p_owner->sout.psz_language )
1728                     free( p_owner->sout.psz_language );
1729                 p_owner->sout.psz_language =
1730                     strdup( p_dec->fmt_in.psz_language );
1731             }
1732
1733             p_owner->p_sout_input =
1734                 sout_InputNew( p_owner->p_sout,
1735                                &p_owner->sout );
1736
1737             if( p_owner->p_sout_input == NULL )
1738             {
1739                 msg_Err( p_dec, "cannot create packetizer output (%4.4s)",
1740                          (char *)&p_owner->sout.i_codec );
1741                 p_dec->b_error = true;
1742
1743                 while( p_sout_block )
1744                 {
1745                     block_t *p_next = p_sout_block->p_next;
1746                     block_Release( p_sout_block );
1747                     p_sout_block = p_next;
1748                 }
1749                 break;
1750             }
1751         }
1752
1753         while( p_sout_block )
1754         {
1755             block_t *p_next = p_sout_block->p_next;
1756
1757             p_sout_block->p_next = NULL;
1758
1759             DecoderPlaySout( p_dec, p_sout_block, b_telx );
1760
1761             p_sout_block = p_next;
1762         }
1763
1764         /* For now it's enough, as only sout impact on this flag */
1765         if( p_owner->p_sout->i_out_pace_nocontrol > 0 &&
1766             p_owner->p_input->p->b_out_pace_control )
1767         {
1768             msg_Dbg( p_dec, "switching to sync mode" );
1769             p_owner->p_input->p->b_out_pace_control = false;
1770         }
1771         else if( p_owner->p_sout->i_out_pace_nocontrol <= 0 &&
1772                  !p_owner->p_input->p->b_out_pace_control )
1773         {
1774             msg_Dbg( p_dec, "switching to async mode" );
1775             p_owner->p_input->p->b_out_pace_control = true;
1776         }
1777     }
1778 }
1779
1780 /* This function process a video block
1781  */
1782 static void DecoderProcessVideo( decoder_t *p_dec, block_t *p_block, bool b_flush )
1783 {
1784     decoder_owner_sys_t *p_owner = (decoder_owner_sys_t *)p_dec->p_owner;
1785
1786     if( p_owner->p_packetizer )
1787     {
1788         block_t *p_packetized_block;
1789         decoder_t *p_packetizer = p_owner->p_packetizer;
1790
1791         while( (p_packetized_block =
1792                 p_packetizer->pf_packetize( p_packetizer, p_block ? &p_block : NULL )) )
1793         {
1794             if( p_packetizer->fmt_out.i_extra && !p_dec->fmt_in.i_extra )
1795             {
1796                 es_format_Clean( &p_dec->fmt_in );
1797                 es_format_Copy( &p_dec->fmt_in, &p_packetizer->fmt_out );
1798             }
1799             if( p_packetizer->pf_get_cc )
1800                 DecoderGetCc( p_dec, p_packetizer );
1801
1802             while( p_packetized_block )
1803             {
1804                 block_t *p_next = p_packetized_block->p_next;
1805                 p_packetized_block->p_next = NULL;
1806
1807                 DecoderDecodeVideo( p_dec, p_packetized_block );
1808
1809                 p_packetized_block = p_next;
1810             }
1811         }
1812     }
1813     else if( p_block )
1814     {
1815         DecoderDecodeVideo( p_dec, p_block );
1816     }
1817
1818     if( b_flush && p_owner->p_vout )
1819         vout_Flush( p_owner->p_vout, 1 );
1820 }
1821
1822 /* This function process a audio block
1823  */
1824 static void DecoderProcessAudio( decoder_t *p_dec, block_t *p_block, bool b_flush )
1825 {
1826     decoder_owner_sys_t *p_owner = (decoder_owner_sys_t *)p_dec->p_owner;
1827
1828     if( p_owner->p_packetizer )
1829     {
1830         block_t *p_packetized_block;
1831         decoder_t *p_packetizer = p_owner->p_packetizer;
1832
1833         while( (p_packetized_block =
1834                 p_packetizer->pf_packetize( p_packetizer, p_block ? &p_block : NULL )) )
1835         {
1836             if( p_packetizer->fmt_out.i_extra && !p_dec->fmt_in.i_extra )
1837             {
1838                 es_format_Clean( &p_dec->fmt_in );
1839                 es_format_Copy( &p_dec->fmt_in, &p_packetizer->fmt_out );
1840             }
1841
1842             while( p_packetized_block )
1843             {
1844                 block_t *p_next = p_packetized_block->p_next;
1845                 p_packetized_block->p_next = NULL;
1846
1847                 DecoderDecodeAudio( p_dec, p_packetized_block );
1848
1849                 p_packetized_block = p_next;
1850             }
1851         }
1852     }
1853     else if( p_block )
1854     {
1855         DecoderDecodeAudio( p_dec, p_block );
1856     }
1857
1858     if( b_flush && p_owner->p_aout && p_owner->p_aout_input )
1859         aout_DecFlush( p_owner->p_aout, p_owner->p_aout_input );
1860 }
1861
1862 /* This function process a subtitle block
1863  */
1864 static void DecoderProcessSpu( decoder_t *p_dec, block_t *p_block, bool b_flush )
1865 {
1866     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1867     const bool b_telx = p_dec->fmt_in.i_codec == VLC_FOURCC('t','e','l','x');
1868
1869     input_thread_t *p_input = p_owner->p_input;
1870     vout_thread_t *p_vout;
1871     subpicture_t *p_spu;
1872
1873     while( (p_spu = p_dec->pf_decode_sub( p_dec, p_block ? &p_block : NULL ) ) )
1874     {
1875         vlc_mutex_lock( &p_input->p->counters.counters_lock );
1876         stats_UpdateInteger( p_dec, p_input->p->counters.p_decoded_sub, 1, NULL );
1877         vlc_mutex_unlock( &p_input->p->counters.counters_lock );
1878
1879         p_vout = input_ressource_HoldVout( p_input->p->p_ressource );
1880         if( p_vout && p_owner->p_spu_vout == p_vout )
1881         {
1882             /* Preroll does not work very well with subtitle */
1883             if( p_spu->i_start > 0 &&
1884                 p_spu->i_start < p_owner->i_preroll_end &&
1885                 ( p_spu->i_stop <= 0 || p_spu->i_stop < p_owner->i_preroll_end ) )
1886             {
1887                 subpicture_Delete( p_spu );
1888             }
1889             else
1890             {
1891                 DecoderPlaySpu( p_dec, p_spu, b_telx );
1892             }
1893         }
1894         else
1895         {
1896             subpicture_Delete( p_spu );
1897         }
1898         if( p_vout )
1899             vlc_object_release( p_vout );
1900     }
1901
1902     if( b_flush && p_owner->p_spu_vout )
1903     {
1904         p_vout = input_ressource_HoldVout( p_input->p->p_ressource );
1905
1906         if( p_vout && p_owner->p_spu_vout == p_vout )
1907             spu_Control( p_vout->p_spu, SPU_CHANNEL_CLEAR,
1908                          p_owner->i_spu_channel );
1909
1910         if( p_vout )
1911             vlc_object_release( p_vout );
1912     }
1913 }
1914
1915 /* */
1916 static void DecoderProcessOnFlush( decoder_t *p_dec )
1917 {
1918     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1919
1920     vlc_mutex_lock( &p_owner->lock );
1921     DecoderFlushBuffering( p_dec );
1922     vlc_mutex_unlock( &p_owner->lock );
1923
1924     DecoderSignalFlushed( p_dec );
1925 }
1926 /**
1927  * Decode a block
1928  *
1929  * \param p_dec the decoder object
1930  * \param p_block the block to decode
1931  * \return VLC_SUCCESS or an error code
1932  */
1933 static void DecoderProcess( decoder_t *p_dec, block_t *p_block )
1934 {
1935     decoder_owner_sys_t *p_owner = (decoder_owner_sys_t *)p_dec->p_owner;
1936     const bool b_flush_request = p_block && (p_block->i_flags & BLOCK_FLAG_CORE_FLUSH);
1937
1938     if( p_block && p_block->i_buffer <= 0 )
1939     {
1940         assert( !b_flush_request );
1941         block_Release( p_block );
1942         return;
1943     }
1944
1945 #ifdef ENABLE_SOUT
1946     if( p_dec->i_object_type == VLC_OBJECT_PACKETIZER )
1947     {
1948         if( p_block )
1949             p_block->i_flags &= ~BLOCK_FLAG_CORE_PRIVATE_MASK;
1950
1951         DecoderProcessSout( p_dec, p_block );
1952     }
1953     else
1954 #endif
1955     {
1956         bool b_flush = false;
1957
1958         if( p_block )
1959         {
1960             const bool b_flushing = p_owner->i_preroll_end == INT64_MAX;
1961             DecoderUpdatePreroll( &p_owner->i_preroll_end, p_block );
1962
1963             b_flush = !b_flushing && b_flush_request;
1964
1965             p_block->i_flags &= ~BLOCK_FLAG_CORE_PRIVATE_MASK;
1966         }
1967
1968         if( p_dec->fmt_in.i_cat == AUDIO_ES )
1969         {
1970             DecoderProcessAudio( p_dec, p_block, b_flush );
1971         }
1972         else if( p_dec->fmt_in.i_cat == VIDEO_ES )
1973         {
1974             DecoderProcessVideo( p_dec, p_block, b_flush );
1975         }
1976         else if( p_dec->fmt_in.i_cat == SPU_ES )
1977         {
1978             DecoderProcessSpu( p_dec, p_block, b_flush );
1979         }
1980         else
1981         {
1982             msg_Err( p_dec, "unknown ES format" );
1983             p_dec->b_error = true;
1984         }
1985     }
1986
1987     /* */
1988     if( b_flush_request )
1989         DecoderProcessOnFlush( p_dec );
1990 }
1991
1992 static void DecoderError( decoder_t *p_dec, block_t *p_block )
1993 {
1994     const bool b_flush_request = p_block && (p_block->i_flags & BLOCK_FLAG_CORE_FLUSH);
1995
1996     /* */
1997     if( p_block )
1998         block_Release( p_block );
1999
2000     if( b_flush_request )
2001         DecoderProcessOnFlush( p_dec );
2002 }
2003
2004
2005 /**
2006  * Destroys a decoder object
2007  *
2008  * \param p_dec the decoder object
2009  * \return nothing
2010  */
2011 static void DeleteDecoder( decoder_t * p_dec )
2012 {
2013     decoder_owner_sys_t *p_owner = p_dec->p_owner;
2014
2015     msg_Dbg( p_dec, "killing decoder fourcc `%4.4s', %u PES in FIFO",
2016              (char*)&p_dec->fmt_in.i_codec,
2017              (unsigned)block_FifoCount( p_owner->p_fifo ) );
2018
2019     /* Free all packets still in the decoder fifo. */
2020     block_FifoEmpty( p_owner->p_fifo );
2021     block_FifoRelease( p_owner->p_fifo );
2022
2023     /* */
2024     vlc_mutex_lock( &p_owner->lock );
2025     DecoderFlushBuffering( p_dec );
2026     vlc_mutex_unlock( &p_owner->lock );
2027
2028     /* Cleanup */
2029     if( p_owner->p_aout_input )
2030         aout_DecDelete( p_owner->p_aout, p_owner->p_aout_input );
2031     if( p_owner->p_aout )
2032     {
2033         input_ressource_RequestAout( p_owner->p_input->p->p_ressource,
2034                                      p_owner->p_aout );
2035         p_owner->p_aout = NULL;
2036     }
2037     if( p_owner->p_vout )
2038     {
2039         /* Hack to make sure all the the pictures are freed by the decoder */
2040         vout_FixLeaks( p_owner->p_vout, true );
2041
2042         /* We are about to die. Reattach video output to p_vlc. */
2043         input_ressource_RequestVout( p_owner->p_input->p->p_ressource, p_owner->p_vout, NULL );
2044         input_SendEventVout( p_owner->p_input );
2045     }
2046
2047 #ifdef ENABLE_SOUT
2048     if( p_owner->p_sout_input )
2049     {
2050         sout_InputDelete( p_owner->p_sout_input );
2051         es_format_Clean( &p_owner->sout );
2052     }
2053 #endif
2054
2055     if( p_dec->fmt_in.i_cat == SPU_ES )
2056     {
2057         vout_thread_t *p_vout;
2058
2059         p_vout = input_ressource_HoldVout( p_owner->p_input->p->p_ressource );
2060         if( p_vout )
2061         {
2062             if( p_owner->p_spu_vout == p_vout )
2063                 spu_Control( p_vout->p_spu, SPU_CHANNEL_CLEAR, p_owner->i_spu_channel );
2064             vlc_object_release( p_vout );
2065         }
2066     }
2067
2068     es_format_Clean( &p_dec->fmt_in );
2069     es_format_Clean( &p_dec->fmt_out );
2070     if( p_dec->p_description )
2071         vlc_meta_Delete( p_dec->p_description );
2072     es_format_Clean( &p_owner->fmt_description );
2073     if( p_owner->p_description )
2074         vlc_meta_Delete( p_owner->p_description );
2075
2076     if( p_owner->p_packetizer )
2077     {
2078         module_unneed( p_owner->p_packetizer,
2079                        p_owner->p_packetizer->p_module );
2080         es_format_Clean( &p_owner->p_packetizer->fmt_in );
2081         es_format_Clean( &p_owner->p_packetizer->fmt_out );
2082         if( p_owner->p_packetizer->p_description )
2083             vlc_meta_Delete( p_owner->p_packetizer->p_description );
2084         vlc_object_detach( p_owner->p_packetizer );
2085         vlc_object_release( p_owner->p_packetizer );
2086     }
2087
2088     vlc_cond_destroy( &p_owner->wait );
2089     vlc_mutex_destroy( &p_owner->lock );
2090
2091     vlc_object_detach( p_dec );
2092
2093     free( p_owner );
2094 }
2095
2096 /*****************************************************************************
2097  * Buffers allocation callbacks for the decoders
2098  *****************************************************************************/
2099 static void DecoderUpdateFormatLocked( decoder_t *p_dec )
2100 {
2101     decoder_owner_sys_t *p_owner = p_dec->p_owner;
2102
2103     vlc_assert_locked( &p_owner->lock );
2104
2105     p_owner->b_fmt_description = true;
2106
2107     /* Copy es_format */
2108     es_format_Clean( &p_owner->fmt_description );
2109     es_format_Copy( &p_owner->fmt_description, &p_dec->fmt_out );
2110
2111     /* Move p_description */
2112     if( p_owner->p_description && p_dec->p_description )
2113         vlc_meta_Delete( p_owner->p_description );
2114     p_owner->p_description = p_dec->p_description;
2115     p_dec->p_description = NULL;
2116 }
2117 static vout_thread_t *aout_request_vout( void *p_private,
2118                                          vout_thread_t *p_vout, video_format_t *p_fmt )
2119 {
2120     decoder_t *p_dec = p_private;
2121
2122     p_vout = input_ressource_RequestVout( p_dec->p_owner->p_input->p->p_ressource, p_vout, p_fmt );
2123     input_SendEventVout( p_dec->p_owner->p_input );
2124
2125     return p_vout;
2126 }
2127
2128 static aout_buffer_t *aout_new_buffer( decoder_t *p_dec, int i_samples )
2129 {
2130     decoder_owner_sys_t *p_owner = p_dec->p_owner;
2131     aout_buffer_t *p_buffer;
2132
2133     if( p_owner->p_aout_input != NULL &&
2134         ( p_dec->fmt_out.audio.i_rate != p_owner->audio.i_rate ||
2135           p_dec->fmt_out.audio.i_original_channels !=
2136               p_owner->audio.i_original_channels ||
2137           p_dec->fmt_out.audio.i_bytes_per_frame !=
2138               p_owner->audio.i_bytes_per_frame ) )
2139     {
2140         aout_input_t *p_aout_input = p_owner->p_aout_input;
2141
2142         /* Parameters changed, restart the aout */
2143         vlc_mutex_lock( &p_owner->lock );
2144
2145         DecoderFlushBuffering( p_dec );
2146
2147         p_owner->p_aout_input = NULL;
2148         aout_DecDelete( p_owner->p_aout, p_aout_input );
2149
2150         vlc_mutex_unlock( &p_owner->lock );
2151     }
2152
2153     if( p_owner->p_aout_input == NULL )
2154     {
2155         const int i_force_dolby = config_GetInt( p_dec, "force-dolby-surround" );
2156         audio_sample_format_t format;
2157         aout_input_t *p_aout_input;
2158         aout_instance_t *p_aout;
2159         aout_request_vout_t request_vout;
2160
2161         p_dec->fmt_out.audio.i_format = p_dec->fmt_out.i_codec;
2162         p_owner->audio = p_dec->fmt_out.audio;
2163
2164         memcpy( &format, &p_owner->audio, sizeof( audio_sample_format_t ) );
2165         if( i_force_dolby &&
2166             (format.i_original_channels&AOUT_CHAN_PHYSMASK) ==
2167                 (AOUT_CHAN_LEFT|AOUT_CHAN_RIGHT) )
2168         {
2169             if( i_force_dolby == 1 )
2170             {
2171                 format.i_original_channels = format.i_original_channels |
2172                                              AOUT_CHAN_DOLBYSTEREO;
2173             }
2174             else /* i_force_dolby == 2 */
2175             {
2176                 format.i_original_channels = format.i_original_channels &
2177                                              ~AOUT_CHAN_DOLBYSTEREO;
2178             }
2179         }
2180
2181         request_vout.pf_request_vout = aout_request_vout;
2182         request_vout.p_private = p_dec;
2183
2184         p_aout = p_owner->p_aout;
2185         if( !p_aout )
2186             p_aout = input_ressource_RequestAout( p_owner->p_input->p->p_ressource, NULL );
2187         p_aout_input = aout_DecNew( p_dec, &p_aout,
2188                                     &format, &p_dec->fmt_out.audio_replay_gain, &request_vout );
2189
2190         vlc_mutex_lock( &p_owner->lock );
2191
2192         p_owner->p_aout = p_aout;
2193         p_owner->p_aout_input = p_aout_input;
2194         DecoderUpdateFormatLocked( p_dec );
2195
2196         vlc_mutex_unlock( &p_owner->lock );
2197
2198         if( p_owner->p_aout_input == NULL )
2199         {
2200             msg_Err( p_dec, "failed to create audio output" );
2201             p_dec->b_error = true;
2202             return NULL;
2203         }
2204         p_dec->fmt_out.audio.i_bytes_per_frame =
2205             p_owner->audio.i_bytes_per_frame;
2206     }
2207
2208     p_buffer = aout_DecNewBuffer( p_owner->p_aout_input, i_samples );
2209
2210     return p_buffer;
2211 }
2212
2213 static void aout_del_buffer( decoder_t *p_dec, aout_buffer_t *p_buffer )
2214 {
2215     decoder_owner_sys_t *p_owner = p_dec->p_owner;
2216
2217     aout_DecDeleteBuffer( p_owner->p_aout,
2218                           p_owner->p_aout_input, p_buffer );
2219 }
2220
2221
2222 int vout_CountPictureAvailable( vout_thread_t *p_vout );
2223
2224 static picture_t *vout_new_buffer( decoder_t *p_dec )
2225 {
2226     decoder_owner_sys_t *p_owner = p_dec->p_owner;
2227
2228     if( p_owner->p_vout == NULL ||
2229         p_dec->fmt_out.video.i_width != p_owner->video.i_width ||
2230         p_dec->fmt_out.video.i_height != p_owner->video.i_height ||
2231         p_dec->fmt_out.video.i_chroma != p_owner->video.i_chroma ||
2232         p_dec->fmt_out.video.i_aspect != p_owner->video.i_aspect )
2233     {
2234         vout_thread_t *p_vout;
2235
2236         if( !p_dec->fmt_out.video.i_width ||
2237             !p_dec->fmt_out.video.i_height )
2238         {
2239             /* Can't create a new vout without display size */
2240             return NULL;
2241         }
2242
2243         if( !p_dec->fmt_out.video.i_visible_width ||
2244             !p_dec->fmt_out.video.i_visible_height )
2245         {
2246             if( p_dec->fmt_in.video.i_visible_width &&
2247                 p_dec->fmt_in.video.i_visible_height )
2248             {
2249                 p_dec->fmt_out.video.i_visible_width =
2250                     p_dec->fmt_in.video.i_visible_width;
2251                 p_dec->fmt_out.video.i_visible_height =
2252                     p_dec->fmt_in.video.i_visible_height;
2253             }
2254             else
2255             {
2256                 p_dec->fmt_out.video.i_visible_width =
2257                     p_dec->fmt_out.video.i_width;
2258                 p_dec->fmt_out.video.i_visible_height =
2259                     p_dec->fmt_out.video.i_height;
2260             }
2261         }
2262
2263         if( p_dec->fmt_out.video.i_visible_height == 1088 &&
2264             var_CreateGetBool( p_dec, "hdtv-fix" ) )
2265         {
2266             p_dec->fmt_out.video.i_visible_height = 1080;
2267             p_dec->fmt_out.video.i_sar_num *= 135;
2268             p_dec->fmt_out.video.i_sar_den *= 136;
2269             msg_Warn( p_dec, "Fixing broken HDTV stream (display_height=1088)");
2270         }
2271
2272         if( !p_dec->fmt_out.video.i_sar_num ||
2273             !p_dec->fmt_out.video.i_sar_den )
2274         {
2275             p_dec->fmt_out.video.i_sar_num = p_dec->fmt_out.video.i_aspect *
2276               p_dec->fmt_out.video.i_visible_height;
2277
2278             p_dec->fmt_out.video.i_sar_den = VOUT_ASPECT_FACTOR *
2279               p_dec->fmt_out.video.i_visible_width;
2280         }
2281
2282         vlc_ureduce( &p_dec->fmt_out.video.i_sar_num,
2283                      &p_dec->fmt_out.video.i_sar_den,
2284                      p_dec->fmt_out.video.i_sar_num,
2285                      p_dec->fmt_out.video.i_sar_den, 50000 );
2286
2287         p_dec->fmt_out.video.i_chroma = p_dec->fmt_out.i_codec;
2288         p_owner->video = p_dec->fmt_out.video;
2289
2290         vlc_mutex_lock( &p_owner->lock );
2291
2292         DecoderFlushBuffering( p_dec );
2293
2294         p_vout = p_owner->p_vout;
2295         p_owner->p_vout = NULL;
2296         vlc_mutex_unlock( &p_owner->lock );
2297
2298         p_vout = input_ressource_RequestVout( p_owner->p_input->p->p_ressource,
2299                                               p_vout, &p_dec->fmt_out.video );
2300
2301         vlc_mutex_lock( &p_owner->lock );
2302         p_owner->p_vout = p_vout;
2303
2304         DecoderUpdateFormatLocked( p_dec );
2305
2306         vlc_mutex_unlock( &p_owner->lock );
2307
2308         input_SendEventVout( p_owner->p_input );
2309         if( p_vout == NULL )
2310         {
2311             msg_Err( p_dec, "failed to create video output" );
2312             p_dec->b_error = true;
2313             return NULL;
2314         }
2315
2316         if( p_owner->video.i_rmask )
2317             p_owner->p_vout->render.i_rmask = p_owner->video.i_rmask;
2318         if( p_owner->video.i_gmask )
2319             p_owner->p_vout->render.i_gmask = p_owner->video.i_gmask;
2320         if( p_owner->video.i_bmask )
2321             p_owner->p_vout->render.i_bmask = p_owner->video.i_bmask;
2322     }
2323
2324     /* Get a new picture
2325      */
2326     for( ;; )
2327     {
2328         picture_t *p_picture;
2329
2330         if( p_dec->b_die || p_dec->b_error )
2331             return NULL;
2332
2333         /* The video filter chain required that there is always 1 free buffer
2334          * that it will use as temporary one. It will release the temporary
2335          * buffer once its work is done, so this check is safe even if we don't
2336          * lock around both count() and create().
2337          */
2338         if( vout_CountPictureAvailable( p_owner->p_vout ) >= 2 )
2339         {
2340             p_picture = vout_CreatePicture( p_owner->p_vout, 0, 0, 0 );
2341             if( p_picture )
2342                 return p_picture;
2343         }
2344
2345         if( DecoderIsFlushing( p_dec ) )
2346             return NULL;
2347
2348         /* */
2349         DecoderSignalBuffering( p_dec, true );
2350
2351         /* Check the decoder doesn't leak pictures */
2352         vout_FixLeaks( p_owner->p_vout, false );
2353
2354         /* FIXME add a vout_WaitPictureAvailable (timedwait) */
2355         msleep( VOUT_OUTMEM_SLEEP );
2356     }
2357 }
2358
2359 static void vout_del_buffer( decoder_t *p_dec, picture_t *p_pic )
2360 {
2361     vout_DropPicture( p_dec->p_owner->p_vout, p_pic );
2362 }
2363
2364 static void vout_link_picture( decoder_t *p_dec, picture_t *p_pic )
2365 {
2366     vout_LinkPicture( p_dec->p_owner->p_vout, p_pic );
2367 }
2368
2369 static void vout_unlink_picture( decoder_t *p_dec, picture_t *p_pic )
2370 {
2371     vout_UnlinkPicture( p_dec->p_owner->p_vout, p_pic );
2372 }
2373
2374 static subpicture_t *spu_new_buffer( decoder_t *p_dec )
2375 {
2376     decoder_owner_sys_t *p_owner = p_dec->p_owner;
2377     vout_thread_t *p_vout = NULL;
2378     subpicture_t *p_subpic;
2379     int i_attempts = 30;
2380
2381     while( i_attempts-- )
2382     {
2383         if( p_dec->b_die || p_dec->b_error )
2384             break;
2385
2386         p_vout = input_ressource_HoldVout( p_owner->p_input->p->p_ressource );
2387         if( p_vout )
2388             break;
2389
2390         msleep( DECODER_SPU_VOUT_WAIT_DURATION );
2391     }
2392
2393     if( !p_vout )
2394     {
2395         msg_Warn( p_dec, "no vout found, dropping subpicture" );
2396         return NULL;
2397     }
2398
2399     if( p_owner->p_spu_vout != p_vout )
2400     {
2401         vlc_mutex_lock( &p_owner->lock );
2402
2403         DecoderFlushBuffering( p_dec );
2404
2405         vlc_mutex_unlock( &p_owner->lock );
2406
2407         spu_Control( p_vout->p_spu, SPU_CHANNEL_REGISTER,
2408                      &p_owner->i_spu_channel );
2409         p_owner->i_spu_order = 0;
2410         p_owner->p_spu_vout = p_vout;
2411     }
2412
2413     p_subpic = subpicture_New();
2414     if( p_subpic )
2415     {
2416         p_subpic->i_channel = p_owner->i_spu_channel;
2417         p_subpic->i_order = p_owner->i_spu_order++;
2418         p_subpic->b_subtitle = true;
2419     }
2420
2421     vlc_object_release( p_vout );
2422
2423     return p_subpic;
2424 }
2425
2426 static void spu_del_buffer( decoder_t *p_dec, subpicture_t *p_subpic )
2427 {
2428     decoder_owner_sys_t *p_owner = p_dec->p_owner;
2429     vout_thread_t *p_vout = NULL;
2430
2431     p_vout = input_ressource_HoldVout( p_owner->p_input->p->p_ressource );
2432     if( !p_vout || p_owner->p_spu_vout != p_vout )
2433     {
2434         if( p_vout )
2435             vlc_object_release( p_vout );
2436         msg_Warn( p_dec, "no vout found, leaking subpicture" );
2437         return;
2438     }
2439
2440     subpicture_Delete( p_subpic );
2441
2442     vlc_object_release( p_vout );
2443 }
2444