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