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