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