]> git.sesse.net Git - vlc/blob - src/input/decoder.c
Convert rate stats to integer and remove useless float support
[vlc] / 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         stats_Update( p_input->p->counters.p_lost_abuffers, i_lost, NULL );
1331         stats_Update( p_input->p->counters.p_played_abuffers, i_played, NULL );
1332         stats_Update( p_input->p->counters.p_decoded_audio, i_decoded, NULL );
1333         vlc_mutex_unlock( &p_input->p->counters.counters_lock);
1334     }
1335 }
1336 static void DecoderGetCc( decoder_t *p_dec, decoder_t *p_dec_cc )
1337 {
1338     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1339     block_t *p_cc;
1340     bool pb_present[4];
1341     bool b_processed = false;
1342     int i;
1343     int i_cc_decoder;
1344
1345     assert( p_dec_cc->pf_get_cc != NULL );
1346
1347     /* Do not try retreiving CC if not wanted (sout) or cannot be retreived */
1348     if( !p_owner->cc.b_supported )
1349         return;
1350
1351     p_cc = p_dec_cc->pf_get_cc( p_dec_cc, pb_present );
1352     if( !p_cc )
1353         return;
1354
1355     vlc_mutex_lock( &p_owner->lock );
1356     for( i = 0, i_cc_decoder = 0; i < 4; i++ )
1357     {
1358         p_owner->cc.pb_present[i] |= pb_present[i];
1359         if( p_owner->cc.pp_decoder[i] )
1360             i_cc_decoder++;
1361     }
1362
1363     for( i = 0; i < 4; i++ )
1364     {
1365         if( !p_owner->cc.pp_decoder[i] )
1366             continue;
1367
1368         if( i_cc_decoder > 1 )
1369             DecoderProcess( p_owner->cc.pp_decoder[i], block_Duplicate( p_cc ) );
1370         else
1371             DecoderProcess( p_owner->cc.pp_decoder[i], p_cc );
1372         i_cc_decoder--;
1373         b_processed = true;
1374     }
1375     vlc_mutex_unlock( &p_owner->lock );
1376
1377     if( !b_processed )
1378         block_Release( p_cc );
1379 }
1380
1381 static void DecoderPlayVideo( decoder_t *p_dec, picture_t *p_picture,
1382                               int *pi_played_sum, int *pi_lost_sum )
1383 {
1384     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1385     vout_thread_t  *p_vout = p_owner->p_vout;
1386     bool b_first_buffered;
1387
1388     if( p_picture->date <= VLC_TS_INVALID )
1389     {
1390         msg_Warn( p_dec, "non-dated video buffer received" );
1391         *pi_lost_sum += 1;
1392         vout_ReleasePicture( p_vout, p_picture );
1393         return;
1394     }
1395
1396     /* */
1397     vlc_mutex_lock( &p_owner->lock );
1398
1399     if( ( p_owner->b_buffering && !p_owner->buffer.b_first ) || p_owner->buffer.p_picture )
1400     {
1401         p_picture->p_next = NULL;
1402
1403         *p_owner->buffer.pp_picture_next = p_picture;
1404         p_owner->buffer.pp_picture_next = &p_picture->p_next;
1405
1406         p_owner->buffer.i_count++;
1407         if( p_owner->buffer.i_count > DECODER_MAX_BUFFERING_COUNT ||
1408             p_picture->date - p_owner->buffer.p_picture->date > DECODER_MAX_BUFFERING_VIDEO_DURATION )
1409         {
1410             p_owner->buffer.b_full = true;
1411             vlc_cond_signal( &p_owner->wait_acknowledge );
1412         }
1413     }
1414     b_first_buffered = p_owner->buffer.p_picture != NULL;
1415
1416     for( ;; b_first_buffered = false )
1417     {
1418         bool b_has_more = false;
1419
1420         bool b_reject;
1421
1422         DecoderWaitUnblock( p_dec, &b_reject );
1423
1424         if( p_owner->b_buffering && !p_owner->buffer.b_first )
1425         {
1426             vlc_mutex_unlock( &p_owner->lock );
1427             return;
1428         }
1429         bool b_buffering_first = p_owner->b_buffering;
1430
1431         /* */
1432         if( p_owner->buffer.p_picture )
1433         {
1434             p_picture = p_owner->buffer.p_picture;
1435
1436             p_owner->buffer.p_picture = p_picture->p_next;
1437             p_owner->buffer.i_count--;
1438
1439             b_has_more = p_owner->buffer.p_picture != NULL;
1440             if( !b_has_more )
1441                 p_owner->buffer.pp_picture_next = &p_owner->buffer.p_picture;
1442         }
1443
1444         /* */
1445         if( b_buffering_first )
1446         {
1447             assert( p_owner->buffer.b_first );
1448             assert( !p_owner->buffer.i_count );
1449             msg_Dbg( p_dec, "Received first picture" );
1450             p_owner->buffer.b_first = false;
1451             p_picture->b_force = true;
1452         }
1453
1454         const bool b_dated = p_picture->date > VLC_TS_INVALID;
1455         int i_rate = INPUT_RATE_DEFAULT;
1456         DecoderFixTs( p_dec, &p_picture->date, NULL, NULL,
1457                       &i_rate, DECODER_BOGUS_VIDEO_DELAY, false );
1458
1459         vlc_mutex_unlock( &p_owner->lock );
1460
1461         /* */
1462         if( !p_picture->b_force && p_picture->date <= VLC_TS_INVALID ) // FIXME --VLC_TS_INVALID verify video_output/*
1463             b_reject = true;
1464
1465         if( !b_reject )
1466         {
1467             if( i_rate != p_owner->i_last_rate || b_first_buffered )
1468             {
1469                 /* Be sure to not display old picture after our own */
1470                 vout_Flush( p_vout, p_picture->date );
1471                 p_owner->i_last_rate = i_rate;
1472             }
1473             vout_PutPicture( p_vout, p_picture );
1474         }
1475         else
1476         {
1477             if( b_dated )
1478                 msg_Warn( p_dec, "early picture skipped" );
1479             else
1480                 msg_Warn( p_dec, "non-dated video buffer received" );
1481
1482             *pi_lost_sum += 1;
1483             vout_ReleasePicture( p_vout, p_picture );
1484         }
1485         int i_tmp_display;
1486         int i_tmp_lost;
1487         vout_GetResetStatistic( p_vout, &i_tmp_display, &i_tmp_lost );
1488
1489         *pi_played_sum += i_tmp_display;
1490         *pi_lost_sum += i_tmp_lost;
1491
1492         if( !b_has_more || b_buffering_first )
1493             break;
1494
1495         vlc_mutex_lock( &p_owner->lock );
1496         if( !p_owner->buffer.p_picture )
1497         {
1498             vlc_mutex_unlock( &p_owner->lock );
1499             break;
1500         }
1501     }
1502 }
1503
1504 static void DecoderDecodeVideo( decoder_t *p_dec, block_t *p_block )
1505 {
1506     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1507     picture_t      *p_pic;
1508     int i_lost = 0;
1509     int i_decoded = 0;
1510     int i_displayed = 0;
1511
1512     while( (p_pic = p_dec->pf_decode_video( p_dec, &p_block )) )
1513     {
1514         vout_thread_t  *p_vout = p_owner->p_vout;
1515         if( DecoderIsExitRequested( p_dec ) )
1516         {
1517             /* It prevent freezing VLC in case of broken decoder */
1518             vout_ReleasePicture( p_vout, p_pic );
1519             if( p_block )
1520                 block_Release( p_block );
1521             break;
1522         }
1523
1524         i_decoded++;
1525
1526         if( p_owner->i_preroll_end > VLC_TS_INVALID && p_pic->date < p_owner->i_preroll_end )
1527         {
1528             vout_ReleasePicture( p_vout, p_pic );
1529             continue;
1530         }
1531
1532         if( p_owner->i_preroll_end > VLC_TS_INVALID )
1533         {
1534             msg_Dbg( p_dec, "End of video preroll" );
1535             if( p_vout )
1536                 vout_Flush( p_vout, VLC_TS_INVALID+1 );
1537             /* */
1538             p_owner->i_preroll_end = VLC_TS_INVALID;
1539         }
1540
1541         if( p_dec->pf_get_cc &&
1542             ( !p_owner->p_packetizer || !p_owner->p_packetizer->pf_get_cc ) )
1543             DecoderGetCc( p_dec, p_dec );
1544
1545         DecoderPlayVideo( p_dec, p_pic, &i_displayed, &i_lost );
1546     }
1547
1548     /* Update ugly stat */
1549     input_thread_t *p_input = p_owner->p_input;
1550
1551     if( p_input != NULL && (i_decoded > 0 || i_lost > 0 || i_displayed > 0) )
1552     {
1553         vlc_mutex_lock( &p_input->p->counters.counters_lock );
1554         stats_Update( p_input->p->counters.p_decoded_video, i_decoded, NULL );
1555         stats_Update( p_input->p->counters.p_lost_pictures, i_lost , NULL);
1556         stats_Update( p_input->p->counters.p_displayed_pictures,
1557                       i_displayed, NULL);
1558         vlc_mutex_unlock( &p_input->p->counters.counters_lock );
1559     }
1560 }
1561
1562 static void DecoderPlaySpu( decoder_t *p_dec, subpicture_t *p_subpic,
1563                             bool b_telx )
1564 {
1565     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1566     vout_thread_t *p_vout = p_owner->p_spu_vout;
1567
1568     /* */
1569     if( p_subpic->i_start <= VLC_TS_INVALID && !b_telx )
1570     {
1571         msg_Warn( p_dec, "non-dated spu buffer received" );
1572         subpicture_Delete( p_subpic );
1573         return;
1574     }
1575
1576     /* */
1577     vlc_mutex_lock( &p_owner->lock );
1578
1579     if( p_owner->b_buffering || p_owner->buffer.p_subpic )
1580     {
1581         p_subpic->p_next = NULL;
1582
1583         *p_owner->buffer.pp_subpic_next = p_subpic;
1584         p_owner->buffer.pp_subpic_next = &p_subpic->p_next;
1585
1586         p_owner->buffer.i_count++;
1587         /* XXX it is important to be full after the first one */
1588         if( p_owner->buffer.i_count > 0 )
1589         {
1590             p_owner->buffer.b_full = true;
1591             vlc_cond_signal( &p_owner->wait_acknowledge );
1592         }
1593     }
1594
1595     for( ;; )
1596     {
1597         bool b_has_more = false;
1598         bool b_reject;
1599         DecoderWaitUnblock( p_dec, &b_reject );
1600
1601         if( p_owner->b_buffering )
1602         {
1603             vlc_mutex_unlock( &p_owner->lock );
1604             return;
1605         }
1606
1607         /* */
1608         if( p_owner->buffer.p_subpic )
1609         {
1610             p_subpic = p_owner->buffer.p_subpic;
1611
1612             p_owner->buffer.p_subpic = p_subpic->p_next;
1613             p_owner->buffer.i_count--;
1614
1615             b_has_more = p_owner->buffer.p_subpic != NULL;
1616             if( !b_has_more )
1617                 p_owner->buffer.pp_subpic_next = &p_owner->buffer.p_subpic;
1618         }
1619
1620         /* */
1621         DecoderFixTs( p_dec, &p_subpic->i_start, &p_subpic->i_stop, NULL,
1622                       NULL, INT64_MAX, b_telx );
1623
1624         vlc_mutex_unlock( &p_owner->lock );
1625
1626         if( p_subpic->i_start <= VLC_TS_INVALID )
1627             b_reject = true;
1628
1629         DecoderWaitDate( p_dec, &b_reject,
1630                          p_subpic->i_start - SPU_MAX_PREPARE_TIME );
1631
1632         if( !b_reject )
1633             vout_PutSubpicture( p_vout, p_subpic );
1634         else
1635             subpicture_Delete( p_subpic );
1636
1637         if( !b_has_more )
1638             break;
1639         vlc_mutex_lock( &p_owner->lock );
1640         if( !p_owner->buffer.p_subpic )
1641         {
1642             vlc_mutex_unlock( &p_owner->lock );
1643             break;
1644         }
1645     }
1646 }
1647
1648 #ifdef ENABLE_SOUT
1649 static void DecoderPlaySout( decoder_t *p_dec, block_t *p_sout_block,
1650                              bool b_telx )
1651 {
1652     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1653
1654     assert( p_owner->p_clock );
1655     assert( !p_sout_block->p_next );
1656
1657     vlc_mutex_lock( &p_owner->lock );
1658
1659     if( p_owner->b_buffering || p_owner->buffer.p_block )
1660     {
1661         block_ChainLastAppend( &p_owner->buffer.pp_block_next, p_sout_block );
1662
1663         p_owner->buffer.i_count++;
1664         /* XXX it is important to be full after the first one */
1665         if( p_owner->buffer.i_count > 0 )
1666         {
1667             p_owner->buffer.b_full = true;
1668             vlc_cond_signal( &p_owner->wait_acknowledge );
1669         }
1670     }
1671
1672     for( ;; )
1673     {
1674         bool b_has_more = false;
1675         bool b_reject;
1676         DecoderWaitUnblock( p_dec, &b_reject );
1677
1678         if( p_owner->b_buffering )
1679         {
1680             vlc_mutex_unlock( &p_owner->lock );
1681             return;
1682         }
1683
1684         /* */
1685         if( p_owner->buffer.p_block )
1686         {
1687             p_sout_block = p_owner->buffer.p_block;
1688
1689             p_owner->buffer.p_block = p_sout_block->p_next;
1690             p_owner->buffer.i_count--;
1691
1692             b_has_more = p_owner->buffer.p_block != NULL;
1693             if( !b_has_more )
1694                 p_owner->buffer.pp_block_next = &p_owner->buffer.p_block;
1695         }
1696         p_sout_block->p_next = NULL;
1697
1698         DecoderFixTs( p_dec, &p_sout_block->i_dts, &p_sout_block->i_pts,
1699                       &p_sout_block->i_length, NULL, INT64_MAX, b_telx );
1700
1701         vlc_mutex_unlock( &p_owner->lock );
1702
1703         if( !b_reject )
1704             sout_InputSendBuffer( p_owner->p_sout_input, p_sout_block ); // FIXME --VLC_TS_INVALID inspect stream_output/*
1705         else
1706             block_Release( p_sout_block );
1707
1708         if( !b_has_more )
1709             break;
1710         vlc_mutex_lock( &p_owner->lock );
1711         if( !p_owner->buffer.p_block )
1712         {
1713             vlc_mutex_unlock( &p_owner->lock );
1714             break;
1715         }
1716     }
1717 }
1718 #endif
1719
1720 /* */
1721 static void DecoderFlushBuffering( decoder_t *p_dec )
1722 {
1723     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1724
1725     vlc_assert_locked( &p_owner->lock );
1726
1727     while( p_owner->buffer.p_picture )
1728     {
1729         picture_t *p_picture = p_owner->buffer.p_picture;
1730
1731         p_owner->buffer.p_picture = p_picture->p_next;
1732         p_owner->buffer.i_count--;
1733
1734         if( p_owner->p_vout )
1735         {
1736             vout_ReleasePicture( p_owner->p_vout, p_picture );
1737         }
1738
1739         if( !p_owner->buffer.p_picture )
1740             p_owner->buffer.pp_picture_next = &p_owner->buffer.p_picture;
1741     }
1742     while( p_owner->buffer.p_audio )
1743     {
1744         aout_buffer_t *p_audio = p_owner->buffer.p_audio;
1745
1746         p_owner->buffer.p_audio = p_audio->p_next;
1747         p_owner->buffer.i_count--;
1748
1749         aout_BufferFree( p_audio );
1750
1751         if( !p_owner->buffer.p_audio )
1752             p_owner->buffer.pp_audio_next = &p_owner->buffer.p_audio;
1753     }
1754     while( p_owner->buffer.p_subpic )
1755     {
1756         subpicture_t *p_subpic = p_owner->buffer.p_subpic;
1757
1758         p_owner->buffer.p_subpic = p_subpic->p_next;
1759         p_owner->buffer.i_count--;
1760
1761         subpicture_Delete( p_subpic );
1762
1763         if( !p_owner->buffer.p_subpic )
1764             p_owner->buffer.pp_subpic_next = &p_owner->buffer.p_subpic;
1765     }
1766     if( p_owner->buffer.p_block )
1767     {
1768         block_ChainRelease( p_owner->buffer.p_block );
1769
1770         p_owner->buffer.i_count = 0;
1771         p_owner->buffer.p_block = NULL;
1772         p_owner->buffer.pp_block_next = &p_owner->buffer.p_block;
1773     }
1774 }
1775
1776 #ifdef ENABLE_SOUT
1777 /* This function process a block for sout
1778  */
1779 static void DecoderProcessSout( decoder_t *p_dec, block_t *p_block )
1780 {
1781     decoder_owner_sys_t *p_owner = (decoder_owner_sys_t *)p_dec->p_owner;
1782     const bool b_telx = p_dec->fmt_in.i_codec == VLC_CODEC_TELETEXT;
1783     block_t *p_sout_block;
1784
1785     while( ( p_sout_block =
1786                  p_dec->pf_packetize( p_dec, p_block ? &p_block : NULL ) ) )
1787     {
1788         if( !p_owner->p_sout_input )
1789         {
1790             es_format_Copy( &p_owner->sout, &p_dec->fmt_out );
1791
1792             p_owner->sout.i_group = p_dec->fmt_in.i_group;
1793             p_owner->sout.i_id = p_dec->fmt_in.i_id;
1794             if( p_dec->fmt_in.psz_language )
1795             {
1796                 free( p_owner->sout.psz_language );
1797                 p_owner->sout.psz_language =
1798                     strdup( p_dec->fmt_in.psz_language );
1799             }
1800
1801             p_owner->p_sout_input =
1802                 sout_InputNew( p_owner->p_sout,
1803                                &p_owner->sout );
1804
1805             if( p_owner->p_sout_input == NULL )
1806             {
1807                 msg_Err( p_dec, "cannot create packetizer output (%4.4s)",
1808                          (char *)&p_owner->sout.i_codec );
1809                 p_dec->b_error = true;
1810
1811                 while( p_sout_block )
1812                 {
1813                     block_t *p_next = p_sout_block->p_next;
1814                     block_Release( p_sout_block );
1815                     p_sout_block = p_next;
1816                 }
1817                 break;
1818             }
1819         }
1820
1821         while( p_sout_block )
1822         {
1823             block_t *p_next = p_sout_block->p_next;
1824
1825             p_sout_block->p_next = NULL;
1826
1827             DecoderPlaySout( p_dec, p_sout_block, b_telx );
1828
1829             p_sout_block = p_next;
1830         }
1831     }
1832 }
1833 #endif
1834
1835 /* This function process a video block
1836  */
1837 static void DecoderProcessVideo( decoder_t *p_dec, block_t *p_block, bool b_flush )
1838 {
1839     decoder_owner_sys_t *p_owner = (decoder_owner_sys_t *)p_dec->p_owner;
1840
1841     if( p_owner->p_packetizer )
1842     {
1843         block_t *p_packetized_block;
1844         decoder_t *p_packetizer = p_owner->p_packetizer;
1845
1846         while( (p_packetized_block =
1847                 p_packetizer->pf_packetize( p_packetizer, p_block ? &p_block : NULL )) )
1848         {
1849             if( p_packetizer->fmt_out.i_extra && !p_dec->fmt_in.i_extra )
1850             {
1851                 es_format_Clean( &p_dec->fmt_in );
1852                 es_format_Copy( &p_dec->fmt_in, &p_packetizer->fmt_out );
1853             }
1854             if( p_packetizer->pf_get_cc )
1855                 DecoderGetCc( p_dec, p_packetizer );
1856
1857             while( p_packetized_block )
1858             {
1859                 block_t *p_next = p_packetized_block->p_next;
1860                 p_packetized_block->p_next = NULL;
1861
1862                 DecoderDecodeVideo( p_dec, p_packetized_block );
1863
1864                 p_packetized_block = p_next;
1865             }
1866         }
1867         /* The packetizer does not output a block that tell the decoder to flush
1868          * do it ourself */
1869         if( b_flush )
1870         {
1871             block_t *p_null = DecoderBlockFlushNew();
1872             if( p_null )
1873                 DecoderDecodeVideo( p_dec, p_null );
1874         }
1875     }
1876     else if( p_block )
1877     {
1878         DecoderDecodeVideo( p_dec, p_block );
1879     }
1880
1881     if( b_flush && p_owner->p_vout )
1882         vout_Flush( p_owner->p_vout, VLC_TS_INVALID+1 );
1883 }
1884
1885 /* This function process a audio block
1886  */
1887 static void DecoderProcessAudio( decoder_t *p_dec, block_t *p_block, bool b_flush )
1888 {
1889     decoder_owner_sys_t *p_owner = (decoder_owner_sys_t *)p_dec->p_owner;
1890
1891     if( p_owner->p_packetizer )
1892     {
1893         block_t *p_packetized_block;
1894         decoder_t *p_packetizer = p_owner->p_packetizer;
1895
1896         while( (p_packetized_block =
1897                 p_packetizer->pf_packetize( p_packetizer, p_block ? &p_block : NULL )) )
1898         {
1899             if( p_packetizer->fmt_out.i_extra && !p_dec->fmt_in.i_extra )
1900             {
1901                 es_format_Clean( &p_dec->fmt_in );
1902                 es_format_Copy( &p_dec->fmt_in, &p_packetizer->fmt_out );
1903             }
1904
1905             while( p_packetized_block )
1906             {
1907                 block_t *p_next = p_packetized_block->p_next;
1908                 p_packetized_block->p_next = NULL;
1909
1910                 DecoderDecodeAudio( p_dec, p_packetized_block );
1911
1912                 p_packetized_block = p_next;
1913             }
1914         }
1915         /* The packetizer does not output a block that tell the decoder to flush
1916          * do it ourself */
1917         if( b_flush )
1918         {
1919             block_t *p_null = DecoderBlockFlushNew();
1920             if( p_null )
1921                 DecoderDecodeAudio( p_dec, p_null );
1922         }
1923     }
1924     else if( p_block )
1925     {
1926         DecoderDecodeAudio( p_dec, p_block );
1927     }
1928
1929     if( b_flush && p_owner->p_aout )
1930         aout_DecFlush( p_owner->p_aout );
1931 }
1932
1933 /* This function process a subtitle block
1934  */
1935 static void DecoderProcessSpu( decoder_t *p_dec, block_t *p_block, bool b_flush )
1936 {
1937     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1938     const bool b_telx = p_dec->fmt_in.i_codec == VLC_CODEC_TELETEXT;
1939
1940     input_thread_t *p_input = p_owner->p_input;
1941     vout_thread_t *p_vout;
1942     subpicture_t *p_spu;
1943
1944     while( (p_spu = p_dec->pf_decode_sub( p_dec, p_block ? &p_block : NULL ) ) )
1945     {
1946         if( p_input != NULL )
1947         {
1948             vlc_mutex_lock( &p_input->p->counters.counters_lock );
1949             stats_Update( p_input->p->counters.p_decoded_sub, 1, NULL );
1950             vlc_mutex_unlock( &p_input->p->counters.counters_lock );
1951         }
1952
1953         p_vout = input_resource_HoldVout( p_owner->p_resource );
1954         if( p_vout && p_owner->p_spu_vout == p_vout )
1955         {
1956             /* Preroll does not work very well with subtitle */
1957             if( p_spu->i_start > VLC_TS_INVALID &&
1958                 p_spu->i_start < p_owner->i_preroll_end &&
1959                 ( p_spu->i_stop <= VLC_TS_INVALID || p_spu->i_stop < p_owner->i_preroll_end ) )
1960             {
1961                 subpicture_Delete( p_spu );
1962             }
1963             else
1964             {
1965                 DecoderPlaySpu( p_dec, p_spu, b_telx );
1966             }
1967         }
1968         else
1969         {
1970             subpicture_Delete( p_spu );
1971         }
1972         if( p_vout )
1973             vlc_object_release( p_vout );
1974     }
1975
1976     if( b_flush && p_owner->p_spu_vout )
1977     {
1978         p_vout = input_resource_HoldVout( p_owner->p_resource );
1979
1980         if( p_vout && p_owner->p_spu_vout == p_vout )
1981             vout_FlushSubpictureChannel( p_vout, p_owner->i_spu_channel );
1982
1983         if( p_vout )
1984             vlc_object_release( p_vout );
1985     }
1986 }
1987
1988 /* */
1989 static void DecoderProcessOnFlush( decoder_t *p_dec )
1990 {
1991     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1992
1993     vlc_mutex_lock( &p_owner->lock );
1994     DecoderFlushBuffering( p_dec );
1995
1996     if( p_owner->b_flushing )
1997     {
1998         p_owner->b_flushing = false;
1999         vlc_cond_signal( &p_owner->wait_acknowledge );
2000     }
2001     vlc_mutex_unlock( &p_owner->lock );
2002 }
2003
2004 /**
2005  * Decode a block
2006  *
2007  * \param p_dec the decoder object
2008  * \param p_block the block to decode
2009  * \return VLC_SUCCESS or an error code
2010  */
2011 static void DecoderProcess( decoder_t *p_dec, block_t *p_block )
2012 {
2013     decoder_owner_sys_t *p_owner = (decoder_owner_sys_t *)p_dec->p_owner;
2014     const bool b_flush_request = p_block && (p_block->i_flags & BLOCK_FLAG_CORE_FLUSH);
2015
2016     if( p_block && p_block->i_buffer <= 0 )
2017     {
2018         assert( !b_flush_request );
2019         block_Release( p_block );
2020         return;
2021     }
2022
2023 #ifdef ENABLE_SOUT
2024     if( p_owner->b_packetizer )
2025     {
2026         if( p_block )
2027             p_block->i_flags &= ~BLOCK_FLAG_CORE_PRIVATE_MASK;
2028
2029         DecoderProcessSout( p_dec, p_block );
2030     }
2031     else
2032 #endif
2033     {
2034         bool b_flush = false;
2035
2036         if( p_block )
2037         {
2038             const bool b_flushing = p_owner->i_preroll_end == INT64_MAX;
2039             DecoderUpdatePreroll( &p_owner->i_preroll_end, p_block );
2040
2041             b_flush = !b_flushing && b_flush_request;
2042
2043             p_block->i_flags &= ~BLOCK_FLAG_CORE_PRIVATE_MASK;
2044         }
2045
2046         if( p_dec->fmt_out.i_cat == AUDIO_ES )
2047         {
2048             DecoderProcessAudio( p_dec, p_block, b_flush );
2049         }
2050         else if( p_dec->fmt_out.i_cat == VIDEO_ES )
2051         {
2052             DecoderProcessVideo( p_dec, p_block, b_flush );
2053         }
2054         else if( p_dec->fmt_out.i_cat == SPU_ES )
2055         {
2056             DecoderProcessSpu( p_dec, p_block, b_flush );
2057         }
2058         else
2059         {
2060             msg_Err( p_dec, "unknown ES format" );
2061             p_dec->b_error = true;
2062         }
2063     }
2064
2065     /* */
2066     if( b_flush_request )
2067         DecoderProcessOnFlush( p_dec );
2068 }
2069
2070 static void DecoderError( decoder_t *p_dec, block_t *p_block )
2071 {
2072     const bool b_flush_request = p_block && (p_block->i_flags & BLOCK_FLAG_CORE_FLUSH);
2073
2074     /* */
2075     if( p_block )
2076         block_Release( p_block );
2077
2078     if( b_flush_request )
2079         DecoderProcessOnFlush( p_dec );
2080 }
2081
2082
2083 /**
2084  * Destroys a decoder object
2085  *
2086  * \param p_dec the decoder object
2087  * \return nothing
2088  */
2089 static void DeleteDecoder( decoder_t * p_dec )
2090 {
2091     decoder_owner_sys_t *p_owner = p_dec->p_owner;
2092
2093     msg_Dbg( p_dec, "killing decoder fourcc `%4.4s', %u PES in FIFO",
2094              (char*)&p_dec->fmt_in.i_codec,
2095              (unsigned)block_FifoCount( p_owner->p_fifo ) );
2096
2097     /* Free all packets still in the decoder fifo. */
2098     block_FifoEmpty( p_owner->p_fifo );
2099     block_FifoRelease( p_owner->p_fifo );
2100
2101     /* */
2102     vlc_mutex_lock( &p_owner->lock );
2103     DecoderFlushBuffering( p_dec );
2104     vlc_mutex_unlock( &p_owner->lock );
2105
2106     /* Cleanup */
2107     if( p_owner->p_aout )
2108     {
2109         /* TODO: REVISIT gap-less audio */
2110         aout_DecFlush( p_owner->p_aout );
2111         aout_DecDelete( p_owner->p_aout );
2112         input_resource_RequestAout( p_owner->p_resource, p_owner->p_aout );
2113         if( p_owner->p_input != NULL )
2114             input_SendEventAout( p_owner->p_input );
2115     }
2116     if( p_owner->p_vout )
2117     {
2118         /* Hack to make sure all the the pictures are freed by the decoder
2119          * and that the vout is not paused anymore */
2120         vout_Reset( p_owner->p_vout );
2121
2122         /* */
2123         input_resource_RequestVout( p_owner->p_resource, p_owner->p_vout, NULL,
2124                                     0, true );
2125         if( p_owner->p_input != NULL )
2126             input_SendEventVout( p_owner->p_input );
2127     }
2128
2129 #ifdef ENABLE_SOUT
2130     if( p_owner->p_sout_input )
2131     {
2132         sout_InputDelete( p_owner->p_sout_input );
2133         es_format_Clean( &p_owner->sout );
2134     }
2135 #endif
2136
2137     if( p_dec->fmt_out.i_cat == SPU_ES )
2138     {
2139         vout_thread_t *p_vout;
2140
2141         p_vout = input_resource_HoldVout( p_owner->p_resource );
2142         if( p_vout )
2143         {
2144             if( p_owner->p_spu_vout == p_vout )
2145                 vout_FlushSubpictureChannel( p_vout, p_owner->i_spu_channel );
2146             vlc_object_release( p_vout );
2147         }
2148     }
2149
2150     es_format_Clean( &p_dec->fmt_in );
2151     es_format_Clean( &p_dec->fmt_out );
2152     if( p_dec->p_description )
2153         vlc_meta_Delete( p_dec->p_description );
2154     es_format_Clean( &p_owner->fmt_description );
2155     if( p_owner->p_description )
2156         vlc_meta_Delete( p_owner->p_description );
2157
2158     if( p_owner->p_packetizer )
2159     {
2160         module_unneed( p_owner->p_packetizer,
2161                        p_owner->p_packetizer->p_module );
2162         es_format_Clean( &p_owner->p_packetizer->fmt_in );
2163         es_format_Clean( &p_owner->p_packetizer->fmt_out );
2164         if( p_owner->p_packetizer->p_description )
2165             vlc_meta_Delete( p_owner->p_packetizer->p_description );
2166         vlc_object_release( p_owner->p_packetizer );
2167     }
2168
2169     vlc_cond_destroy( &p_owner->wait_acknowledge );
2170     vlc_cond_destroy( &p_owner->wait_request );
2171     vlc_mutex_destroy( &p_owner->lock );
2172
2173     vlc_object_release( p_dec );
2174
2175     free( p_owner );
2176 }
2177
2178 /*****************************************************************************
2179  * Buffers allocation callbacks for the decoders
2180  *****************************************************************************/
2181 static void DecoderUpdateFormatLocked( decoder_t *p_dec )
2182 {
2183     decoder_owner_sys_t *p_owner = p_dec->p_owner;
2184
2185     vlc_assert_locked( &p_owner->lock );
2186
2187     p_owner->b_fmt_description = true;
2188
2189     /* Copy es_format */
2190     es_format_Clean( &p_owner->fmt_description );
2191     es_format_Copy( &p_owner->fmt_description, &p_dec->fmt_out );
2192
2193     /* Move p_description */
2194     if( p_owner->p_description && p_dec->p_description )
2195         vlc_meta_Delete( p_owner->p_description );
2196     p_owner->p_description = p_dec->p_description;
2197     p_dec->p_description = NULL;
2198 }
2199 static vout_thread_t *aout_request_vout( void *p_private,
2200                                          vout_thread_t *p_vout, video_format_t *p_fmt, bool b_recyle )
2201 {
2202     decoder_t *p_dec = p_private;
2203     decoder_owner_sys_t *p_owner = p_dec->p_owner;
2204     input_thread_t *p_input = p_owner->p_input;
2205
2206     p_vout = input_resource_RequestVout( p_owner->p_resource, p_vout, p_fmt, 1,
2207                                          b_recyle );
2208     if( p_input != NULL )
2209         input_SendEventVout( p_input );
2210
2211     return p_vout;
2212 }
2213
2214 static aout_buffer_t *aout_new_buffer( decoder_t *p_dec, int i_samples )
2215 {
2216     decoder_owner_sys_t *p_owner = p_dec->p_owner;
2217     aout_buffer_t *p_buffer;
2218
2219     if( p_owner->p_aout &&
2220         ( p_dec->fmt_out.audio.i_rate != p_owner->audio.i_rate ||
2221           p_dec->fmt_out.audio.i_original_channels !=
2222               p_owner->audio.i_original_channels ||
2223           p_dec->fmt_out.audio.i_bytes_per_frame !=
2224               p_owner->audio.i_bytes_per_frame ) )
2225     {
2226         audio_output_t *p_aout = p_owner->p_aout;
2227
2228         /* Parameters changed, restart the aout */
2229         vlc_mutex_lock( &p_owner->lock );
2230
2231         DecoderFlushBuffering( p_dec );
2232
2233         aout_DecDelete( p_owner->p_aout );
2234         p_owner->p_aout = NULL;
2235
2236         vlc_mutex_unlock( &p_owner->lock );
2237         input_resource_RequestAout( p_owner->p_resource, p_aout );
2238     }
2239
2240     if( p_owner->p_aout == NULL )
2241     {
2242         const int i_force_dolby = var_InheritInteger( p_dec, "force-dolby-surround" );
2243         audio_sample_format_t format;
2244         audio_output_t *p_aout;
2245         aout_request_vout_t request_vout;
2246
2247         p_dec->fmt_out.audio.i_format = p_dec->fmt_out.i_codec;
2248         p_owner->audio = p_dec->fmt_out.audio;
2249
2250         memcpy( &format, &p_owner->audio, sizeof( audio_sample_format_t ) );
2251         if( i_force_dolby &&
2252             (format.i_original_channels&AOUT_CHAN_PHYSMASK) ==
2253                 (AOUT_CHAN_LEFT|AOUT_CHAN_RIGHT) )
2254         {
2255             if( i_force_dolby == 1 )
2256             {
2257                 format.i_original_channels = format.i_original_channels |
2258                                              AOUT_CHAN_DOLBYSTEREO;
2259             }
2260             else /* i_force_dolby == 2 */
2261             {
2262                 format.i_original_channels = format.i_original_channels &
2263                                              ~AOUT_CHAN_DOLBYSTEREO;
2264             }
2265         }
2266
2267         request_vout.pf_request_vout = aout_request_vout;
2268         request_vout.p_private = p_dec;
2269
2270         assert( p_owner->p_aout == NULL );
2271         p_aout = input_resource_RequestAout( p_owner->p_resource, NULL );
2272         if( p_aout )
2273         {
2274             aout_FormatPrepare( &format );
2275             if( aout_DecNew( p_aout, &format,
2276                              &p_dec->fmt_out.audio_replay_gain,
2277                              &request_vout ) )
2278             {
2279                 input_resource_RequestAout( p_owner->p_resource, p_aout );
2280                 p_aout = NULL;
2281             }
2282         }
2283
2284         vlc_mutex_lock( &p_owner->lock );
2285
2286         p_owner->p_aout = p_aout;
2287         DecoderUpdateFormatLocked( p_dec );
2288
2289         vlc_mutex_unlock( &p_owner->lock );
2290
2291         if( p_owner->p_input != NULL )
2292             input_SendEventAout( p_owner->p_input );
2293
2294         if( p_aout == NULL )
2295         {
2296             msg_Err( p_dec, "failed to create audio output" );
2297             p_dec->b_error = true;
2298             return NULL;
2299         }
2300         p_dec->fmt_out.audio.i_bytes_per_frame =
2301             p_owner->audio.i_bytes_per_frame;
2302     }
2303
2304     p_buffer = aout_DecNewBuffer( p_owner->p_aout, i_samples );
2305
2306     return p_buffer;
2307 }
2308
2309 static picture_t *vout_new_buffer( decoder_t *p_dec )
2310 {
2311     decoder_owner_sys_t *p_owner = p_dec->p_owner;
2312
2313     if( p_owner->p_vout == NULL ||
2314         p_dec->fmt_out.video.i_width != p_owner->video.i_width ||
2315         p_dec->fmt_out.video.i_height != p_owner->video.i_height ||
2316         p_dec->fmt_out.video.i_visible_width != p_owner->video.i_visible_width ||
2317         p_dec->fmt_out.video.i_visible_height != p_owner->video.i_visible_height ||
2318         p_dec->fmt_out.video.i_x_offset != p_owner->video.i_x_offset  ||
2319         p_dec->fmt_out.video.i_y_offset != p_owner->video.i_y_offset  ||
2320         p_dec->fmt_out.i_codec != p_owner->video.i_chroma ||
2321         (int64_t)p_dec->fmt_out.video.i_sar_num * p_owner->video.i_sar_den !=
2322         (int64_t)p_dec->fmt_out.video.i_sar_den * p_owner->video.i_sar_num )
2323     {
2324         vout_thread_t *p_vout;
2325
2326         if( !p_dec->fmt_out.video.i_width ||
2327             !p_dec->fmt_out.video.i_height )
2328         {
2329             /* Can't create a new vout without display size */
2330             return NULL;
2331         }
2332
2333         video_format_t fmt = p_dec->fmt_out.video;
2334         fmt.i_chroma = p_dec->fmt_out.i_codec;
2335         p_owner->video = fmt;
2336
2337         if( vlc_fourcc_IsYUV( fmt.i_chroma ) )
2338         {
2339             const vlc_chroma_description_t *dsc = vlc_fourcc_GetChromaDescription( fmt.i_chroma );
2340             for( int i = 0; dsc && i < dsc->plane_count; i++ )
2341             {
2342                 while( fmt.i_width % dsc->p[i].w.den )
2343                     fmt.i_width++;
2344                 while( fmt.i_height % dsc->p[i].h.den )
2345                     fmt.i_height++;
2346             }
2347         }
2348
2349         if( !fmt.i_visible_width || !fmt.i_visible_height )
2350         {
2351             if( p_dec->fmt_in.video.i_visible_width &&
2352                 p_dec->fmt_in.video.i_visible_height )
2353             {
2354                 fmt.i_visible_width  = p_dec->fmt_in.video.i_visible_width;
2355                 fmt.i_visible_height = p_dec->fmt_in.video.i_visible_height;
2356                 fmt.i_x_offset       = p_dec->fmt_in.video.i_x_offset;
2357                 fmt.i_y_offset       = p_dec->fmt_in.video.i_y_offset;
2358             }
2359             else
2360             {
2361                 fmt.i_visible_width  = fmt.i_width;
2362                 fmt.i_visible_height = fmt.i_height;
2363                 fmt.i_x_offset       = 0;
2364                 fmt.i_y_offset       = 0;
2365             }
2366         }
2367
2368         if( fmt.i_visible_height == 1088 &&
2369             var_CreateGetBool( p_dec, "hdtv-fix" ) )
2370         {
2371             fmt.i_visible_height = 1080;
2372             if( !(fmt.i_sar_num % 136))
2373             {
2374                 fmt.i_sar_num *= 135;
2375                 fmt.i_sar_den *= 136;
2376             }
2377             msg_Warn( p_dec, "Fixing broken HDTV stream (display_height=1088)");
2378         }
2379
2380         if( !fmt.i_sar_num || !fmt.i_sar_den )
2381         {
2382             fmt.i_sar_num = 1;
2383             fmt.i_sar_den = 1;
2384         }
2385
2386         vlc_ureduce( &fmt.i_sar_num, &fmt.i_sar_den,
2387                      fmt.i_sar_num, fmt.i_sar_den, 50000 );
2388
2389         vlc_mutex_lock( &p_owner->lock );
2390
2391         DecoderFlushBuffering( p_dec );
2392
2393         p_vout = p_owner->p_vout;
2394         p_owner->p_vout = NULL;
2395         vlc_mutex_unlock( &p_owner->lock );
2396
2397         unsigned dpb_size;
2398         switch( p_dec->fmt_in.i_codec )
2399         {
2400         case VLC_CODEC_H264:
2401         case VLC_CODEC_DIRAC: /* FIXME valid ? */
2402             dpb_size = 18;
2403             break;
2404         case VLC_CODEC_VP5:
2405         case VLC_CODEC_VP6:
2406         case VLC_CODEC_VP6F:
2407         case VLC_CODEC_VP8:
2408             dpb_size = 3;
2409             break;
2410         default:
2411             dpb_size = 2;
2412             break;
2413         }
2414         p_vout = input_resource_RequestVout( p_owner->p_resource,
2415                                              p_vout, &fmt,
2416                                              dpb_size + 1 + DECODER_MAX_BUFFERING_COUNT,
2417                                              true );
2418         vlc_mutex_lock( &p_owner->lock );
2419         p_owner->p_vout = p_vout;
2420
2421         DecoderUpdateFormatLocked( p_dec );
2422
2423         vlc_mutex_unlock( &p_owner->lock );
2424
2425         if( p_owner->p_input != NULL )
2426             input_SendEventVout( p_owner->p_input );
2427         if( p_vout == NULL )
2428         {
2429             msg_Err( p_dec, "failed to create video output" );
2430             p_dec->b_error = true;
2431             return NULL;
2432         }
2433     }
2434
2435     /* Get a new picture
2436      */
2437     for( ;; )
2438     {
2439         if( DecoderIsExitRequested( p_dec ) || p_dec->b_error )
2440             return NULL;
2441
2442         picture_t *p_picture = vout_GetPicture( p_owner->p_vout );
2443         if( p_picture )
2444             return p_picture;
2445
2446         if( DecoderIsFlushing( p_dec ) )
2447             return NULL;
2448
2449         /* */
2450         DecoderSignalBuffering( p_dec, true );
2451
2452         /* Check the decoder doesn't leak pictures */
2453         vout_FixLeaks( p_owner->p_vout );
2454
2455         /* FIXME add a vout_WaitPictureAvailable (timedwait) */
2456         msleep( VOUT_OUTMEM_SLEEP );
2457     }
2458 }
2459
2460 static void vout_del_buffer( decoder_t *p_dec, picture_t *p_pic )
2461 {
2462     vout_ReleasePicture( p_dec->p_owner->p_vout, p_pic );
2463 }
2464
2465 static void vout_link_picture( decoder_t *p_dec, picture_t *p_pic )
2466 {
2467     vout_HoldPicture( p_dec->p_owner->p_vout, p_pic );
2468 }
2469
2470 static void vout_unlink_picture( decoder_t *p_dec, picture_t *p_pic )
2471 {
2472     vout_ReleasePicture( p_dec->p_owner->p_vout, p_pic );
2473 }
2474
2475 static subpicture_t *spu_new_buffer( decoder_t *p_dec,
2476                                      const subpicture_updater_t *p_updater )
2477 {
2478     decoder_owner_sys_t *p_owner = p_dec->p_owner;
2479     vout_thread_t *p_vout = NULL;
2480     subpicture_t *p_subpic;
2481     int i_attempts = 30;
2482
2483     while( i_attempts-- )
2484     {
2485         if( DecoderIsExitRequested( p_dec ) || p_dec->b_error )
2486             break;
2487
2488         p_vout = input_resource_HoldVout( p_owner->p_resource );
2489         if( p_vout )
2490             break;
2491
2492         msleep( DECODER_SPU_VOUT_WAIT_DURATION );
2493     }
2494
2495     if( !p_vout )
2496     {
2497         msg_Warn( p_dec, "no vout found, dropping subpicture" );
2498         return NULL;
2499     }
2500
2501     if( p_owner->p_spu_vout != p_vout )
2502     {
2503         vlc_mutex_lock( &p_owner->lock );
2504
2505         DecoderFlushBuffering( p_dec );
2506
2507         vlc_mutex_unlock( &p_owner->lock );
2508
2509         p_owner->i_spu_channel = vout_RegisterSubpictureChannel( p_vout );
2510         p_owner->i_spu_order = 0;
2511         p_owner->p_spu_vout = p_vout;
2512     }
2513
2514     p_subpic = subpicture_New( p_updater );
2515     if( p_subpic )
2516     {
2517         p_subpic->i_channel = p_owner->i_spu_channel;
2518         p_subpic->i_order = p_owner->i_spu_order++;
2519         p_subpic->b_subtitle = true;
2520     }
2521
2522     vlc_object_release( p_vout );
2523
2524     return p_subpic;
2525 }
2526
2527 static void spu_del_buffer( decoder_t *p_dec, subpicture_t *p_subpic )
2528 {
2529     decoder_owner_sys_t *p_owner = p_dec->p_owner;
2530     vout_thread_t *p_vout = NULL;
2531
2532     p_vout = input_resource_HoldVout( p_owner->p_resource );
2533     if( !p_vout || p_owner->p_spu_vout != p_vout )
2534     {
2535         if( p_vout )
2536             vlc_object_release( p_vout );
2537         msg_Warn( p_dec, "no vout found, leaking subpicture" );
2538         return;
2539     }
2540
2541     subpicture_Delete( p_subpic );
2542
2543     vlc_object_release( p_vout );
2544 }
2545