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