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