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