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