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