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