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