]> git.sesse.net Git - vlc/blob - src/input/es_out.c
Constify es_out_Add es_format_t* argument.
[vlc] / src / input / es_out.c
1 /*****************************************************************************
2  * es_out.c: Es Out handler for input.
3  *****************************************************************************
4  * Copyright (C) 2003-2004 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Jean-Paul Saman <jpsaman #_at_# m2x dot nl>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <stdio.h>
33 #include <assert.h>
34 #include <vlc_common.h>
35
36 #include <vlc_input.h>
37 #include <vlc_es_out.h>
38 #include <vlc_block.h>
39 #include <vlc_aout.h>
40
41 #include "input_internal.h"
42 #include "clock.h"
43 #include "decoder.h"
44 #include "es_out.h"
45
46 #include "../stream_output/stream_output.h"
47
48 #include <vlc_iso_lang.h>
49 /* FIXME we should find a better way than including that */
50 #include "../text/iso-639_def.h"
51
52 /*****************************************************************************
53  * Local prototypes
54  *****************************************************************************/
55 typedef struct
56 {
57     /* Program ID */
58     int i_id;
59
60     /* Number of es for this pgrm */
61     int i_es;
62
63     bool b_selected;
64
65     /* Clock for this program */
66     input_clock_t *p_clock;
67
68     char    *psz_name;
69     char    *psz_now_playing;
70     char    *psz_publisher;
71
72     vlc_epg_t *p_epg;
73 } es_out_pgrm_t;
74
75 struct es_out_id_t
76 {
77     /* ES ID */
78     int       i_id;
79     es_out_pgrm_t *p_pgrm;
80
81     /* Channel in the track type */
82     int         i_channel;
83     es_format_t fmt;
84     char        *psz_language;
85     char        *psz_language_code;
86
87     decoder_t   *p_dec;
88     decoder_t   *p_dec_record;
89
90     /* Fields for Video with CC */
91     bool  pb_cc_present[4];
92     es_out_id_t  *pp_cc_es[4];
93
94     /* Field for CC track from a master video */
95     es_out_id_t *p_master;
96 };
97
98 struct es_out_sys_t
99 {
100     input_thread_t *p_input;
101
102     /* */
103     vlc_mutex_t   lock;
104
105     /* all programs */
106     int           i_pgrm;
107     es_out_pgrm_t **pgrm;
108     es_out_pgrm_t **pp_selected_pgrm; /* --programs */
109     es_out_pgrm_t *p_pgrm;  /* Master program */
110
111     /* all es */
112     int         i_id;
113     int         i_es;
114     es_out_id_t **es;
115
116     /* mode gestion */
117     bool  b_active;
118     int         i_mode;
119
120     /* es count */
121     int         i_audio;
122     int         i_video;
123     int         i_sub;
124
125     /* es to select */
126     int         i_audio_last, i_audio_id;
127     int         i_sub_last, i_sub_id;
128     int         i_default_sub_id;   /* As specified in container; if applicable */
129     char        **ppsz_audio_language;
130     char        **ppsz_sub_language;
131
132     /* current main es */
133     es_out_id_t *p_es_audio;
134     es_out_id_t *p_es_video;
135     es_out_id_t *p_es_sub;
136
137     /* delay */
138     int64_t i_audio_delay;
139     int64_t i_spu_delay;
140
141     /* Rate used for clock */
142     int         i_rate;
143
144     /* */
145     bool        b_paused;
146
147     /* Current preroll */
148     mtime_t     i_preroll_end;
149
150     /* Used for buffering */
151     bool        b_buffering;
152     mtime_t     i_buffering_extra_initial;
153     mtime_t     i_buffering_extra_stream;
154     mtime_t     i_buffering_extra_system;
155
156     /* Record */
157     sout_instance_t *p_sout_record;
158 };
159
160 static es_out_id_t *EsOutAdd    ( es_out_t *, const es_format_t * );
161 static int          EsOutSend   ( es_out_t *, es_out_id_t *, block_t * );
162 static void         EsOutDel    ( es_out_t *, es_out_id_t * );
163 static int          EsOutControl( es_out_t *, int i_query, va_list );
164 static void         EsOutDelete ( es_out_t * );
165
166 static void         EsOutSelect( es_out_t *, es_out_id_t *es, bool b_force );
167 static void         EsOutAddInfo( es_out_t *, es_out_id_t *es );
168 static int          EsOutSetRecord(  es_out_t *, bool b_record );
169
170 static bool EsIsSelected( es_out_id_t *es );
171 static void EsSelect( es_out_t *out, es_out_id_t *es );
172 static void EsUnselect( es_out_t *out, es_out_id_t *es, bool b_update );
173 static void EsOutDecoderChangeDelay( es_out_t *out, es_out_id_t *p_es );
174 static void EsOutDecodersChangePause( es_out_t *out, bool b_paused, mtime_t i_date );
175 static void EsOutProgramChangePause( es_out_t *out, bool b_paused, mtime_t i_date );
176 static void EsOutProgramsChangeRate( es_out_t *out );
177 static void EsOutDecodersStopBuffering( es_out_t *out, bool b_forced );
178 static char *LanguageGetName( const char *psz_code );
179 static char *LanguageGetCode( const char *psz_lang );
180 static char **LanguageSplit( const char *psz_langs );
181 static int LanguageArrayIndex( char **ppsz_langs, char *psz_lang );
182
183 static char *EsOutProgramGetMetaName( es_out_pgrm_t *p_pgrm );
184
185 static const vlc_fourcc_t EsOutFourccClosedCaptions[4] = {
186     VLC_FOURCC('c', 'c', '1', ' '),
187     VLC_FOURCC('c', 'c', '2', ' '),
188     VLC_FOURCC('c', 'c', '3', ' '),
189     VLC_FOURCC('c', 'c', '4', ' '),
190 };
191 static inline int EsOutGetClosedCaptionsChannel( vlc_fourcc_t fcc )
192 {
193     int i;
194     for( i = 0; i < 4; i++ )
195     {
196         if( fcc == EsOutFourccClosedCaptions[i] )
197             return i;
198     }
199     return -1;
200 }
201
202
203 /*****************************************************************************
204  * input_EsOutNew:
205  *****************************************************************************/
206 es_out_t *input_EsOutNew( input_thread_t *p_input, int i_rate )
207 {
208     vlc_value_t  val;
209     int i;
210
211     es_out_t     *out = malloc( sizeof( *out ) );
212     if( !out )
213         return NULL;
214
215     es_out_sys_t *p_sys = malloc( sizeof( *p_sys ) );
216     if( !p_sys )
217     {
218         free( out );
219         return NULL;
220     }
221
222     out->pf_add     = EsOutAdd;
223     out->pf_send    = EsOutSend;
224     out->pf_del     = EsOutDel;
225     out->pf_control = EsOutControl;
226     out->pf_destroy = EsOutDelete;
227     out->p_sys      = p_sys;
228     out->b_sout     = p_input->p->p_sout != NULL;
229
230
231     vlc_mutex_init_recursive( &p_sys->lock );
232     p_sys->p_input = p_input;
233
234     p_sys->b_active = false;
235     p_sys->i_mode   = ES_OUT_MODE_AUTO;
236
237
238     TAB_INIT( p_sys->i_pgrm, p_sys->pgrm );
239     p_sys->p_pgrm   = NULL;
240
241     p_sys->i_id    = 0;
242
243     TAB_INIT( p_sys->i_es, p_sys->es );
244
245     p_sys->i_audio = 0;
246     p_sys->i_video = 0;
247     p_sys->i_sub   = 0;
248
249     /* */
250     var_Get( p_input, "audio-track", &val );
251     p_sys->i_audio_last = val.i_int;
252
253     var_Get( p_input, "sub-track", &val );
254     p_sys->i_sub_last = val.i_int;
255
256     p_sys->i_default_sub_id   = -1;
257
258     if( !p_input->b_preparsing )
259     {
260         var_Get( p_input, "audio-language", &val );
261         p_sys->ppsz_audio_language = LanguageSplit(val.psz_string);
262         if( p_sys->ppsz_audio_language )
263         {
264             for( i = 0; p_sys->ppsz_audio_language[i]; i++ )
265                 msg_Dbg( p_input, "selected audio language[%d] %s",
266                          i, p_sys->ppsz_audio_language[i] );
267         }
268         free( val.psz_string );
269
270         var_Get( p_input, "sub-language", &val );
271         p_sys->ppsz_sub_language = LanguageSplit(val.psz_string);
272         if( p_sys->ppsz_sub_language )
273         {
274             for( i = 0; p_sys->ppsz_sub_language[i]; i++ )
275                 msg_Dbg( p_input, "selected subtitle language[%d] %s",
276                          i, p_sys->ppsz_sub_language[i] );
277         }
278         free( val.psz_string );
279     }
280     else
281     {
282         p_sys->ppsz_sub_language = NULL;
283         p_sys->ppsz_audio_language = NULL;
284     }
285
286     var_Get( p_input, "audio-track-id", &val );
287     p_sys->i_audio_id = val.i_int;
288
289     var_Get( p_input, "sub-track-id", &val );
290     p_sys->i_sub_id = val.i_int;
291
292     p_sys->p_es_audio = NULL;
293     p_sys->p_es_video = NULL;
294     p_sys->p_es_sub   = NULL;
295
296     p_sys->i_audio_delay= 0;
297     p_sys->i_spu_delay  = 0;
298
299     p_sys->b_paused = false;
300
301     p_sys->i_rate = i_rate;
302
303     p_sys->b_buffering = true;
304     p_sys->i_buffering_extra_initial = 0;
305     p_sys->i_buffering_extra_stream = 0;
306     p_sys->i_buffering_extra_system = 0;
307     p_sys->i_preroll_end = -1;
308
309     p_sys->p_sout_record = NULL;
310
311     return out;
312 }
313
314 /*****************************************************************************
315  *
316  *****************************************************************************/
317 static void EsOutDelete( es_out_t *out )
318 {
319     es_out_sys_t *p_sys = out->p_sys;
320     int i;
321
322     if( p_sys->p_sout_record )
323         EsOutSetRecord( out, false );
324
325     for( i = 0; i < p_sys->i_es; i++ )
326     {
327         if( p_sys->es[i]->p_dec )
328             input_DecoderDelete( p_sys->es[i]->p_dec );
329
330         free( p_sys->es[i]->psz_language );
331         free( p_sys->es[i]->psz_language_code );
332         es_format_Clean( &p_sys->es[i]->fmt );
333
334         free( p_sys->es[i] );
335     }
336     if( p_sys->ppsz_audio_language )
337     {
338         for( i = 0; p_sys->ppsz_audio_language[i]; i++ )
339             free( p_sys->ppsz_audio_language[i] );
340         free( p_sys->ppsz_audio_language );
341     }
342     if( p_sys->ppsz_sub_language )
343     {
344         for( i = 0; p_sys->ppsz_sub_language[i]; i++ )
345             free( p_sys->ppsz_sub_language[i] );
346         free( p_sys->ppsz_sub_language );
347     }
348     free( p_sys->es );
349
350     /* FIXME duplicate work EsOutProgramDel (but we cannot use it) add a EsOutProgramClean ? */
351     for( i = 0; i < p_sys->i_pgrm; i++ )
352     {
353         es_out_pgrm_t *p_pgrm = p_sys->pgrm[i];
354         input_clock_Delete( p_pgrm->p_clock );
355         free( p_pgrm->psz_now_playing );
356         free( p_pgrm->psz_publisher );
357         free( p_pgrm->psz_name );
358         if( p_pgrm->p_epg )
359             vlc_epg_Delete( p_pgrm->p_epg );
360
361         free( p_pgrm );
362     }
363     TAB_CLEAN( p_sys->i_pgrm, p_sys->pgrm );
364     vlc_mutex_destroy( &p_sys->lock );
365
366     free( p_sys );
367     free( out );
368 }
369
370 static mtime_t EsOutGetWakeup( es_out_t *out )
371 {
372     es_out_sys_t   *p_sys = out->p_sys;
373     input_thread_t *p_input = p_sys->p_input;
374
375     if( !p_sys->p_pgrm )
376         return 0;
377
378     /* We do not have a wake up date if the input cannot have its speed
379      * controlled or sout is imposing its own or while buffering
380      *
381      * FIXME for !p_input->b_can_pace_control a wkeup time is still needed to avoid too strong buffering */
382     if( !p_input->b_can_pace_control ||
383         p_input->p->b_out_pace_control ||
384         p_sys->b_buffering )
385         return 0;
386
387     return input_clock_GetWakeup( p_sys->p_pgrm->p_clock );
388 }
389
390 static es_out_id_t *EsOutGetFromID( es_out_t *out, int i_id )
391 {
392     int i;
393     if( i_id < 0 )
394     {
395         /* Special HACK, -i_id is the cat of the stream */
396         return (es_out_id_t*)((uint8_t*)NULL-i_id);
397     }
398
399     for( i = 0; i < out->p_sys->i_es; i++ )
400     {
401         if( out->p_sys->es[i]->i_id == i_id )
402             return out->p_sys->es[i];
403     }
404     return NULL;
405 }
406
407 static bool EsOutDecodersIsEmpty( es_out_t *out )
408 {
409     es_out_sys_t      *p_sys = out->p_sys;
410     int i;
411
412     if( p_sys->b_buffering && p_sys->p_pgrm )
413     {
414         EsOutDecodersStopBuffering( out, true );
415         if( p_sys->b_buffering )
416             return true;
417     }
418
419     for( i = 0; i < p_sys->i_es; i++ )
420     {
421         es_out_id_t *es = p_sys->es[i];
422
423         if( es->p_dec && !input_DecoderIsEmpty( es->p_dec ) )
424             return false;
425         if( es->p_dec_record && !input_DecoderIsEmpty( es->p_dec_record ) )
426             return false;
427     }
428     return true;
429 }
430
431 static void EsOutSetDelay( es_out_t *out, int i_cat, int64_t i_delay )
432 {
433     es_out_sys_t *p_sys = out->p_sys;
434
435     if( i_cat == AUDIO_ES )
436         p_sys->i_audio_delay = i_delay;
437     else if( i_cat == SPU_ES )
438         p_sys->i_spu_delay = i_delay;
439
440     for( int i = 0; i < p_sys->i_es; i++ )
441         EsOutDecoderChangeDelay( out, p_sys->es[i] );
442 }
443
444 static int EsOutSetRecord(  es_out_t *out, bool b_record )
445 {
446     es_out_sys_t   *p_sys = out->p_sys;
447     input_thread_t *p_input = p_sys->p_input;
448
449     assert( ( b_record && !p_sys->p_sout_record ) || ( !b_record && p_sys->p_sout_record ) );
450
451     if( b_record )
452     {
453         char *psz_path = var_CreateGetString( p_input, "input-record-path" );
454         if( !psz_path || *psz_path == '\0' )
455         {
456             free( psz_path );
457             psz_path = strdup( config_GetHomeDir() );
458         }
459
460         char *psz_sout = NULL;  // TODO conf
461
462         if( !psz_sout && psz_path )
463         {
464             char *psz_file = input_CreateFilename( VLC_OBJECT(p_input), psz_path, INPUT_RECORD_PREFIX, NULL );
465             if( psz_file )
466             {
467                 if( asprintf( &psz_sout, "#record{dst-prefix='%s'}", psz_file ) < 0 )
468                     psz_sout = NULL;
469                 free( psz_file );
470             }
471         }
472         free( psz_path );
473
474         if( !psz_sout )
475             return VLC_EGENERIC;
476
477 #ifdef ENABLE_SOUT
478         p_sys->p_sout_record = sout_NewInstance( p_input, psz_sout );
479 #endif
480         free( psz_sout );
481
482         if( !p_sys->p_sout_record )
483             return VLC_EGENERIC;
484
485         for( int i = 0; i < p_sys->i_es; i++ )
486         {
487             es_out_id_t *p_es = p_sys->es[i];
488
489             if( !p_es->p_dec || p_es->p_master )
490                 continue;
491
492             p_es->p_dec_record = input_DecoderNew( p_input, &p_es->fmt, p_es->p_pgrm->p_clock, p_sys->p_sout_record );
493             if( p_es->p_dec_record && p_sys->b_buffering )
494                 input_DecoderStartBuffering( p_es->p_dec_record );
495         }
496     }
497     else
498     {
499         for( int i = 0; i < p_sys->i_es; i++ )
500         {
501             es_out_id_t *p_es = p_sys->es[i];
502
503             if( !p_es->p_dec_record )
504                 continue;
505
506             input_DecoderDelete( p_es->p_dec_record );
507             p_es->p_dec_record = NULL;
508         }
509 #ifdef ENABLE_SOUT
510         sout_DeleteInstance( p_sys->p_sout_record );
511 #endif
512         p_sys->p_sout_record = NULL;
513     }
514
515     return VLC_SUCCESS;
516 }
517 static void EsOutChangePause( es_out_t *out, bool b_paused, mtime_t i_date )
518 {
519     es_out_sys_t *p_sys = out->p_sys;
520
521     /* XXX the order is important */
522     if( b_paused )
523     {
524         EsOutDecodersChangePause( out, true, i_date );
525         EsOutProgramChangePause( out, true, i_date );
526     }
527     else
528     {
529         if( p_sys->i_buffering_extra_initial > 0 )
530         {
531             mtime_t i_stream_start;
532             mtime_t i_system_start;
533             mtime_t i_stream_duration;
534             mtime_t i_system_duration;
535             int i_ret;
536             i_ret = input_clock_GetState( p_sys->p_pgrm->p_clock,
537                                           &i_stream_start, &i_system_start,
538                                           &i_stream_duration, &i_system_duration );
539             if( !i_ret )
540             {
541                 /* FIXME pcr != exactly what wanted */
542                 const mtime_t i_used = /*(i_stream_duration - p_sys->p_input->i_pts_delay)*/ p_sys->i_buffering_extra_system - p_sys->i_buffering_extra_initial;
543                 i_date -= i_used;
544             }
545             p_sys->i_buffering_extra_initial = 0;
546             p_sys->i_buffering_extra_stream = 0;
547             p_sys->i_buffering_extra_system = 0;
548         }
549         EsOutProgramChangePause( out, false, i_date );
550         EsOutDecodersChangePause( out, false, i_date );
551
552         EsOutProgramsChangeRate( out );
553     }
554     p_sys->b_paused = b_paused;
555 }
556
557 static void EsOutChangeRate( es_out_t *out, int i_rate )
558 {
559     es_out_sys_t      *p_sys = out->p_sys;
560
561     p_sys->i_rate = i_rate;
562
563     if( !p_sys->b_paused )
564         EsOutProgramsChangeRate( out );
565 }
566
567 static void EsOutChangePosition( es_out_t *out )
568 {
569     es_out_sys_t      *p_sys = out->p_sys;
570
571     for( int i = 0; i < p_sys->i_es; i++ )
572     {
573         es_out_id_t *p_es = p_sys->es[i];
574
575         if( !p_es->p_dec )
576             continue;
577
578         input_DecoderStartBuffering( p_es->p_dec );
579
580         if( p_es->p_dec_record )
581             input_DecoderStartBuffering( p_es->p_dec );
582     }
583
584     for( int i = 0; i < p_sys->i_pgrm; i++ )
585         input_clock_Reset( p_sys->pgrm[i]->p_clock );
586
587     p_sys->b_buffering = true;
588     p_sys->i_buffering_extra_initial = 0;
589     p_sys->i_buffering_extra_stream = 0;
590     p_sys->i_buffering_extra_system = 0;
591     p_sys->i_preroll_end = -1;
592 }
593
594
595
596 static void EsOutDecodersStopBuffering( es_out_t *out, bool b_forced )
597 {
598     es_out_sys_t *p_sys = out->p_sys;
599     int i_ret;
600
601     mtime_t i_stream_start;
602     mtime_t i_system_start;
603     mtime_t i_stream_duration;
604     mtime_t i_system_duration;
605     i_ret = input_clock_GetState( p_sys->p_pgrm->p_clock,
606                                   &i_stream_start, &i_system_start,
607                                   &i_stream_duration, &i_system_duration );
608     assert( !i_ret || b_forced );
609     if( i_ret )
610         return;
611
612     mtime_t i_preroll_duration = 0;
613     if( p_sys->i_preroll_end >= 0 )
614         i_preroll_duration = __MAX( p_sys->i_preroll_end - i_stream_start, 0 );
615
616     const mtime_t i_buffering_duration = p_sys->p_input->i_pts_delay +
617                                          i_preroll_duration +
618                                          p_sys->i_buffering_extra_stream;
619
620     if( i_stream_duration <= i_buffering_duration && !b_forced )
621     {
622         msg_Dbg( p_sys->p_input, "Buffering %d%%",
623                  (int)(100 * i_stream_duration / i_buffering_duration ) );
624         return;
625     }
626
627     msg_Dbg( p_sys->p_input, "Stream buffering done (%d ms in %d ms)",
628               (int)(i_stream_duration/1000), (int)(i_system_duration/1000) );
629     p_sys->b_buffering = false;
630     p_sys->i_preroll_end = -1;
631
632     if( p_sys->i_buffering_extra_initial > 0 )
633     {
634         /* FIXME wrong ? */
635         return;
636     }
637
638     const mtime_t i_decoder_buffering_start = mdate();
639     for( int i = 0; i < p_sys->i_es; i++ )
640     {
641         es_out_id_t *p_es = p_sys->es[i];
642
643         if( !p_es->p_dec )
644             continue;
645         input_DecoderWaitBuffering( p_es->p_dec );
646         if( p_es->p_dec_record )
647             input_DecoderWaitBuffering( p_es->p_dec_record );
648     }
649
650     msg_Dbg( p_sys->p_input, "Decoder buffering done in %d ms",
651               (int)(mdate() - i_decoder_buffering_start)/1000 );
652
653     const mtime_t i_ts_delay = 10*1000 + /* FIXME CLEANUP thread wake up time*/
654                                mdate();
655     //msg_Dbg( p_sys->p_input, "==> %lld", i_ts_delay - p_sys->p_input->i_pts_delay );
656     input_clock_ChangeSystemOrigin( p_sys->p_pgrm->p_clock, i_ts_delay - i_buffering_duration );
657
658     for( int i = 0; i < p_sys->i_es; i++ )
659     {
660         es_out_id_t *p_es = p_sys->es[i];
661
662         if( !p_es->p_dec )
663             continue;
664
665         input_DecoderStopBuffering( p_es->p_dec );
666         if( p_es->p_dec_record )
667             input_DecoderStopBuffering( p_es->p_dec );
668     }
669 }
670 static void EsOutDecodersChangePause( es_out_t *out, bool b_paused, mtime_t i_date )
671 {
672     es_out_sys_t *p_sys = out->p_sys;
673
674     /* Pause decoders first */
675     for( int i = 0; i < p_sys->i_es; i++ )
676     {
677         es_out_id_t *es = p_sys->es[i];
678
679         if( es->p_dec )
680         {
681             input_DecoderChangePause( es->p_dec, b_paused, i_date );
682             if( es->p_dec_record )
683                 input_DecoderChangePause( es->p_dec_record, b_paused, i_date );
684         }
685     }
686 }
687 static void EsOutProgramChangePause( es_out_t *out, bool b_paused, mtime_t i_date )
688 {
689     es_out_sys_t *p_sys = out->p_sys;
690
691     for( int i = 0; i < p_sys->i_pgrm; i++ )
692         input_clock_ChangePause( p_sys->pgrm[i]->p_clock, b_paused, i_date );
693 }
694
695 static void EsOutDecoderChangeDelay( es_out_t *out, es_out_id_t *p_es )
696 {
697     es_out_sys_t *p_sys = out->p_sys;
698
699     mtime_t i_delay = 0;
700     if( p_es->fmt.i_cat == AUDIO_ES )
701         i_delay = p_sys->i_audio_delay;
702     else if( p_es->fmt.i_cat == SPU_ES )
703         i_delay = p_sys->i_spu_delay;
704
705     if( i_delay != 0 )
706     {
707         if( p_es->p_dec )
708             input_DecoderChangeDelay( p_es->p_dec, i_delay );
709         if( p_es->p_dec_record )
710             input_DecoderChangeDelay( p_es->p_dec_record, i_delay );
711     }
712 }
713 static void EsOutProgramsChangeRate( es_out_t *out )
714 {
715     es_out_sys_t      *p_sys = out->p_sys;
716
717     for( int i = 0; i < p_sys->i_pgrm; i++ )
718         input_clock_ChangeRate( p_sys->pgrm[i]->p_clock, p_sys->i_rate );
719 }
720
721 static void EsOutFrameNext( es_out_t *out )
722 {
723     es_out_sys_t *p_sys = out->p_sys;
724     es_out_id_t *p_es_video = NULL;
725
726     if( p_sys->b_buffering )
727     {
728         msg_Warn( p_sys->p_input, "buffering, ignoring 'frame next'" );
729         return;
730     }
731
732     assert( p_sys->b_paused );
733
734     for( int i = 0; i < p_sys->i_es; i++ )
735     {
736         es_out_id_t *p_es = p_sys->es[i];
737
738         if( p_es->fmt.i_cat == VIDEO_ES && p_es->p_dec )
739         {
740             p_es_video = p_es;
741             break;
742         }
743     }
744
745     if( !p_es_video )
746     {
747         msg_Warn( p_sys->p_input, "No video track selected, ignoring 'frame next'" );
748         return;
749     }
750
751     mtime_t i_duration;
752     input_DecoderFrameNext( p_es_video->p_dec, &i_duration );
753
754     msg_Dbg( out->p_sys->p_input, "EsOutFrameNext consummed %d ms", (int)(i_duration/1000) );
755
756     if( i_duration <= 0 )
757         i_duration = 40*1000;
758
759     /* FIXME it is not a clean way ? */
760     if( p_sys->i_buffering_extra_initial <= 0 )
761     {
762         mtime_t i_stream_start;
763         mtime_t i_system_start;
764         mtime_t i_stream_duration;
765         mtime_t i_system_duration;
766         int i_ret;
767
768         i_ret = input_clock_GetState( p_sys->p_pgrm->p_clock,
769                                       &i_stream_start, &i_system_start,
770                                       &i_stream_duration, &i_system_duration );
771         if( i_ret )
772             return;
773
774         p_sys->i_buffering_extra_initial = 1 + i_stream_duration - p_sys->p_input->i_pts_delay; /* FIXME < 0 ? */
775         p_sys->i_buffering_extra_system =
776         p_sys->i_buffering_extra_stream = p_sys->i_buffering_extra_initial;
777     }
778
779     const int i_rate = input_clock_GetRate( p_sys->p_pgrm->p_clock );
780
781     p_sys->b_buffering = true;
782     p_sys->i_buffering_extra_system += i_duration;
783     p_sys->i_buffering_extra_stream = p_sys->i_buffering_extra_initial +
784                                       ( p_sys->i_buffering_extra_system - p_sys->i_buffering_extra_initial ) *
785                                                 INPUT_RATE_DEFAULT / i_rate;
786
787     p_sys->i_preroll_end = -1;
788 }
789
790
791
792 static void EsOutESVarUpdateGeneric( es_out_t *out, int i_id, es_format_t *fmt, const char *psz_language,
793                                      bool b_delete )
794 {
795     es_out_sys_t      *p_sys = out->p_sys;
796     input_thread_t    *p_input = p_sys->p_input;
797     const  bool b_teletext = fmt->i_cat == SPU_ES && fmt->i_codec == VLC_FOURCC( 't', 'e', 'l', 'x' );
798     vlc_value_t       val, text;
799
800     const char *psz_var;
801
802     if( fmt->i_cat == AUDIO_ES )
803         psz_var = "audio-es";
804     else if( fmt->i_cat == VIDEO_ES )
805         psz_var = "video-es";
806     else if( fmt->i_cat == SPU_ES )
807         psz_var = "spu-es";
808     else
809         return;
810
811     if( b_delete )
812     {
813         if( b_teletext )
814             var_SetInteger( p_sys->p_input, "teletext-es", -1 );
815
816         val.i_int = i_id;
817         var_Change( p_input, psz_var, VLC_VAR_DELCHOICE, &val, NULL );
818
819         var_SetBool( p_sys->p_input, "intf-change", true );
820         return;
821     }
822
823     /* Get the number of ES already added */
824     var_Change( p_input, psz_var, VLC_VAR_CHOICESCOUNT, &val, NULL );
825     if( val.i_int == 0 )
826     {
827         vlc_value_t val2;
828
829         /* First one, we need to add the "Disable" choice */
830         val2.i_int = -1; text.psz_string = _("Disable");
831         var_Change( p_input, psz_var, VLC_VAR_ADDCHOICE, &val2, &text );
832         val.i_int++;
833     }
834
835     /* Take care of the ES description */
836     if( fmt->psz_description && *fmt->psz_description )
837     {
838         if( psz_language && *psz_language )
839         {
840             text.psz_string = malloc( strlen( fmt->psz_description) +
841                                       strlen( psz_language ) + 10 );
842             sprintf( text.psz_string, "%s - [%s]", fmt->psz_description,
843                                                    psz_language );
844         }
845         else text.psz_string = strdup( fmt->psz_description );
846     }
847     else
848     {
849         if( psz_language && *psz_language )
850         {
851             if( asprintf( &text.psz_string, "%s %i - [%s]", _( "Track" ), val.i_int, psz_language ) == -1 )
852                 text.psz_string = NULL;
853         }
854         else
855         {
856             if( asprintf( &text.psz_string, "%s %i", _( "Track" ), val.i_int ) == -1 )
857                 text.psz_string = NULL;
858         }
859     }
860
861     val.i_int = i_id;
862     var_Change( p_input, psz_var, VLC_VAR_ADDCHOICE, &val, &text );
863
864     free( text.psz_string );
865
866     if( b_teletext )
867     {
868         if( var_GetInteger( p_sys->p_input, "teletext-es" ) < 0 )
869             var_SetInteger( p_sys->p_input, "teletext-es", i_id );
870     }
871
872     var_SetBool( p_sys->p_input, "intf-change", true );
873 }
874
875 static void EsOutESVarUpdate( es_out_t *out, es_out_id_t *es,
876                               bool b_delete )
877 {
878     EsOutESVarUpdateGeneric( out, es->i_id, &es->fmt, es->psz_language, b_delete );
879 }
880
881 /* EsOutProgramSelect:
882  *  Select a program and update the object variable
883  */
884 static void EsOutProgramSelect( es_out_t *out, es_out_pgrm_t *p_pgrm )
885 {
886     es_out_sys_t      *p_sys = out->p_sys;
887     input_thread_t    *p_input = p_sys->p_input;
888     vlc_value_t       val;
889     int               i;
890
891     if( p_sys->p_pgrm == p_pgrm )
892         return; /* Nothing to do */
893
894     if( p_sys->p_pgrm )
895     {
896         es_out_pgrm_t *old = p_sys->p_pgrm;
897         msg_Dbg( p_input, "unselecting program id=%d", old->i_id );
898
899         for( i = 0; i < p_sys->i_es; i++ )
900         {
901             if( p_sys->es[i]->p_pgrm == old && EsIsSelected( p_sys->es[i] ) &&
902                 p_sys->i_mode != ES_OUT_MODE_ALL )
903                 EsUnselect( out, p_sys->es[i], true );
904         }
905
906         p_sys->p_es_audio = NULL;
907         p_sys->p_es_sub = NULL;
908         p_sys->p_es_video = NULL;
909     }
910
911     msg_Dbg( p_input, "selecting program id=%d", p_pgrm->i_id );
912
913     /* Mark it selected */
914     p_pgrm->b_selected = true;
915
916     /* Switch master stream */
917     p_sys->p_pgrm = p_pgrm;
918
919     /* Update "program" */
920     val.i_int = p_pgrm->i_id;
921     var_Change( p_input, "program", VLC_VAR_SETVALUE, &val, NULL );
922
923     /* Update "es-*" */
924     var_Change( p_input, "audio-es", VLC_VAR_CLEARCHOICES, NULL, NULL );
925     var_Change( p_input, "video-es", VLC_VAR_CLEARCHOICES, NULL, NULL );
926     var_Change( p_input, "spu-es",   VLC_VAR_CLEARCHOICES, NULL, NULL );
927     var_SetInteger( p_input, "teletext-es", -1 );
928     for( i = 0; i < p_sys->i_es; i++ )
929     {
930         if( p_sys->es[i]->p_pgrm == p_sys->p_pgrm )
931             EsOutESVarUpdate( out, p_sys->es[i], false );
932         EsOutSelect( out, p_sys->es[i], false );
933     }
934
935     /* Update now playing */
936     input_item_SetNowPlaying( p_input->p->input.p_item,
937                               p_pgrm->psz_now_playing );
938     input_item_SetPublisher( p_input->p->input.p_item,
939                              p_pgrm->psz_publisher );
940
941     var_SetBool( p_sys->p_input, "intf-change", true );
942 }
943
944 /* EsOutAddProgram:
945  *  Add a program
946  */
947 static es_out_pgrm_t *EsOutProgramAdd( es_out_t *out, int i_group )
948 {
949     es_out_sys_t      *p_sys = out->p_sys;
950     input_thread_t    *p_input = p_sys->p_input;
951     vlc_value_t       val;
952
953     es_out_pgrm_t *p_pgrm = malloc( sizeof( es_out_pgrm_t ) );
954     if( !p_pgrm )
955         return NULL;
956
957     /* Init */
958     p_pgrm->i_id = i_group;
959     p_pgrm->i_es = 0;
960     p_pgrm->b_selected = false;
961     p_pgrm->psz_name = NULL;
962     p_pgrm->psz_now_playing = NULL;
963     p_pgrm->psz_publisher = NULL;
964     p_pgrm->p_epg = NULL;
965     p_pgrm->p_clock = input_clock_New( p_input->p->input.i_cr_average, p_sys->i_rate );
966     if( !p_pgrm->p_clock )
967     {
968         free( p_pgrm );
969         return NULL;
970     }
971
972     /* Append it */
973     TAB_APPEND( p_sys->i_pgrm, p_sys->pgrm, p_pgrm );
974
975     /* Update "program" variable */
976     val.i_int = i_group;
977     var_Change( p_input, "program", VLC_VAR_ADDCHOICE, &val, NULL );
978
979     if( i_group == var_GetInteger( p_input, "program" ) )
980     {
981         EsOutProgramSelect( out, p_pgrm );
982     }
983     else
984     {
985         var_SetBool( p_sys->p_input, "intf-change", true );
986     }
987     return p_pgrm;
988 }
989
990 /* EsOutDelProgram:
991  *  Delete a program
992  */
993 static int EsOutProgramDel( es_out_t *out, int i_group )
994 {
995     es_out_sys_t      *p_sys = out->p_sys;
996     input_thread_t    *p_input = p_sys->p_input;
997     es_out_pgrm_t     *p_pgrm = NULL;
998     vlc_value_t       val;
999     int               i;
1000
1001     for( i = 0; i < p_sys->i_pgrm; i++ )
1002     {
1003         if( p_sys->pgrm[i]->i_id == i_group )
1004         {
1005             p_pgrm = p_sys->pgrm[i];
1006             break;
1007         }
1008     }
1009
1010     if( p_pgrm == NULL )
1011         return VLC_EGENERIC;
1012
1013     if( p_pgrm->i_es )
1014     {
1015         msg_Dbg( p_input, "can't delete program %d which still has %i ES",
1016                  i_group, p_pgrm->i_es );
1017         return VLC_EGENERIC;
1018     }
1019
1020     TAB_REMOVE( p_sys->i_pgrm, p_sys->pgrm, p_pgrm );
1021
1022     /* If program is selected we need to unselect it */
1023     if( p_sys->p_pgrm == p_pgrm )
1024         p_sys->p_pgrm = NULL;
1025
1026     input_clock_Delete( p_pgrm->p_clock );
1027
1028     free( p_pgrm->psz_name );
1029     free( p_pgrm->psz_now_playing );
1030     free( p_pgrm->psz_publisher );
1031     if( p_pgrm->p_epg )
1032         vlc_epg_Delete( p_pgrm->p_epg );
1033     free( p_pgrm );
1034
1035     /* Update "program" variable */
1036     val.i_int = i_group;
1037     var_Change( p_input, "program", VLC_VAR_DELCHOICE, &val, NULL );
1038
1039     var_SetBool( p_sys->p_input, "intf-change", true );
1040
1041     return VLC_SUCCESS;
1042 }
1043
1044 /* EsOutProgramMeta:
1045  */
1046 static char *EsOutProgramGetMetaName( es_out_pgrm_t *p_pgrm )
1047 {
1048     char *psz = NULL;
1049     if( p_pgrm->psz_name )
1050     {
1051         if( asprintf( &psz, _("%s [%s %d]"), p_pgrm->psz_name, _("Program"), p_pgrm->i_id ) == -1 )
1052             return NULL;
1053     }
1054     else
1055     {
1056         if( asprintf( &psz, "%s %d", _("Program"), p_pgrm->i_id ) == -1 )
1057             return NULL;
1058     }
1059     return psz;
1060 }
1061
1062 static void EsOutProgramMeta( es_out_t *out, int i_group, vlc_meta_t *p_meta )
1063 {
1064     es_out_sys_t      *p_sys = out->p_sys;
1065     es_out_pgrm_t     *p_pgrm = NULL;
1066     input_thread_t    *p_input = p_sys->p_input;
1067     char              *psz_cat;
1068     const char        *psz_title = NULL;
1069     const char        *psz_provider = NULL;
1070     int i;
1071
1072     msg_Dbg( p_input, "EsOutProgramMeta: number=%d", i_group );
1073
1074     /* Check against empty meta data (empty for what we handle) */
1075     if( !vlc_meta_Get( p_meta, vlc_meta_Title) &&
1076         !vlc_meta_Get( p_meta, vlc_meta_NowPlaying) &&
1077         !vlc_meta_Get( p_meta, vlc_meta_Publisher) &&
1078         vlc_dictionary_keys_count( &p_meta->extra_tags ) <= 0 )
1079     {
1080         return;
1081     }
1082     /* Find program */
1083     for( i = 0; i < p_sys->i_pgrm; i++ )
1084     {
1085         if( p_sys->pgrm[i]->i_id == i_group )
1086         {
1087             p_pgrm = p_sys->pgrm[i];
1088             break;
1089         }
1090     }
1091     if( p_pgrm == NULL )
1092         p_pgrm = EsOutProgramAdd( out, i_group );   /* Create it */
1093
1094     /* */
1095     psz_title = vlc_meta_Get( p_meta, vlc_meta_Title);
1096     psz_provider = vlc_meta_Get( p_meta, vlc_meta_Publisher);
1097
1098     /* Update the description text of the program */
1099     if( psz_title && *psz_title )
1100     {
1101         vlc_value_t val;
1102         vlc_value_t text;
1103
1104         if( !p_pgrm->psz_name || strcmp( p_pgrm->psz_name, psz_title ) )
1105         {
1106             char *psz_cat = EsOutProgramGetMetaName( p_pgrm );
1107
1108             /* Remove old entries */
1109             input_Control( p_input, INPUT_DEL_INFO, psz_cat, NULL );
1110             /* TODO update epg name */
1111             free( psz_cat );
1112         }
1113         free( p_pgrm->psz_name );
1114         p_pgrm->psz_name = strdup( psz_title );
1115
1116         /* ugly but it works */
1117         val.i_int = i_group;
1118         var_Change( p_input, "program", VLC_VAR_DELCHOICE, &val, NULL );
1119
1120         if( psz_provider && *psz_provider )
1121         {
1122             if( asprintf( &text.psz_string, "%s [%s]", psz_title, psz_provider ) != -1 )
1123             {
1124                 var_Change( p_input, "program", VLC_VAR_ADDCHOICE, &val, &text );
1125                 free( text.psz_string );
1126             }
1127         }
1128         else
1129         {
1130             text.psz_string = (char *)psz_title;
1131             var_Change( p_input, "program", VLC_VAR_ADDCHOICE, &val, &text );
1132         }
1133     }
1134
1135     psz_cat = EsOutProgramGetMetaName( p_pgrm );
1136     if( psz_provider )
1137     {
1138         if( p_sys->p_pgrm == p_pgrm )
1139             input_item_SetPublisher( p_input->p->input.p_item, psz_provider );
1140         input_Control( p_input, INPUT_ADD_INFO, psz_cat, input_MetaTypeToLocalizedString(vlc_meta_Publisher), psz_provider );
1141     }
1142     char ** ppsz_all_keys = vlc_dictionary_all_keys( &p_meta->extra_tags );
1143     for( i = 0; ppsz_all_keys[i]; i++ )
1144     {
1145         input_Control( p_input, INPUT_ADD_INFO, psz_cat, _(ppsz_all_keys[i]),
1146                        vlc_dictionary_value_for_key( &p_meta->extra_tags, ppsz_all_keys[i] ) );
1147         free( ppsz_all_keys[i] );
1148     }
1149     free( ppsz_all_keys );
1150
1151     free( psz_cat );
1152 }
1153
1154 static void vlc_epg_Merge( vlc_epg_t *p_dst, const vlc_epg_t *p_src )
1155 {
1156     int i;
1157
1158     /* Add new event */
1159     for( i = 0; i < p_src->i_event; i++ )
1160     {
1161         vlc_epg_event_t *p_evt = p_src->pp_event[i];
1162         bool b_add = true;
1163         int j;
1164
1165         for( j = 0; j < p_dst->i_event; j++ )
1166         {
1167             if( p_dst->pp_event[j]->i_start == p_evt->i_start && p_dst->pp_event[j]->i_duration == p_evt->i_duration )
1168             {
1169                 b_add = false;
1170                 break;
1171             }
1172             if( p_dst->pp_event[j]->i_start > p_evt->i_start )
1173                 break;
1174         }
1175         if( b_add )
1176         {
1177             vlc_epg_event_t *p_copy = malloc( sizeof(vlc_epg_event_t) );
1178             if( !p_copy )
1179                 break;
1180             memset( p_copy, 0, sizeof(vlc_epg_event_t) );
1181             p_copy->i_start = p_evt->i_start;
1182             p_copy->i_duration = p_evt->i_duration;
1183             p_copy->psz_name = p_evt->psz_name ? strdup( p_evt->psz_name ) : NULL;
1184             p_copy->psz_short_description = p_evt->psz_short_description ? strdup( p_evt->psz_short_description ) : NULL;
1185             p_copy->psz_description = p_evt->psz_description ? strdup( p_evt->psz_description ) : NULL;
1186             TAB_INSERT( p_dst->i_event, p_dst->pp_event, p_copy, j );
1187         }
1188     }
1189     /* Update current */
1190     vlc_epg_SetCurrent( p_dst, p_src->p_current ? p_src->p_current->i_start : -1 );
1191
1192     /* Keep only 1 old event  */
1193     if( p_dst->p_current )
1194     {
1195         while( p_dst->i_event > 1 && p_dst->pp_event[0] != p_dst->p_current && p_dst->pp_event[1] != p_dst->p_current )
1196             TAB_REMOVE( p_dst->i_event, p_dst->pp_event, p_dst->pp_event[0] );
1197     }
1198 }
1199
1200 static void EsOutProgramEpg( es_out_t *out, int i_group, vlc_epg_t *p_epg )
1201 {
1202     es_out_sys_t      *p_sys = out->p_sys;
1203     input_thread_t    *p_input = p_sys->p_input;
1204     es_out_pgrm_t     *p_pgrm = NULL;
1205     char *psz_cat;
1206     int i;
1207
1208     /* Find program */
1209     for( i = 0; i < p_sys->i_pgrm; i++ )
1210     {
1211         if( p_sys->pgrm[i]->i_id == i_group )
1212         {
1213             p_pgrm = p_sys->pgrm[i];
1214             break;
1215         }
1216     }
1217     if( p_pgrm == NULL )
1218         p_pgrm = EsOutProgramAdd( out, i_group );   /* Create it */
1219
1220     /* Merge EPG */
1221     if( !p_pgrm->p_epg )
1222         p_pgrm->p_epg = vlc_epg_New( p_pgrm->psz_name );
1223     vlc_epg_Merge( p_pgrm->p_epg, p_epg );
1224
1225     /* Update info */
1226     psz_cat = EsOutProgramGetMetaName( p_pgrm );
1227 #ifdef HAVE_LOCALTIME_R
1228     char *psz_epg;
1229     if( asprintf( &psz_epg, "EPG %s", psz_cat ) == -1 )
1230         psz_epg = NULL;
1231     input_Control( p_input, INPUT_DEL_INFO, psz_epg, NULL );
1232     msg_Dbg( p_input, "EsOutProgramEpg: number=%d name=%s", i_group, p_pgrm->p_epg->psz_name );
1233     for( i = 0; i < p_pgrm->p_epg->i_event; i++ )
1234     {
1235         const vlc_epg_event_t *p_evt = p_pgrm->p_epg->pp_event[i];
1236         time_t t_start = (time_t)p_evt->i_start;
1237         struct tm tm_start;
1238         char psz_start[128];
1239
1240         localtime_r( &t_start, &tm_start );
1241
1242         snprintf( psz_start, sizeof(psz_start), "%2.2d:%2.2d:%2.2d", tm_start.tm_hour, tm_start.tm_min, tm_start.tm_sec );
1243         if( p_evt->psz_short_description || p_evt->psz_description )
1244             input_Control( p_input, INPUT_ADD_INFO, psz_epg, psz_start, "%s (%2.2d:%2.2d) - %s",
1245                            p_evt->psz_name,
1246                            p_evt->i_duration/60/60, (p_evt->i_duration/60)%60,
1247                            p_evt->psz_short_description ? p_evt->psz_short_description : p_evt->psz_description );
1248         else
1249             input_Control( p_input, INPUT_ADD_INFO, psz_epg, psz_start, "%s (%2.2d:%2.2d)",
1250                            p_evt->psz_name,
1251                            p_evt->i_duration/60/60, (p_evt->i_duration/60)%60 );
1252     }
1253     free( psz_epg );
1254 #endif
1255     /* Update now playing */
1256     free( p_pgrm->psz_now_playing );
1257     p_pgrm->psz_now_playing = NULL;
1258     if( p_epg->p_current && p_epg->p_current->psz_name && *p_epg->p_current->psz_name )
1259         p_pgrm->psz_now_playing = strdup( p_epg->p_current->psz_name );
1260
1261     if( p_pgrm == p_sys->p_pgrm )
1262         input_item_SetNowPlaying( p_input->p->input.p_item, p_pgrm->psz_now_playing );
1263
1264     if( p_pgrm->psz_now_playing )
1265     {
1266         input_Control( p_input, INPUT_ADD_INFO, psz_cat,
1267             input_MetaTypeToLocalizedString(vlc_meta_NowPlaying),
1268             p_pgrm->psz_now_playing );
1269     }
1270     else
1271     {
1272         input_Control( p_input, INPUT_DEL_INFO, psz_cat,
1273             input_MetaTypeToLocalizedString(vlc_meta_NowPlaying) );
1274     }
1275
1276     free( psz_cat );
1277 }
1278
1279 /* EsOutAdd:
1280  *  Add an es_out
1281  */
1282 static es_out_id_t *EsOutAdd( es_out_t *out, const es_format_t *fmt )
1283 {
1284     es_out_sys_t      *p_sys = out->p_sys;
1285     input_thread_t    *p_input = p_sys->p_input;
1286
1287     if( fmt->i_group < 0 )
1288     {
1289         msg_Err( p_input, "invalid group number" );
1290         return NULL;
1291     }
1292
1293     es_out_id_t       *es = malloc( sizeof( *es ) );
1294     es_out_pgrm_t     *p_pgrm = NULL;
1295     int i;
1296
1297     if( !es )
1298         return NULL;
1299
1300     vlc_mutex_lock( &p_sys->lock );
1301
1302     /* Search the program */
1303     for( i = 0; i < p_sys->i_pgrm; i++ )
1304     {
1305         if( fmt->i_group == p_sys->pgrm[i]->i_id )
1306         {
1307             p_pgrm = p_sys->pgrm[i];
1308             break;
1309         }
1310     }
1311     if( p_pgrm == NULL )
1312     {
1313         /* Create a new one */
1314         p_pgrm = EsOutProgramAdd( out, fmt->i_group );
1315     }
1316
1317     /* Increase ref count for program */
1318     p_pgrm->i_es++;
1319
1320     /* Set up ES */
1321     es->p_pgrm = p_pgrm;
1322     es_format_Copy( &es->fmt, fmt );
1323     if( es->fmt.i_id < 0 )
1324         es->fmt.i_id = out->p_sys->i_id;
1325     es->i_id = fmt->i_id;
1326
1327     switch( es->fmt.i_cat )
1328     {
1329     case AUDIO_ES:
1330     {
1331         audio_replay_gain_t rg;
1332
1333         es->i_channel = p_sys->i_audio;
1334
1335         memset( &rg, 0, sizeof(rg) );
1336         vlc_mutex_lock( &p_input->p->input.p_item->lock );
1337         vlc_audio_replay_gain_MergeFromMeta( &rg, p_input->p->input.p_item->p_meta );
1338         vlc_mutex_unlock( &p_input->p->input.p_item->lock );
1339
1340         for( i = 0; i < AUDIO_REPLAY_GAIN_MAX; i++ )
1341         {
1342             if( !es->fmt.audio_replay_gain.pb_peak[i] )
1343             {
1344                 es->fmt.audio_replay_gain.pb_peak[i] = rg.pb_peak[i];
1345                 es->fmt.audio_replay_gain.pf_peak[i] = rg.pf_peak[i];
1346             }
1347             if( !es->fmt.audio_replay_gain.pb_gain[i] )
1348             {
1349                 es->fmt.audio_replay_gain.pb_gain[i] = rg.pb_gain[i];
1350                 es->fmt.audio_replay_gain.pf_gain[i] = rg.pf_gain[i];
1351             }
1352         }
1353         break;
1354     }
1355
1356     case VIDEO_ES:
1357         es->i_channel = p_sys->i_video;
1358         if( es->fmt.video.i_frame_rate && es->fmt.video.i_frame_rate_base )
1359             vlc_ureduce( &es->fmt.video.i_frame_rate,
1360                          &es->fmt.video.i_frame_rate_base,
1361                          fmt->video.i_frame_rate,
1362                          fmt->video.i_frame_rate_base, 0 );
1363         break;
1364
1365     case SPU_ES:
1366         es->i_channel = p_sys->i_sub;
1367         break;
1368
1369     default:
1370         es->i_channel = 0;
1371         break;
1372     }
1373     es->psz_language = LanguageGetName( es->fmt.psz_language ); /* remember so we only need to do it once */
1374     es->psz_language_code = LanguageGetCode( es->fmt.psz_language );
1375     es->p_dec = NULL;
1376     es->p_dec_record = NULL;
1377     for( i = 0; i < 4; i++ )
1378         es->pb_cc_present[i] = false;
1379     es->p_master = NULL;
1380
1381     if( es->p_pgrm == p_sys->p_pgrm )
1382         EsOutESVarUpdate( out, es, false );
1383
1384     /* Select it if needed */
1385     EsOutSelect( out, es, false );
1386
1387
1388     TAB_APPEND( out->p_sys->i_es, out->p_sys->es, es );
1389     p_sys->i_id++;  /* always incremented */
1390     switch( es->fmt.i_cat )
1391     {
1392         case AUDIO_ES:
1393             p_sys->i_audio++;
1394             break;
1395         case SPU_ES:
1396             p_sys->i_sub++;
1397             break;
1398         case VIDEO_ES:
1399             p_sys->i_video++;
1400             break;
1401     }
1402
1403     EsOutAddInfo( out, es );
1404
1405     vlc_mutex_unlock( &p_sys->lock );
1406
1407     return es;
1408 }
1409
1410 static bool EsIsSelected( es_out_id_t *es )
1411 {
1412     if( es->p_master )
1413     {
1414         bool b_decode = false;
1415         if( es->p_master->p_dec )
1416         {
1417             int i_channel = EsOutGetClosedCaptionsChannel( es->fmt.i_codec );
1418             if( i_channel != -1 )
1419                 input_DecoderGetCcState( es->p_master->p_dec, &b_decode, i_channel );
1420         }
1421         return b_decode;
1422     }
1423     else
1424     {
1425         return es->p_dec != NULL;
1426     }
1427 }
1428 static void EsCreateDecoder( es_out_t *out, es_out_id_t *p_es )
1429 {
1430     es_out_sys_t   *p_sys = out->p_sys;
1431     input_thread_t *p_input = p_sys->p_input;
1432
1433     p_es->p_dec = input_DecoderNew( p_input, &p_es->fmt, p_es->p_pgrm->p_clock, p_input->p->p_sout );
1434     if( p_es->p_dec )
1435     {
1436         if( p_sys->b_buffering )
1437             input_DecoderStartBuffering( p_es->p_dec );
1438
1439         if( !p_es->p_master && p_sys->p_sout_record )
1440         {
1441             p_es->p_dec_record = input_DecoderNew( p_input, &p_es->fmt, p_es->p_pgrm->p_clock, p_sys->p_sout_record );
1442             if( p_es->p_dec_record && p_sys->b_buffering )
1443                 input_DecoderStartBuffering( p_es->p_dec_record );
1444         }
1445     }
1446
1447     EsOutDecoderChangeDelay( out, p_es );
1448 }
1449 static void EsDestroyDecoder( es_out_t *out, es_out_id_t *p_es )
1450 {
1451     VLC_UNUSED(out);
1452
1453     if( !p_es->p_dec )
1454         return;
1455
1456     input_DecoderDelete( p_es->p_dec );
1457     p_es->p_dec = NULL;
1458
1459     if( p_es->p_dec_record )
1460     {
1461         input_DecoderDelete( p_es->p_dec_record );
1462         p_es->p_dec_record = NULL;
1463     }
1464 }
1465
1466 static void EsSelect( es_out_t *out, es_out_id_t *es )
1467 {
1468     es_out_sys_t   *p_sys = out->p_sys;
1469     input_thread_t *p_input = p_sys->p_input;
1470     vlc_value_t    val;
1471     const char     *psz_var;
1472
1473     if( EsIsSelected( es ) )
1474     {
1475         msg_Warn( p_input, "ES 0x%x is already selected", es->i_id );
1476         return;
1477     }
1478
1479     if( es->p_master )
1480     {
1481         int i_channel;
1482         if( !es->p_master->p_dec )
1483             return;
1484
1485         i_channel = EsOutGetClosedCaptionsChannel( es->fmt.i_codec );
1486         if( i_channel == -1 || input_DecoderSetCcState( es->p_master->p_dec, true, i_channel ) )
1487             return;
1488     }
1489     else
1490     {
1491         if( es->fmt.i_cat == VIDEO_ES || es->fmt.i_cat == SPU_ES )
1492         {
1493             if( !var_GetBool( p_input, out->b_sout ? "sout-video" : "video" ) )
1494             {
1495                 msg_Dbg( p_input, "video is disabled, not selecting ES 0x%x",
1496                          es->i_id );
1497                 return;
1498             }
1499         }
1500         else if( es->fmt.i_cat == AUDIO_ES )
1501         {
1502             var_Get( p_input, "audio", &val );
1503             if( !var_GetBool( p_input, out->b_sout ? "sout-audio" : "audio" ) )
1504             {
1505                 msg_Dbg( p_input, "audio is disabled, not selecting ES 0x%x",
1506                          es->i_id );
1507                 return;
1508             }
1509         }
1510         if( es->fmt.i_cat == SPU_ES )
1511         {
1512             var_Get( p_input, "spu", &val );
1513             if( !var_GetBool( p_input, out->b_sout ? "sout-spu" : "spu" ) )
1514             {
1515                 msg_Dbg( p_input, "spu is disabled, not selecting ES 0x%x",
1516                          es->i_id );
1517                 return;
1518             }
1519         }
1520
1521         EsCreateDecoder( out, es );
1522
1523         if( es->p_dec == NULL || es->p_pgrm != p_sys->p_pgrm )
1524             return;
1525     }
1526
1527     if( es->fmt.i_cat == VIDEO_ES )
1528         psz_var = "video-es";
1529     else if( es->fmt.i_cat == AUDIO_ES )
1530         psz_var = "audio-es";
1531     else if( es->fmt.i_cat == SPU_ES )
1532         psz_var = "spu-es";
1533     else
1534         return;
1535
1536     /* Mark it as selected */
1537     val.i_int = es->i_id;
1538     var_Change( p_input, psz_var, VLC_VAR_SETVALUE, &val, NULL );
1539
1540     var_SetBool( p_sys->p_input, "intf-change", true );
1541 }
1542
1543 static void EsUnselect( es_out_t *out, es_out_id_t *es, bool b_update )
1544 {
1545     es_out_sys_t   *p_sys = out->p_sys;
1546     input_thread_t *p_input = p_sys->p_input;
1547     vlc_value_t    val;
1548     const char     *psz_var;
1549
1550     if( !EsIsSelected( es ) )
1551     {
1552         msg_Warn( p_input, "ES 0x%x is already unselected", es->i_id );
1553         return;
1554     }
1555
1556     if( es->p_master )
1557     {
1558         if( es->p_master->p_dec )
1559         {
1560             int i_channel = EsOutGetClosedCaptionsChannel( es->fmt.i_codec );
1561             if( i_channel != -1 )
1562                 input_DecoderSetCcState( es->p_master->p_dec, false, i_channel );
1563         }
1564     }
1565     else
1566     {
1567         const int i_spu_id = var_GetInteger( p_input, "spu-es");
1568         int i;
1569         for( i = 0; i < 4; i++ )
1570         {
1571             if( !es->pb_cc_present[i] || !es->pp_cc_es[i] )
1572                 continue;
1573
1574             if( i_spu_id == es->pp_cc_es[i]->i_id )
1575             {
1576                 /* Force unselection of the CC */
1577                 val.i_int = -1;
1578                 var_Change( p_input, "spu-es", VLC_VAR_SETVALUE, &val, NULL );
1579                 if( !b_update )
1580                     var_SetBool( p_sys->p_input, "intf-change", true );
1581             }
1582             EsOutDel( out, es->pp_cc_es[i] );
1583
1584             es->pb_cc_present[i] = false;
1585         }
1586         EsDestroyDecoder( out, es );
1587     }
1588
1589     if( !b_update )
1590         return;
1591
1592     /* Update var */
1593     if( es->p_dec == NULL )
1594         return;
1595     if( es->fmt.i_cat == VIDEO_ES )
1596         psz_var = "video-es";
1597     else if( es->fmt.i_cat == AUDIO_ES )
1598         psz_var = "audio-es";
1599     else if( es->fmt.i_cat == SPU_ES )
1600         psz_var = "spu-es";
1601     else
1602         return;
1603
1604     /* Mark it as unselected */
1605     val.i_int = -1;
1606     var_Change( p_input, psz_var, VLC_VAR_SETVALUE, &val, NULL );
1607
1608     var_SetBool( p_sys->p_input, "intf-change", true );
1609 }
1610
1611 /**
1612  * Select an ES given the current mode
1613  * XXX: you need to take a the lock before (stream.stream_lock)
1614  *
1615  * \param out The es_out structure
1616  * \param es es_out_id structure
1617  * \param b_force ...
1618  * \return nothing
1619  */
1620 static void EsOutSelect( es_out_t *out, es_out_id_t *es, bool b_force )
1621 {
1622     es_out_sys_t      *p_sys = out->p_sys;
1623
1624     int i_cat = es->fmt.i_cat;
1625
1626     if( !p_sys->b_active ||
1627         ( !b_force && es->fmt.i_priority < 0 ) )
1628     {
1629         return;
1630     }
1631
1632     if( p_sys->i_mode == ES_OUT_MODE_ALL || b_force )
1633     {
1634         if( !EsIsSelected( es ) )
1635             EsSelect( out, es );
1636     }
1637     else if( p_sys->i_mode == ES_OUT_MODE_PARTIAL )
1638     {
1639         vlc_value_t val;
1640         int i;
1641         var_Get( p_sys->p_input, "programs", &val );
1642         for ( i = 0; i < val.p_list->i_count; i++ )
1643         {
1644             if ( val.p_list->p_values[i].i_int == es->p_pgrm->i_id || b_force )
1645             {
1646                 if( !EsIsSelected( es ) )
1647                     EsSelect( out, es );
1648                 break;
1649             }
1650         }
1651         var_Change( p_sys->p_input, "programs", VLC_VAR_FREELIST, &val, NULL );
1652     }
1653     else if( p_sys->i_mode == ES_OUT_MODE_AUTO )
1654     {
1655         int i_wanted  = -1;
1656
1657         if( es->p_pgrm != p_sys->p_pgrm )
1658             return;
1659
1660         if( i_cat == AUDIO_ES )
1661         {
1662             int idx1 = LanguageArrayIndex( p_sys->ppsz_audio_language,
1663                                      es->psz_language_code );
1664
1665             if( p_sys->p_es_audio &&
1666                 p_sys->p_es_audio->fmt.i_priority >= es->fmt.i_priority )
1667             {
1668                 int idx2 = LanguageArrayIndex( p_sys->ppsz_audio_language,
1669                                          p_sys->p_es_audio->psz_language_code );
1670
1671                 if( idx1 < 0 || ( idx2 >= 0 && idx2 <= idx1 ) )
1672                     return;
1673                 i_wanted = es->i_channel;
1674             }
1675             else
1676             {
1677                 /* Select audio if (no audio selected yet)
1678                  * - no audio-language
1679                  * - no audio code for the ES
1680                  * - audio code in the requested list */
1681                 if( idx1 >= 0 ||
1682                     !strcmp( es->psz_language_code, "??" ) ||
1683                     !p_sys->ppsz_audio_language )
1684                     i_wanted = es->i_channel;
1685             }
1686
1687             if( p_sys->i_audio_last >= 0 )
1688                 i_wanted = p_sys->i_audio_last;
1689
1690             if( p_sys->i_audio_id >= 0 )
1691             {
1692                 if( es->i_id == p_sys->i_audio_id )
1693                     i_wanted = es->i_channel;
1694                 else
1695                     return;
1696             }
1697         }
1698         else if( i_cat == SPU_ES )
1699         {
1700             int idx1 = LanguageArrayIndex( p_sys->ppsz_sub_language,
1701                                      es->psz_language_code );
1702
1703             if( p_sys->p_es_sub &&
1704                 p_sys->p_es_sub->fmt.i_priority >= es->fmt.i_priority )
1705             {
1706                 int idx2 = LanguageArrayIndex( p_sys->ppsz_sub_language,
1707                                          p_sys->p_es_sub->psz_language_code );
1708
1709                 msg_Dbg( p_sys->p_input, "idx1=%d(%s) idx2=%d(%s)",
1710                         idx1, es->psz_language_code, idx2,
1711                         p_sys->p_es_sub->psz_language_code );
1712
1713                 if( idx1 < 0 || ( idx2 >= 0 && idx2 <= idx1 ) )
1714                     return;
1715                 /* We found a SPU that matches our language request */
1716                 i_wanted  = es->i_channel;
1717             }
1718             else if( idx1 >= 0 )
1719             {
1720                 msg_Dbg( p_sys->p_input, "idx1=%d(%s)",
1721                         idx1, es->psz_language_code );
1722
1723                 i_wanted  = es->i_channel;
1724             }
1725             else if( p_sys->i_default_sub_id >= 0 )
1726             {
1727                 if( es->i_id == p_sys->i_default_sub_id )
1728                     i_wanted = es->i_channel;
1729             }
1730
1731             if( p_sys->i_sub_last >= 0 )
1732                 i_wanted  = p_sys->i_sub_last;
1733
1734             if( p_sys->i_sub_id >= 0 )
1735             {
1736                 if( es->i_id == p_sys->i_sub_id )
1737                     i_wanted = es->i_channel;
1738                 else
1739                     return;
1740             }
1741         }
1742         else if( i_cat == VIDEO_ES )
1743         {
1744             i_wanted  = es->i_channel;
1745         }
1746
1747         if( i_wanted == es->i_channel && !EsIsSelected( es ) )
1748             EsSelect( out, es );
1749     }
1750
1751     /* FIXME TODO handle priority here */
1752     if( EsIsSelected( es ) )
1753     {
1754         if( i_cat == AUDIO_ES )
1755         {
1756             if( p_sys->i_mode == ES_OUT_MODE_AUTO &&
1757                 p_sys->p_es_audio &&
1758                 p_sys->p_es_audio != es &&
1759                 EsIsSelected( p_sys->p_es_audio ) )
1760             {
1761                 EsUnselect( out, p_sys->p_es_audio, false );
1762             }
1763             p_sys->p_es_audio = es;
1764         }
1765         else if( i_cat == SPU_ES )
1766         {
1767             if( p_sys->i_mode == ES_OUT_MODE_AUTO &&
1768                 p_sys->p_es_sub &&
1769                 p_sys->p_es_sub != es &&
1770                 EsIsSelected( p_sys->p_es_sub ) )
1771             {
1772                 EsUnselect( out, p_sys->p_es_sub, false );
1773             }
1774             p_sys->p_es_sub = es;
1775         }
1776         else if( i_cat == VIDEO_ES )
1777         {
1778             p_sys->p_es_video = es;
1779         }
1780     }
1781 }
1782
1783 /**
1784  * Send a block for the given es_out
1785  *
1786  * \param out the es_out to send from
1787  * \param es the es_out_id
1788  * \param p_block the data block to send
1789  */
1790 static int EsOutSend( es_out_t *out, es_out_id_t *es, block_t *p_block )
1791 {
1792     es_out_sys_t   *p_sys = out->p_sys;
1793     input_thread_t *p_input = p_sys->p_input;
1794     int i_total = 0;
1795
1796     if( libvlc_stats( p_input ) )
1797     {
1798         vlc_mutex_lock( &p_input->p->counters.counters_lock );
1799         stats_UpdateInteger( p_input, p_input->p->counters.p_demux_read,
1800                              p_block->i_buffer, &i_total );
1801         stats_UpdateFloat( p_input , p_input->p->counters.p_demux_bitrate,
1802                            (float)i_total, NULL );
1803         vlc_mutex_unlock( &p_input->p->counters.counters_lock );
1804     }
1805
1806     vlc_mutex_lock( &p_sys->lock );
1807
1808     /* Mark preroll blocks */
1809     if( p_sys->i_preroll_end >= 0 )
1810     {
1811         int64_t i_date = p_block->i_pts;
1812         if( i_date <= 0 )
1813             i_date = p_block->i_dts;
1814
1815         if( i_date < p_sys->i_preroll_end )
1816             p_block->i_flags |= BLOCK_FLAG_PREROLL;
1817     }
1818
1819     p_block->i_rate = 0;
1820
1821     if( !es->p_dec )
1822     {
1823         block_Release( p_block );
1824         vlc_mutex_unlock( &p_sys->lock );
1825         return VLC_SUCCESS;
1826     }
1827
1828     /* Decode */
1829     if( es->p_dec_record )
1830     {
1831         block_t *p_dup = block_Duplicate( p_block );
1832         if( p_dup )
1833             input_DecoderDecode( es->p_dec_record, p_dup );
1834     }
1835     input_DecoderDecode( es->p_dec, p_block );
1836
1837     /* Check CC status */
1838     bool pb_cc[4];
1839     bool b_cc_new = false;
1840
1841     input_DecoderIsCcPresent( es->p_dec, pb_cc );
1842     for( int i = 0; i < 4; i++ )
1843     {
1844         static const vlc_fourcc_t fcc[4] = {
1845             VLC_FOURCC('c', 'c', '1', ' '),
1846             VLC_FOURCC('c', 'c', '2', ' '),
1847             VLC_FOURCC('c', 'c', '3', ' '),
1848             VLC_FOURCC('c', 'c', '4', ' '),
1849         };
1850         es_format_t fmt;
1851
1852         if(  es->pb_cc_present[i] || !pb_cc[i] )
1853             continue;
1854         msg_Dbg( p_input, "Adding CC track %d for es[%d]", 1+i, es->i_id );
1855
1856         es_format_Init( &fmt, SPU_ES, fcc[i] );
1857         fmt.i_group = es->fmt.i_group;
1858         if( asprintf( &fmt.psz_description,
1859                       _("Closed captions %u"), 1 + i ) == -1 )
1860             fmt.psz_description = NULL;
1861         es->pp_cc_es[i] = EsOutAdd( out, &fmt );
1862         es->pp_cc_es[i]->p_master = es;
1863         es_format_Clean( &fmt );
1864
1865         /* */
1866         es->pb_cc_present[i] = true;
1867         b_cc_new = true;
1868     }
1869     if( b_cc_new )
1870         var_SetBool( p_sys->p_input, "intf-change", true );
1871
1872     vlc_mutex_unlock( &p_sys->lock );
1873
1874     return VLC_SUCCESS;
1875 }
1876
1877 /*****************************************************************************
1878  * EsOutDel:
1879  *****************************************************************************/
1880 static void EsOutDel( es_out_t *out, es_out_id_t *es )
1881 {
1882     es_out_sys_t *p_sys = out->p_sys;
1883     bool b_reselect = false;
1884     int i;
1885
1886     vlc_mutex_lock( &p_sys->lock );
1887
1888     /* We don't try to reselect */
1889     if( es->p_dec )
1890     {
1891         while( !p_sys->p_input->b_die && !p_sys->b_buffering && es->p_dec )
1892         {
1893             if( input_DecoderIsEmpty( es->p_dec ) &&
1894                 ( !es->p_dec_record || input_DecoderIsEmpty( es->p_dec_record ) ))
1895                 break;
1896             /* FIXME there should be a way to have auto deleted es, but there will be
1897              * a problem when another codec of the same type is created (mainly video) */
1898             msleep( 20*1000 );
1899         }
1900         EsUnselect( out, es, es->p_pgrm == p_sys->p_pgrm );
1901     }
1902
1903     if( es->p_pgrm == p_sys->p_pgrm )
1904         EsOutESVarUpdate( out, es, true );
1905
1906     TAB_REMOVE( p_sys->i_es, p_sys->es, es );
1907
1908     es->p_pgrm->i_es--;
1909     if( es->p_pgrm->i_es == 0 )
1910     {
1911         msg_Dbg( p_sys->p_input, "Program doesn't contain anymore ES" );
1912     }
1913
1914     if( p_sys->p_es_audio == es || p_sys->p_es_video == es ||
1915         p_sys->p_es_sub == es ) b_reselect = true;
1916
1917     if( p_sys->p_es_audio == es ) p_sys->p_es_audio = NULL;
1918     if( p_sys->p_es_video == es ) p_sys->p_es_video = NULL;
1919     if( p_sys->p_es_sub   == es ) p_sys->p_es_sub   = NULL;
1920
1921     switch( es->fmt.i_cat )
1922     {
1923         case AUDIO_ES:
1924             p_sys->i_audio--;
1925             break;
1926         case SPU_ES:
1927             p_sys->i_sub--;
1928             break;
1929         case VIDEO_ES:
1930             p_sys->i_video--;
1931             break;
1932     }
1933
1934     /* Re-select another track when needed */
1935     if( b_reselect )
1936     {
1937         for( i = 0; i < p_sys->i_es; i++ )
1938         {
1939             if( es->fmt.i_cat == p_sys->es[i]->fmt.i_cat )
1940                 EsOutSelect( out, p_sys->es[i], false );
1941         }
1942     }
1943
1944     free( es->psz_language );
1945     free( es->psz_language_code );
1946
1947     es_format_Clean( &es->fmt );
1948
1949     vlc_mutex_unlock( &p_sys->lock );
1950
1951     free( es );
1952 }
1953
1954 /**
1955  * Control query handler
1956  *
1957  * \param out the es_out to control
1958  * \param i_query A es_out query as defined in include/ninput.h
1959  * \param args a variable list of arguments for the query
1960  * \return VLC_SUCCESS or an error code
1961  */
1962 static int EsOutControlLocked( es_out_t *out, int i_query, va_list args )
1963 {
1964     es_out_sys_t *p_sys = out->p_sys;
1965     bool  b, *pb;
1966     int         i, *pi;
1967
1968     es_out_id_t *es;
1969
1970     switch( i_query )
1971     {
1972         case ES_OUT_SET_ES_STATE:
1973             es = (es_out_id_t*) va_arg( args, es_out_id_t * );
1974             b = (bool) va_arg( args, int );
1975             if( b && !EsIsSelected( es ) )
1976             {
1977                 EsSelect( out, es );
1978                 return EsIsSelected( es ) ? VLC_SUCCESS : VLC_EGENERIC;
1979             }
1980             else if( !b && EsIsSelected( es ) )
1981             {
1982                 EsUnselect( out, es, es->p_pgrm == p_sys->p_pgrm );
1983                 return VLC_SUCCESS;
1984             }
1985             return VLC_SUCCESS;
1986
1987         case ES_OUT_GET_ES_STATE:
1988             es = (es_out_id_t*) va_arg( args, es_out_id_t * );
1989             pb = (bool*) va_arg( args, bool * );
1990
1991             *pb = EsIsSelected( es );
1992             return VLC_SUCCESS;
1993
1994         case ES_OUT_SET_ACTIVE:
1995         {
1996             b = (bool) va_arg( args, int );
1997             p_sys->b_active = b;
1998             /* Needed ? */
1999             if( b )
2000                 var_SetBool( p_sys->p_input, "intf-change", true );
2001             return VLC_SUCCESS;
2002         }
2003
2004         case ES_OUT_GET_ACTIVE:
2005             pb = (bool*) va_arg( args, bool * );
2006             *pb = p_sys->b_active;
2007             return VLC_SUCCESS;
2008
2009         case ES_OUT_SET_MODE:
2010             i = (int) va_arg( args, int );
2011             if( i == ES_OUT_MODE_NONE || i == ES_OUT_MODE_ALL ||
2012                 i == ES_OUT_MODE_AUTO || i == ES_OUT_MODE_PARTIAL )
2013             {
2014                 p_sys->i_mode = i;
2015
2016                 /* Reapply policy mode */
2017                 for( i = 0; i < p_sys->i_es; i++ )
2018                 {
2019                     if( EsIsSelected( p_sys->es[i] ) )
2020                     {
2021                         EsUnselect( out, p_sys->es[i],
2022                                     p_sys->es[i]->p_pgrm == p_sys->p_pgrm );
2023                     }
2024                 }
2025                 for( i = 0; i < p_sys->i_es; i++ )
2026                 {
2027                     EsOutSelect( out, p_sys->es[i], false );
2028                 }
2029                 return VLC_SUCCESS;
2030             }
2031             return VLC_EGENERIC;
2032
2033         case ES_OUT_GET_MODE:
2034             pi = (int*) va_arg( args, int* );
2035             *pi = p_sys->i_mode;
2036             return VLC_SUCCESS;
2037
2038         case ES_OUT_SET_ES:
2039         case ES_OUT_RESTART_ES:
2040         {
2041             int i_cat;
2042
2043             es = (es_out_id_t*) va_arg( args, es_out_id_t * );
2044
2045             if( es == NULL )
2046                 i_cat = UNKNOWN_ES;
2047             else if( es == (es_out_id_t*)((uint8_t*)NULL+AUDIO_ES) )
2048                 i_cat = AUDIO_ES;
2049             else if( es == (es_out_id_t*)((uint8_t*)NULL+VIDEO_ES) )
2050                 i_cat = VIDEO_ES;
2051             else if( es == (es_out_id_t*)((uint8_t*)NULL+SPU_ES) )
2052                 i_cat = SPU_ES;
2053             else
2054                 i_cat = -1;
2055
2056             for( i = 0; i < p_sys->i_es; i++ )
2057             {
2058                 if( i_cat == -1 )
2059                 {
2060                     if( es == p_sys->es[i] )
2061                     {
2062                         EsOutSelect( out, es, true );
2063                         break;
2064                     }
2065                 }
2066                 else
2067                 {
2068                     if( i_cat == UNKNOWN_ES || p_sys->es[i]->fmt.i_cat == i_cat )
2069                     {
2070                         if( EsIsSelected( p_sys->es[i] ) )
2071                         {
2072                             if( i_query == ES_OUT_RESTART_ES )
2073                             {
2074                                 if( p_sys->es[i]->p_dec )
2075                                 {
2076                                     EsDestroyDecoder( out, p_sys->es[i] );
2077                                     EsCreateDecoder( out, p_sys->es[i] );
2078                                 }
2079                             }
2080                             else
2081                             {
2082                                 EsUnselect( out, p_sys->es[i],
2083                                             p_sys->es[i]->p_pgrm == p_sys->p_pgrm );
2084                             }
2085                         }
2086                     }
2087                 }
2088             }
2089             if( i_query == ES_OUT_SET_ES )
2090             {
2091                 vlc_event_t event;
2092                 event.type = vlc_InputSelectedStreamChanged;
2093                 vlc_event_send( &p_sys->p_input->p->event_manager, &event );
2094             }
2095             return VLC_SUCCESS;
2096         }
2097  
2098         case ES_OUT_SET_ES_DEFAULT:
2099         {
2100             es = (es_out_id_t*) va_arg( args, es_out_id_t * );
2101
2102             if( es == NULL )
2103             {
2104                 /*p_sys->i_default_video_id = -1;*/
2105                 /*p_sys->i_default_audio_id = -1;*/
2106                 p_sys->i_default_sub_id = -1;
2107             }
2108             else if( es == (es_out_id_t*)((uint8_t*)NULL+AUDIO_ES) )
2109             {
2110                 /*p_sys->i_default_video_id = -1;*/
2111             }
2112             else if( es == (es_out_id_t*)((uint8_t*)NULL+VIDEO_ES) )
2113             {
2114                 /*p_sys->i_default_audio_id = -1;*/
2115             }
2116             else if( es == (es_out_id_t*)((uint8_t*)NULL+SPU_ES) )
2117             {
2118                 p_sys->i_default_sub_id = -1;
2119             }
2120             else
2121             {
2122                 /*if( es->fmt.i_cat == VIDEO_ES )
2123                     p_sys->i_default_video_id = es->i_id;
2124                 else
2125                 if( es->fmt.i_cat == AUDIO_ES )
2126                     p_sys->i_default_audio_id = es->i_id;
2127                 else*/
2128                 if( es->fmt.i_cat == SPU_ES )
2129                     p_sys->i_default_sub_id = es->i_id;
2130             }
2131             return VLC_SUCCESS;
2132         }
2133
2134         case ES_OUT_SET_PCR:
2135         case ES_OUT_SET_GROUP_PCR:
2136         {
2137             es_out_pgrm_t *p_pgrm = NULL;
2138             int            i_group = 0;
2139             int64_t        i_pcr;
2140
2141             if( i_query == ES_OUT_SET_PCR )
2142             {
2143                 p_pgrm = p_sys->p_pgrm;
2144             }
2145             else
2146             {
2147                 int i;
2148                 i_group = (int)va_arg( args, int );
2149                 for( i = 0; i < p_sys->i_pgrm; i++ )
2150                 {
2151                     if( p_sys->pgrm[i]->i_id == i_group )
2152                     {
2153                         p_pgrm = p_sys->pgrm[i];
2154                         break;
2155                     }
2156                 }
2157             }
2158             if( p_pgrm == NULL )
2159                 p_pgrm = EsOutProgramAdd( out, i_group );   /* Create it */
2160
2161             i_pcr = (int64_t)va_arg( args, int64_t );
2162             /* search program
2163              * TODO do not use mdate() but proper stream acquisition date */
2164             input_clock_Update( p_pgrm->p_clock, VLC_OBJECT(p_sys->p_input),
2165                                 p_sys->p_input->b_can_pace_control, i_pcr, mdate() );
2166             /* Check buffering state on master clock update */
2167             if( p_sys->b_buffering && p_pgrm == p_sys->p_pgrm )
2168                 EsOutDecodersStopBuffering( out, false );
2169
2170             return VLC_SUCCESS;
2171         }
2172
2173         case ES_OUT_RESET_PCR:
2174             msg_Err( p_sys->p_input, "ES_OUT_RESET_PCR called" );
2175             EsOutChangePosition( out );
2176             return VLC_SUCCESS;
2177
2178         case ES_OUT_GET_TS:
2179             if( p_sys->p_pgrm )
2180             {
2181                 int64_t i_ts = (int64_t)va_arg( args, int64_t );
2182                 int64_t *pi_ts = (int64_t *)va_arg( args, int64_t * );
2183                 *pi_ts = input_clock_GetTS( p_sys->p_pgrm->p_clock, NULL,
2184                                             p_sys->p_input->i_pts_delay, i_ts );
2185                 return VLC_SUCCESS;
2186             }
2187             return VLC_EGENERIC;
2188
2189         case ES_OUT_GET_GROUP:
2190             pi = (int*) va_arg( args, int* );
2191             if( p_sys->p_pgrm )
2192                 *pi = p_sys->p_pgrm->i_id;
2193             else
2194                 *pi = -1;    /* FIXME */
2195             return VLC_SUCCESS;
2196
2197         case ES_OUT_SET_GROUP:
2198         {
2199             int j;
2200             i = (int) va_arg( args, int );
2201             for( j = 0; j < p_sys->i_pgrm; j++ )
2202             {
2203                 es_out_pgrm_t *p_pgrm = p_sys->pgrm[j];
2204                 if( p_pgrm->i_id == i )
2205                 {
2206                     EsOutProgramSelect( out, p_pgrm );
2207                     return VLC_SUCCESS;
2208                 }
2209             }
2210             return VLC_EGENERIC;
2211         }
2212
2213         case ES_OUT_SET_FMT:
2214         {
2215             /* This ain't pretty but is need by some demuxers (eg. Ogg )
2216              * to update the p_extra data */
2217             es_format_t *p_fmt;
2218             es = (es_out_id_t*) va_arg( args, es_out_id_t * );
2219             p_fmt = (es_format_t*) va_arg( args, es_format_t * );
2220             if( es == NULL )
2221                 return VLC_EGENERIC;
2222
2223             if( p_fmt->i_extra )
2224             {
2225                 es->fmt.i_extra = p_fmt->i_extra;
2226                 es->fmt.p_extra = realloc( es->fmt.p_extra, p_fmt->i_extra );
2227                 memcpy( es->fmt.p_extra, p_fmt->p_extra, p_fmt->i_extra );
2228
2229                 if( !es->p_dec )
2230                     return VLC_SUCCESS;
2231 #if 1
2232                 EsDestroyDecoder( out, es );
2233
2234                 EsCreateDecoder( out, es );
2235 #else
2236                 es->p_dec->fmt_in.i_extra = p_fmt->i_extra;
2237                 es->p_dec->fmt_in.p_extra =
2238                     realloc( es->p_dec->fmt_in.p_extra, p_fmt->i_extra );
2239                 memcpy( es->p_dec->fmt_in.p_extra,
2240                         p_fmt->p_extra, p_fmt->i_extra );
2241 #endif
2242             }
2243
2244             return VLC_SUCCESS;
2245         }
2246
2247         case ES_OUT_SET_NEXT_DISPLAY_TIME:
2248         {
2249             const int64_t i_date = (int64_t)va_arg( args, int64_t );
2250
2251             if( i_date < 0 )
2252                 return VLC_EGENERIC;
2253
2254             p_sys->i_preroll_end = i_date;
2255
2256             return VLC_SUCCESS;
2257         }
2258         case ES_OUT_SET_GROUP_META:
2259         {
2260             int i_group = (int)va_arg( args, int );
2261             vlc_meta_t *p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t * );
2262
2263             EsOutProgramMeta( out, i_group, p_meta );
2264             return VLC_SUCCESS;
2265         }
2266         case ES_OUT_SET_GROUP_EPG:
2267         {
2268             int i_group = (int)va_arg( args, int );
2269             vlc_epg_t *p_epg = (vlc_epg_t*)va_arg( args, vlc_epg_t * );
2270
2271             EsOutProgramEpg( out, i_group, p_epg );
2272             return VLC_SUCCESS;
2273         }
2274         case ES_OUT_DEL_GROUP:
2275         {
2276             int i_group = (int)va_arg( args, int );
2277
2278             return EsOutProgramDel( out, i_group );
2279         }
2280
2281         case ES_OUT_GET_WAKE_UP:
2282         {
2283             mtime_t *pi_wakeup = (mtime_t*)va_arg( args, mtime_t* );
2284             *pi_wakeup = EsOutGetWakeup( out );
2285             return VLC_SUCCESS;
2286         }
2287
2288         case ES_OUT_SET_ES_BY_ID:
2289         case ES_OUT_RESTART_ES_BY_ID:
2290         case ES_OUT_SET_ES_DEFAULT_BY_ID:
2291         {
2292             const int i_id = (int)va_arg( args, int );
2293             es_out_id_t *p_es = EsOutGetFromID( out, i_id );
2294             int i_new_query;
2295
2296             switch( i_query )
2297             {
2298             case ES_OUT_SET_ES_BY_ID:         i_new_query = ES_OUT_SET_ES; break;
2299             case ES_OUT_RESTART_ES_BY_ID:     i_new_query = ES_OUT_RESTART_ES; break;
2300             case ES_OUT_SET_ES_DEFAULT_BY_ID: i_new_query = ES_OUT_SET_ES_DEFAULT; break;
2301             default:
2302               assert(0);
2303             }
2304             /* TODO if the lock is made non recursive it should be changed */
2305             return es_out_Control( out, i_new_query, p_es );
2306         }
2307
2308         case ES_OUT_GET_BUFFERING:
2309             pb = (bool *)va_arg( args, bool* );
2310             *pb = p_sys->b_buffering;
2311             return VLC_SUCCESS;
2312
2313         case ES_OUT_GET_EMPTY:
2314             pb = (bool *)va_arg( args, bool* );
2315             *pb = EsOutDecodersIsEmpty( out );
2316             return VLC_SUCCESS;
2317
2318         case ES_OUT_SET_DELAY:
2319         {
2320             const int i_cat = (int)va_arg( args, int );
2321             const mtime_t i_delay = (mtime_t)va_arg( args, mtime_t );
2322             EsOutSetDelay( out, i_cat, i_delay );
2323             return VLC_SUCCESS;
2324         }
2325
2326         case ES_OUT_SET_RECORD_STATE:
2327             b = (bool) va_arg( args, int );
2328             return EsOutSetRecord( out, b );
2329
2330         case ES_OUT_SET_PAUSE_STATE:
2331         {
2332             const bool b_source_paused = (bool)va_arg( args, int );
2333             const bool b_paused = (bool)va_arg( args, int );
2334             const mtime_t i_date = (mtime_t) va_arg( args, mtime_t );
2335
2336             assert( !b_source_paused == !b_paused );
2337             EsOutChangePause( out, b_paused, i_date );
2338
2339             return VLC_SUCCESS;
2340         }
2341
2342         case ES_OUT_SET_RATE:
2343         {
2344             const int i_src_rate = (int)va_arg( args, int );
2345             const int i_rate = (int)va_arg( args, int );
2346
2347             assert( i_src_rate == i_rate );
2348             EsOutChangeRate( out, i_rate );
2349
2350             return VLC_SUCCESS;
2351         }
2352
2353         case ES_OUT_SET_TIME:
2354         {
2355             const mtime_t i_date = (mtime_t)va_arg( args, mtime_t );
2356
2357             assert( i_date == -1 );
2358             EsOutChangePosition( out );
2359
2360             return VLC_SUCCESS;
2361         }
2362
2363         case ES_OUT_SET_FRAME_NEXT:
2364             EsOutFrameNext( out );
2365             return VLC_SUCCESS;
2366
2367         case ES_OUT_LOCK:
2368             vlc_mutex_lock( &p_sys->lock );
2369             return VLC_SUCCESS;
2370
2371         case ES_OUT_UNLOCK:
2372             vlc_mutex_unlock( &p_sys->lock );
2373             return VLC_SUCCESS;
2374
2375         default:
2376             msg_Err( p_sys->p_input, "unknown query in es_out_Control" );
2377             return VLC_EGENERIC;
2378     }
2379 }
2380 static int EsOutControl( es_out_t *out, int i_query, va_list args )
2381 {
2382     es_out_sys_t *p_sys = out->p_sys;
2383     int i_ret;
2384
2385     vlc_mutex_lock( &p_sys->lock );
2386     i_ret = EsOutControlLocked( out, i_query, args );
2387     vlc_mutex_unlock( &p_sys->lock );
2388
2389     return i_ret;
2390 }
2391
2392 /****************************************************************************
2393  * LanguageGetName: try to expend iso639 into plain name
2394  ****************************************************************************/
2395 static char *LanguageGetName( const char *psz_code )
2396 {
2397     const iso639_lang_t *pl;
2398
2399     if( psz_code == NULL )
2400     {
2401         return strdup( "" );
2402     }
2403
2404     if( strlen( psz_code ) == 2 )
2405     {
2406         pl = GetLang_1( psz_code );
2407     }
2408     else if( strlen( psz_code ) == 3 )
2409     {
2410         pl = GetLang_2B( psz_code );
2411         if( !strcmp( pl->psz_iso639_1, "??" ) )
2412         {
2413             pl = GetLang_2T( psz_code );
2414         }
2415     }
2416     else
2417     {
2418         return strdup( psz_code );
2419     }
2420
2421     if( !strcmp( pl->psz_iso639_1, "??" ) )
2422     {
2423        return strdup( psz_code );
2424     }
2425     else
2426     {
2427         if( *pl->psz_native_name )
2428         {
2429             return strdup( pl->psz_native_name );
2430         }
2431         return strdup( pl->psz_eng_name );
2432     }
2433 }
2434
2435 /* Get a 2 char code */
2436 static char *LanguageGetCode( const char *psz_lang )
2437 {
2438     const iso639_lang_t *pl;
2439
2440     if( psz_lang == NULL || *psz_lang == '\0' )
2441         return strdup("??");
2442
2443     for( pl = p_languages; pl->psz_iso639_1 != NULL; pl++ )
2444     {
2445         if( !strcasecmp( pl->psz_eng_name, psz_lang ) ||
2446             !strcasecmp( pl->psz_native_name, psz_lang ) ||
2447             !strcasecmp( pl->psz_iso639_1, psz_lang ) ||
2448             !strcasecmp( pl->psz_iso639_2T, psz_lang ) ||
2449             !strcasecmp( pl->psz_iso639_2B, psz_lang ) )
2450             break;
2451     }
2452
2453     if( pl->psz_iso639_1 != NULL )
2454         return strdup( pl->psz_iso639_1 );
2455
2456     return strdup("??");
2457 }
2458
2459 static char **LanguageSplit( const char *psz_langs )
2460 {
2461     char *psz_dup;
2462     char *psz_parser;
2463     char **ppsz = NULL;
2464     int i_psz = 0;
2465
2466     if( psz_langs == NULL ) return NULL;
2467
2468     psz_parser = psz_dup = strdup(psz_langs);
2469
2470     while( psz_parser && *psz_parser )
2471     {
2472         char *psz;
2473         char *psz_code;
2474
2475         psz = strchr(psz_parser, ',' );
2476         if( psz ) *psz++ = '\0';
2477
2478         if( !strcmp( psz_parser, "any" ) )
2479         {
2480             TAB_APPEND( i_psz, ppsz, strdup("any") );
2481         }
2482         else
2483         {
2484             psz_code = LanguageGetCode( psz_parser );
2485             if( strcmp( psz_code, "??" ) )
2486             {
2487                 TAB_APPEND( i_psz, ppsz, psz_code );
2488             }
2489             else
2490             {
2491                 free( psz_code );
2492             }
2493         }
2494
2495         psz_parser = psz;
2496     }
2497
2498     if( i_psz )
2499     {
2500         TAB_APPEND( i_psz, ppsz, NULL );
2501     }
2502
2503     free( psz_dup );
2504     return ppsz;
2505 }
2506
2507 static int LanguageArrayIndex( char **ppsz_langs, char *psz_lang )
2508 {
2509     int i;
2510
2511     if( !ppsz_langs || !psz_lang ) return -1;
2512
2513     for( i = 0; ppsz_langs[i]; i++ )
2514     {
2515         if( !strcasecmp( ppsz_langs[i], psz_lang ) ||
2516             !strcasecmp( ppsz_langs[i], "any" ) )
2517         {
2518             return i;
2519         }
2520     }
2521
2522     return -1;
2523 }
2524
2525 /****************************************************************************
2526  * EsOutAddInfo:
2527  * - add meta info to the playlist item
2528  ****************************************************************************/
2529 static void EsOutAddInfo( es_out_t *out, es_out_id_t *es )
2530 {
2531     es_out_sys_t   *p_sys = out->p_sys;
2532     input_thread_t *p_input = p_sys->p_input;
2533     es_format_t    *fmt = &es->fmt;
2534     char           *psz_cat;
2535     lldiv_t         div;
2536
2537     /* Add stream info */
2538     if( asprintf( &psz_cat, _("Stream %d"), out->p_sys->i_id - 1 ) == -1 )
2539         return;
2540
2541     input_Control( p_input, INPUT_ADD_INFO, psz_cat, _("Codec"),
2542                    "%.4s", (char*)&fmt->i_codec );
2543
2544     input_Control( p_input, INPUT_ADD_INFO, psz_cat, _("Language"),
2545                    "%s", es->psz_language );
2546
2547     /* Add information */
2548     switch( fmt->i_cat )
2549     {
2550     case AUDIO_ES:
2551         input_Control( p_input, INPUT_ADD_INFO, psz_cat,
2552                        _("Type"), _("Audio") );
2553
2554         if( fmt->audio.i_channels > 0 )
2555             input_Control( p_input, INPUT_ADD_INFO, psz_cat, _("Channels"),
2556                            "%u", fmt->audio.i_channels );
2557
2558         if( fmt->audio.i_rate > 0 )
2559         {
2560             input_Control( p_input, INPUT_ADD_INFO, psz_cat, _("Sample rate"),
2561                            _("%u Hz"), fmt->audio.i_rate );
2562             var_SetInteger( p_input, "sample-rate", fmt->audio.i_rate );
2563         }
2564
2565         if( fmt->audio.i_bitspersample > 0 )
2566             input_Control( p_input, INPUT_ADD_INFO, psz_cat,
2567                            _("Bits per sample"), "%u",
2568                            fmt->audio.i_bitspersample );
2569
2570         if( fmt->i_bitrate > 0 )
2571         {
2572             input_Control( p_input, INPUT_ADD_INFO, psz_cat, _("Bitrate"),
2573                            _("%u kb/s"), fmt->i_bitrate / 1000 );
2574             var_SetInteger( p_input, "bit-rate", fmt->i_bitrate );
2575         }
2576         break;
2577
2578     case VIDEO_ES:
2579         input_Control( p_input, INPUT_ADD_INFO, psz_cat,
2580                        _("Type"), _("Video") );
2581
2582         if( fmt->video.i_width > 0 && fmt->video.i_height > 0 )
2583             input_Control( p_input, INPUT_ADD_INFO, psz_cat,
2584                            _("Resolution"), "%ux%u",
2585                            fmt->video.i_width, fmt->video.i_height );
2586
2587         if( fmt->video.i_visible_width > 0 &&
2588             fmt->video.i_visible_height > 0 )
2589             input_Control( p_input, INPUT_ADD_INFO, psz_cat,
2590                            _("Display resolution"), "%ux%u",
2591                            fmt->video.i_visible_width,
2592                            fmt->video.i_visible_height);
2593        if( fmt->video.i_frame_rate > 0 &&
2594            fmt->video.i_frame_rate_base > 0 )
2595        {
2596            div = lldiv( (float)fmt->video.i_frame_rate /
2597                                fmt->video.i_frame_rate_base * 1000000,
2598                                1000000 );
2599            input_Control( p_input, INPUT_ADD_INFO, psz_cat,
2600                           _("Frame rate"), "%"PRId64".%06u",
2601                           div.quot, (unsigned int )div.rem );
2602        }
2603        break;
2604
2605     case SPU_ES:
2606         input_Control( p_input, INPUT_ADD_INFO, psz_cat,
2607                        _("Type"), _("Subtitle") );
2608         break;
2609
2610     default:
2611         break;
2612     }
2613
2614     free( psz_cat );
2615 }