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