]> git.sesse.net Git - vlc/blob - src/input/es_out.c
1468ba4a7cf6bbddbe88e2a888104cc626134788
[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 = __MAX( (double)i_stream_duration / i_buffering_duration, 0 );
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] && *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     if( es->fmt.i_cat == AUDIO_ES )
1457         es->fmt.i_codec = vlc_fourcc_GetCodecAudio( es->fmt.i_codec,
1458                                                     es->fmt.audio.i_bitspersample );
1459     else
1460         es->fmt.i_codec = vlc_fourcc_GetCodec( es->fmt.i_cat,
1461                                                es->fmt.i_codec );
1462
1463     es->i_id = es->fmt.i_id;
1464     es->i_meta_id = out->p_sys->i_id;
1465     es->b_scrambled = false;
1466
1467     switch( es->fmt.i_cat )
1468     {
1469     case AUDIO_ES:
1470     {
1471         audio_replay_gain_t rg;
1472
1473         es->i_channel = p_sys->i_audio;
1474
1475         memset( &rg, 0, sizeof(rg) );
1476         vlc_mutex_lock( &p_input->p->p_item->lock );
1477         vlc_audio_replay_gain_MergeFromMeta( &rg, p_input->p->p_item->p_meta );
1478         vlc_mutex_unlock( &p_input->p->p_item->lock );
1479
1480         for( i = 0; i < AUDIO_REPLAY_GAIN_MAX; i++ )
1481         {
1482             if( !es->fmt.audio_replay_gain.pb_peak[i] )
1483             {
1484                 es->fmt.audio_replay_gain.pb_peak[i] = rg.pb_peak[i];
1485                 es->fmt.audio_replay_gain.pf_peak[i] = rg.pf_peak[i];
1486             }
1487             if( !es->fmt.audio_replay_gain.pb_gain[i] )
1488             {
1489                 es->fmt.audio_replay_gain.pb_gain[i] = rg.pb_gain[i];
1490                 es->fmt.audio_replay_gain.pf_gain[i] = rg.pf_gain[i];
1491             }
1492         }
1493         break;
1494     }
1495
1496     case VIDEO_ES:
1497         es->i_channel = p_sys->i_video;
1498         if( es->fmt.video.i_frame_rate && es->fmt.video.i_frame_rate_base )
1499             vlc_ureduce( &es->fmt.video.i_frame_rate,
1500                          &es->fmt.video.i_frame_rate_base,
1501                          es->fmt.video.i_frame_rate,
1502                          es->fmt.video.i_frame_rate_base, 0 );
1503         break;
1504
1505     case SPU_ES:
1506         es->i_channel = p_sys->i_sub;
1507         break;
1508
1509     default:
1510         es->i_channel = 0;
1511         break;
1512     }
1513     es->psz_language = LanguageGetName( es->fmt.psz_language ); /* remember so we only need to do it once */
1514     es->psz_language_code = LanguageGetCode( es->fmt.psz_language );
1515     es->p_dec = NULL;
1516     es->p_dec_record = NULL;
1517     for( i = 0; i < 4; i++ )
1518         es->pb_cc_present[i] = false;
1519     es->p_master = NULL;
1520
1521     if( es->p_pgrm == p_sys->p_pgrm )
1522         EsOutESVarUpdate( out, es, false );
1523
1524     /* Select it if needed */
1525     EsOutSelect( out, es, false );
1526
1527
1528     TAB_APPEND( out->p_sys->i_es, out->p_sys->es, es );
1529     p_sys->i_id++;  /* always incremented */
1530     switch( es->fmt.i_cat )
1531     {
1532         case AUDIO_ES:
1533             p_sys->i_audio++;
1534             break;
1535         case SPU_ES:
1536             p_sys->i_sub++;
1537             break;
1538         case VIDEO_ES:
1539             p_sys->i_video++;
1540             break;
1541     }
1542
1543     EsOutUpdateInfo( out, es, &es->fmt, NULL );
1544
1545     if( es->b_scrambled )
1546         EsOutProgramUpdateScrambled( out, es->p_pgrm );
1547
1548     vlc_mutex_unlock( &p_sys->lock );
1549
1550     return es;
1551 }
1552
1553 static bool EsIsSelected( es_out_id_t *es )
1554 {
1555     if( es->p_master )
1556     {
1557         bool b_decode = false;
1558         if( es->p_master->p_dec )
1559         {
1560             int i_channel = EsOutGetClosedCaptionsChannel( es->fmt.i_codec );
1561             if( i_channel != -1 )
1562                 input_DecoderGetCcState( es->p_master->p_dec, &b_decode, i_channel );
1563         }
1564         return b_decode;
1565     }
1566     else
1567     {
1568         return es->p_dec != NULL;
1569     }
1570 }
1571 static void EsCreateDecoder( es_out_t *out, es_out_id_t *p_es )
1572 {
1573     es_out_sys_t   *p_sys = out->p_sys;
1574     input_thread_t *p_input = p_sys->p_input;
1575
1576     p_es->p_dec = input_DecoderNew( p_input, &p_es->fmt, p_es->p_pgrm->p_clock, p_input->p->p_sout );
1577     if( p_es->p_dec )
1578     {
1579         if( p_sys->b_buffering )
1580             input_DecoderStartBuffering( p_es->p_dec );
1581
1582         if( !p_es->p_master && p_sys->p_sout_record )
1583         {
1584             p_es->p_dec_record = input_DecoderNew( p_input, &p_es->fmt, p_es->p_pgrm->p_clock, p_sys->p_sout_record );
1585             if( p_es->p_dec_record && p_sys->b_buffering )
1586                 input_DecoderStartBuffering( p_es->p_dec_record );
1587         }
1588     }
1589
1590     EsOutDecoderChangeDelay( out, p_es );
1591 }
1592 static void EsDestroyDecoder( es_out_t *out, es_out_id_t *p_es )
1593 {
1594     VLC_UNUSED(out);
1595
1596     if( !p_es->p_dec )
1597         return;
1598
1599     input_DecoderDelete( p_es->p_dec );
1600     p_es->p_dec = NULL;
1601
1602     if( p_es->p_dec_record )
1603     {
1604         input_DecoderDelete( p_es->p_dec_record );
1605         p_es->p_dec_record = NULL;
1606     }
1607 }
1608
1609 static void EsSelect( es_out_t *out, es_out_id_t *es )
1610 {
1611     es_out_sys_t   *p_sys = out->p_sys;
1612     input_thread_t *p_input = p_sys->p_input;
1613
1614     if( EsIsSelected( es ) )
1615     {
1616         msg_Warn( p_input, "ES 0x%x is already selected", es->i_id );
1617         return;
1618     }
1619
1620     if( es->p_master )
1621     {
1622         int i_channel;
1623         if( !es->p_master->p_dec )
1624             return;
1625
1626         i_channel = EsOutGetClosedCaptionsChannel( es->fmt.i_codec );
1627         if( i_channel == -1 || input_DecoderSetCcState( es->p_master->p_dec, true, i_channel ) )
1628             return;
1629     }
1630     else
1631     {
1632         const bool b_sout = p_input->p->p_sout != NULL;
1633         if( es->fmt.i_cat == VIDEO_ES || es->fmt.i_cat == SPU_ES )
1634         {
1635             if( !var_GetBool( p_input, b_sout ? "sout-video" : "video" ) )
1636             {
1637                 msg_Dbg( p_input, "video is disabled, not selecting ES 0x%x",
1638                          es->i_id );
1639                 return;
1640             }
1641         }
1642         else if( es->fmt.i_cat == AUDIO_ES )
1643         {
1644             if( !var_GetBool( p_input, b_sout ? "sout-audio" : "audio" ) )
1645             {
1646                 msg_Dbg( p_input, "audio is disabled, not selecting ES 0x%x",
1647                          es->i_id );
1648                 return;
1649             }
1650         }
1651         if( es->fmt.i_cat == SPU_ES )
1652         {
1653             if( !var_GetBool( p_input, b_sout ? "sout-spu" : "spu" ) )
1654             {
1655                 msg_Dbg( p_input, "spu is disabled, not selecting ES 0x%x",
1656                          es->i_id );
1657                 return;
1658             }
1659         }
1660
1661         EsCreateDecoder( out, es );
1662
1663         if( es->p_dec == NULL || es->p_pgrm != p_sys->p_pgrm )
1664             return;
1665     }
1666
1667     /* Mark it as selected */
1668     input_SendEventEsSelect( p_input, es->fmt.i_cat, es->i_id );
1669     input_SendEventTeletextSelect( p_input, EsFmtIsTeletext( &es->fmt ) ? es->i_id : -1 );
1670 }
1671
1672 static void EsUnselect( es_out_t *out, es_out_id_t *es, bool b_update )
1673 {
1674     es_out_sys_t   *p_sys = out->p_sys;
1675     input_thread_t *p_input = p_sys->p_input;
1676
1677     if( !EsIsSelected( es ) )
1678     {
1679         msg_Warn( p_input, "ES 0x%x is already unselected", es->i_id );
1680         return;
1681     }
1682
1683     if( es->p_master )
1684     {
1685         if( es->p_master->p_dec )
1686         {
1687             int i_channel = EsOutGetClosedCaptionsChannel( es->fmt.i_codec );
1688             if( i_channel != -1 )
1689                 input_DecoderSetCcState( es->p_master->p_dec, false, i_channel );
1690         }
1691     }
1692     else
1693     {
1694         const int i_spu_id = var_GetInteger( p_input, "spu-es");
1695         int i;
1696         for( i = 0; i < 4; i++ )
1697         {
1698             if( !es->pb_cc_present[i] || !es->pp_cc_es[i] )
1699                 continue;
1700
1701             if( i_spu_id == es->pp_cc_es[i]->i_id )
1702             {
1703                 /* Force unselection of the CC */
1704                 input_SendEventEsSelect( p_input, SPU_ES, -1 );
1705             }
1706             EsOutDel( out, es->pp_cc_es[i] );
1707
1708             es->pb_cc_present[i] = false;
1709         }
1710         EsDestroyDecoder( out, es );
1711     }
1712
1713     if( !b_update )
1714         return;
1715
1716     /* Mark it as unselected */
1717     input_SendEventEsSelect( p_input, es->fmt.i_cat, -1 );
1718     if( EsFmtIsTeletext( &es->fmt ) )
1719         input_SendEventTeletextSelect( p_input, -1 );
1720 }
1721
1722 /**
1723  * Select an ES given the current mode
1724  * XXX: you need to take a the lock before (stream.stream_lock)
1725  *
1726  * \param out The es_out structure
1727  * \param es es_out_id structure
1728  * \param b_force ...
1729  * \return nothing
1730  */
1731 static void EsOutSelect( es_out_t *out, es_out_id_t *es, bool b_force )
1732 {
1733     es_out_sys_t      *p_sys = out->p_sys;
1734
1735     int i_cat = es->fmt.i_cat;
1736
1737     if( !p_sys->b_active ||
1738         ( !b_force && es->fmt.i_priority < 0 ) )
1739     {
1740         return;
1741     }
1742
1743     if( p_sys->i_mode == ES_OUT_MODE_ALL || b_force )
1744     {
1745         if( !EsIsSelected( es ) )
1746             EsSelect( out, es );
1747     }
1748     else if( p_sys->i_mode == ES_OUT_MODE_PARTIAL )
1749     {
1750         char *prgms = var_GetNonEmptyString( p_sys->p_input, "programs" );
1751         if( prgms != NULL )
1752         {
1753             char *buf;
1754
1755             for ( const char *prgm = strtok_r( prgms, ",", &buf );
1756                   prgm != NULL;
1757                   prgm = strtok_r( NULL, ",", &buf ) )
1758             {
1759                 if( atoi( prgm ) == es->p_pgrm->i_id || b_force )
1760                 {
1761                     if( !EsIsSelected( es ) )
1762                         EsSelect( out, es );
1763                     break;
1764                 }
1765             }
1766             free( prgms );
1767         }
1768     }
1769     else if( p_sys->i_mode == ES_OUT_MODE_AUTO )
1770     {
1771         int i_wanted  = -1;
1772
1773         if( es->p_pgrm != p_sys->p_pgrm )
1774             return;
1775
1776         if( i_cat == AUDIO_ES )
1777         {
1778             int idx1 = LanguageArrayIndex( p_sys->ppsz_audio_language,
1779                                      es->psz_language_code );
1780
1781             if( p_sys->p_es_audio &&
1782                 p_sys->p_es_audio->fmt.i_priority >= es->fmt.i_priority )
1783             {
1784                 int idx2 = LanguageArrayIndex( p_sys->ppsz_audio_language,
1785                                          p_sys->p_es_audio->psz_language_code );
1786
1787                 if( idx1 < 0 || ( idx2 >= 0 && idx2 <= idx1 ) )
1788                     return;
1789                 i_wanted = es->i_channel;
1790             }
1791             else
1792             {
1793                 /* Select audio if (no audio selected yet)
1794                  * - no audio-language
1795                  * - no audio code for the ES
1796                  * - audio code in the requested list */
1797                 if( idx1 >= 0 ||
1798                     !strcmp( es->psz_language_code, "??" ) ||
1799                     !p_sys->ppsz_audio_language )
1800                     i_wanted = es->i_channel;
1801             }
1802
1803             if( p_sys->i_audio_last >= 0 )
1804                 i_wanted = p_sys->i_audio_last;
1805
1806             if( p_sys->i_audio_id >= 0 )
1807             {
1808                 if( es->i_id == p_sys->i_audio_id )
1809                     i_wanted = es->i_channel;
1810                 else
1811                     return;
1812             }
1813         }
1814         else if( i_cat == SPU_ES )
1815         {
1816             int idx1 = LanguageArrayIndex( p_sys->ppsz_sub_language,
1817                                      es->psz_language_code );
1818
1819             if( p_sys->p_es_sub &&
1820                 p_sys->p_es_sub->fmt.i_priority >= es->fmt.i_priority )
1821             {
1822                 int idx2 = LanguageArrayIndex( p_sys->ppsz_sub_language,
1823                                          p_sys->p_es_sub->psz_language_code );
1824
1825                 msg_Dbg( p_sys->p_input, "idx1=%d(%s) idx2=%d(%s)",
1826                         idx1, es->psz_language_code, idx2,
1827                         p_sys->p_es_sub->psz_language_code );
1828
1829                 if( idx1 < 0 || ( idx2 >= 0 && idx2 <= idx1 ) )
1830                     return;
1831                 /* We found a SPU that matches our language request */
1832                 i_wanted  = es->i_channel;
1833             }
1834             else if( idx1 >= 0 )
1835             {
1836                 msg_Dbg( p_sys->p_input, "idx1=%d(%s)",
1837                         idx1, es->psz_language_code );
1838
1839                 i_wanted  = es->i_channel;
1840             }
1841             else if( p_sys->i_default_sub_id >= 0 )
1842             {
1843                 if( es->i_id == p_sys->i_default_sub_id )
1844                     i_wanted = es->i_channel;
1845             }
1846
1847             if( p_sys->i_sub_last >= 0 )
1848                 i_wanted  = p_sys->i_sub_last;
1849
1850             if( p_sys->i_sub_id >= 0 )
1851             {
1852                 if( es->i_id == p_sys->i_sub_id )
1853                     i_wanted = es->i_channel;
1854                 else
1855                     return;
1856             }
1857         }
1858         else if( i_cat == VIDEO_ES )
1859         {
1860             i_wanted  = es->i_channel;
1861         }
1862
1863         if( i_wanted == es->i_channel && !EsIsSelected( es ) )
1864             EsSelect( out, es );
1865     }
1866
1867     /* FIXME TODO handle priority here */
1868     if( EsIsSelected( es ) )
1869     {
1870         if( i_cat == AUDIO_ES )
1871         {
1872             if( p_sys->i_mode == ES_OUT_MODE_AUTO &&
1873                 p_sys->p_es_audio &&
1874                 p_sys->p_es_audio != es &&
1875                 EsIsSelected( p_sys->p_es_audio ) )
1876             {
1877                 EsUnselect( out, p_sys->p_es_audio, false );
1878             }
1879             p_sys->p_es_audio = es;
1880         }
1881         else if( i_cat == SPU_ES )
1882         {
1883             if( p_sys->i_mode == ES_OUT_MODE_AUTO &&
1884                 p_sys->p_es_sub &&
1885                 p_sys->p_es_sub != es &&
1886                 EsIsSelected( p_sys->p_es_sub ) )
1887             {
1888                 EsUnselect( out, p_sys->p_es_sub, false );
1889             }
1890             p_sys->p_es_sub = es;
1891         }
1892         else if( i_cat == VIDEO_ES )
1893         {
1894             p_sys->p_es_video = es;
1895         }
1896     }
1897 }
1898
1899 /**
1900  * Send a block for the given es_out
1901  *
1902  * \param out the es_out to send from
1903  * \param es the es_out_id
1904  * \param p_block the data block to send
1905  */
1906 static int EsOutSend( es_out_t *out, es_out_id_t *es, block_t *p_block )
1907 {
1908     es_out_sys_t   *p_sys = out->p_sys;
1909     input_thread_t *p_input = p_sys->p_input;
1910     int i_total = 0;
1911
1912     if( libvlc_stats( p_input ) )
1913     {
1914         vlc_mutex_lock( &p_input->p->counters.counters_lock );
1915         stats_UpdateInteger( p_input, p_input->p->counters.p_demux_read,
1916                              p_block->i_buffer, &i_total );
1917         stats_UpdateFloat( p_input , p_input->p->counters.p_demux_bitrate,
1918                            (float)i_total, NULL );
1919
1920         /* Update number of corrupted data packats */
1921         if( p_block->i_flags & BLOCK_FLAG_CORRUPTED )
1922         {
1923             stats_UpdateInteger( p_input, p_input->p->counters.p_demux_corrupted,
1924                                  1, NULL );
1925         }
1926         /* Update number of discontinuities */
1927         if( p_block->i_flags & BLOCK_FLAG_DISCONTINUITY )
1928         {
1929             stats_UpdateInteger( p_input, p_input->p->counters.p_demux_discontinuity,
1930                                  1, NULL );
1931         }
1932         vlc_mutex_unlock( &p_input->p->counters.counters_lock );
1933     }
1934
1935     vlc_mutex_lock( &p_sys->lock );
1936
1937     /* Mark preroll blocks */
1938     if( p_sys->i_preroll_end >= 0 )
1939     {
1940         int64_t i_date = p_block->i_pts;
1941         if( p_block->i_pts <= VLC_TS_INVALID )
1942             i_date = p_block->i_dts;
1943
1944         if( i_date < p_sys->i_preroll_end )
1945             p_block->i_flags |= BLOCK_FLAG_PREROLL;
1946     }
1947
1948     p_block->i_rate = 0;
1949
1950     if( !es->p_dec )
1951     {
1952         block_Release( p_block );
1953         vlc_mutex_unlock( &p_sys->lock );
1954         return VLC_SUCCESS;
1955     }
1956
1957     /* Check for sout mode */
1958     if( p_input->p->p_sout )
1959     {
1960         /* FIXME review this, proper lock may be missing */
1961         if( p_input->p->p_sout->i_out_pace_nocontrol > 0 &&
1962             p_input->p->b_out_pace_control )
1963         {
1964             msg_Dbg( p_input, "switching to sync mode" );
1965             p_input->p->b_out_pace_control = false;
1966         }
1967         else if( p_input->p->p_sout->i_out_pace_nocontrol <= 0 &&
1968                  !p_input->p->b_out_pace_control )
1969         {
1970             msg_Dbg( p_input, "switching to async mode" );
1971             p_input->p->b_out_pace_control = true;
1972         }
1973     }
1974
1975     /* Decode */
1976     if( es->p_dec_record )
1977     {
1978         block_t *p_dup = block_Duplicate( p_block );
1979         if( p_dup )
1980             input_DecoderDecode( es->p_dec_record, p_dup,
1981                                  p_input->p->b_out_pace_control );
1982     }
1983     input_DecoderDecode( es->p_dec, p_block,
1984                          p_input->p->b_out_pace_control );
1985
1986     es_format_t fmt_dsc;
1987     vlc_meta_t  *p_meta_dsc;
1988     if( input_DecoderHasFormatChanged( es->p_dec, &fmt_dsc, &p_meta_dsc ) )
1989     {
1990         EsOutUpdateInfo( out, es, &fmt_dsc, p_meta_dsc );
1991
1992         es_format_Clean( &fmt_dsc );
1993         if( p_meta_dsc )
1994             vlc_meta_Delete( p_meta_dsc );
1995     }
1996
1997     /* Check CC status */
1998     bool pb_cc[4];
1999
2000     input_DecoderIsCcPresent( es->p_dec, pb_cc );
2001     for( int i = 0; i < 4; i++ )
2002     {
2003         es_format_t fmt;
2004
2005         if(  es->pb_cc_present[i] || !pb_cc[i] )
2006             continue;
2007         msg_Dbg( p_input, "Adding CC track %d for es[%d]", 1+i, es->i_id );
2008
2009         es_format_Init( &fmt, SPU_ES, EsOutFourccClosedCaptions[i] );
2010         fmt.i_group = es->fmt.i_group;
2011         if( asprintf( &fmt.psz_description,
2012                       _("Closed captions %u"), 1 + i ) == -1 )
2013             fmt.psz_description = NULL;
2014         es->pp_cc_es[i] = EsOutAdd( out, &fmt );
2015         es->pp_cc_es[i]->p_master = es;
2016         es_format_Clean( &fmt );
2017
2018         /* */
2019         es->pb_cc_present[i] = true;
2020     }
2021
2022     vlc_mutex_unlock( &p_sys->lock );
2023
2024     return VLC_SUCCESS;
2025 }
2026
2027 /*****************************************************************************
2028  * EsOutDel:
2029  *****************************************************************************/
2030 static void EsOutDel( es_out_t *out, es_out_id_t *es )
2031 {
2032     es_out_sys_t *p_sys = out->p_sys;
2033     bool b_reselect = false;
2034     int i;
2035
2036     vlc_mutex_lock( &p_sys->lock );
2037
2038     /* We don't try to reselect */
2039     if( es->p_dec )
2040     {
2041         while( !p_sys->p_input->b_die && !p_sys->b_buffering && es->p_dec )
2042         {
2043             if( input_DecoderIsEmpty( es->p_dec ) &&
2044                 ( !es->p_dec_record || input_DecoderIsEmpty( es->p_dec_record ) ))
2045                 break;
2046             /* FIXME there should be a way to have auto deleted es, but there will be
2047              * a problem when another codec of the same type is created (mainly video) */
2048             msleep( 20*1000 );
2049         }
2050         EsUnselect( out, es, es->p_pgrm == p_sys->p_pgrm );
2051     }
2052
2053     if( es->p_pgrm == p_sys->p_pgrm )
2054         EsOutESVarUpdate( out, es, true );
2055
2056     TAB_REMOVE( p_sys->i_es, p_sys->es, es );
2057
2058     /* Update program */
2059     es->p_pgrm->i_es--;
2060     if( es->p_pgrm->i_es == 0 )
2061         msg_Dbg( p_sys->p_input, "Program doesn't contain anymore ES" );
2062
2063     if( es->b_scrambled )
2064         EsOutProgramUpdateScrambled( out, es->p_pgrm );
2065
2066     /* */
2067     if( p_sys->p_es_audio == es || p_sys->p_es_video == es ||
2068         p_sys->p_es_sub == es ) b_reselect = true;
2069
2070     if( p_sys->p_es_audio == es ) p_sys->p_es_audio = NULL;
2071     if( p_sys->p_es_video == es ) p_sys->p_es_video = NULL;
2072     if( p_sys->p_es_sub   == es ) p_sys->p_es_sub   = NULL;
2073
2074     switch( es->fmt.i_cat )
2075     {
2076         case AUDIO_ES:
2077             p_sys->i_audio--;
2078             break;
2079         case SPU_ES:
2080             p_sys->i_sub--;
2081             break;
2082         case VIDEO_ES:
2083             p_sys->i_video--;
2084             break;
2085     }
2086
2087     /* Re-select another track when needed */
2088     if( b_reselect )
2089     {
2090         for( i = 0; i < p_sys->i_es; i++ )
2091         {
2092             if( es->fmt.i_cat == p_sys->es[i]->fmt.i_cat )
2093                 EsOutSelect( out, p_sys->es[i], false );
2094         }
2095     }
2096
2097     free( es->psz_language );
2098     free( es->psz_language_code );
2099
2100     es_format_Clean( &es->fmt );
2101
2102     vlc_mutex_unlock( &p_sys->lock );
2103
2104     free( es );
2105 }
2106
2107 /**
2108  * Control query handler
2109  *
2110  * \param out the es_out to control
2111  * \param i_query A es_out query as defined in include/ninput.h
2112  * \param args a variable list of arguments for the query
2113  * \return VLC_SUCCESS or an error code
2114  */
2115 static int EsOutControlLocked( es_out_t *out, int i_query, va_list args )
2116 {
2117     es_out_sys_t *p_sys = out->p_sys;
2118
2119     switch( i_query )
2120     {
2121         case ES_OUT_SET_ES_STATE:
2122         {
2123             es_out_id_t *es = va_arg( args, es_out_id_t * );
2124             bool b = va_arg( args, int );
2125             if( b && !EsIsSelected( es ) )
2126             {
2127                 EsSelect( out, es );
2128                 return EsIsSelected( es ) ? VLC_SUCCESS : VLC_EGENERIC;
2129             }
2130             else if( !b && EsIsSelected( es ) )
2131             {
2132                 EsUnselect( out, es, es->p_pgrm == p_sys->p_pgrm );
2133                 return VLC_SUCCESS;
2134             }
2135             return VLC_SUCCESS;
2136         }
2137
2138         case ES_OUT_GET_ES_STATE:
2139         {
2140             es_out_id_t *es = va_arg( args, es_out_id_t * );
2141             bool *pb = va_arg( args, bool * );
2142
2143             *pb = EsIsSelected( es );
2144             return VLC_SUCCESS;
2145         }
2146
2147         case ES_OUT_SET_MODE:
2148         {
2149             const int i_mode = va_arg( args, int );
2150             assert( i_mode == ES_OUT_MODE_NONE || i_mode == ES_OUT_MODE_ALL ||
2151                     i_mode == ES_OUT_MODE_AUTO || i_mode == ES_OUT_MODE_PARTIAL ||
2152                     i_mode == ES_OUT_MODE_END );
2153
2154             if( i_mode != ES_OUT_MODE_NONE && !p_sys->b_active && p_sys->i_es > 0 )
2155             {
2156                 /* XXX Terminate vout if there are tracks but no video one.
2157                  * This one is not mandatory but is he earliest place where it
2158                  * can be done */
2159                 int i;
2160                 for( i = 0; i < p_sys->i_es; i++ )
2161                 {
2162                     es_out_id_t *p_es = p_sys->es[i];
2163                     if( p_es->fmt.i_cat == VIDEO_ES )
2164                         break;
2165                 }
2166                 if( i >= p_sys->i_es )
2167                     input_resource_TerminateVout( p_sys->p_input->p->p_resource );
2168             }
2169             p_sys->b_active = i_mode != ES_OUT_MODE_NONE;
2170             p_sys->i_mode = i_mode;
2171
2172             /* Reapply policy mode */
2173             for( int i = 0; i < p_sys->i_es; i++ )
2174             {
2175                 if( EsIsSelected( p_sys->es[i] ) )
2176                     EsUnselect( out, p_sys->es[i],
2177                                 p_sys->es[i]->p_pgrm == p_sys->p_pgrm );
2178             }
2179             for( int i = 0; i < p_sys->i_es; i++ )
2180                 EsOutSelect( out, p_sys->es[i], false );
2181             if( i_mode == ES_OUT_MODE_END )
2182                 EsOutTerminate( out );
2183             return VLC_SUCCESS;
2184         }
2185
2186         case ES_OUT_SET_ES:
2187         case ES_OUT_RESTART_ES:
2188         {
2189             es_out_id_t *es = va_arg( args, es_out_id_t * );
2190
2191             int i_cat;
2192             if( es == NULL )
2193                 i_cat = UNKNOWN_ES;
2194             else if( es == (es_out_id_t*)((uint8_t*)NULL+AUDIO_ES) )
2195                 i_cat = AUDIO_ES;
2196             else if( es == (es_out_id_t*)((uint8_t*)NULL+VIDEO_ES) )
2197                 i_cat = VIDEO_ES;
2198             else if( es == (es_out_id_t*)((uint8_t*)NULL+SPU_ES) )
2199                 i_cat = SPU_ES;
2200             else
2201                 i_cat = -1;
2202
2203             for( int i = 0; i < p_sys->i_es; i++ )
2204             {
2205                 if( i_cat == -1 )
2206                 {
2207                     if( es == p_sys->es[i] )
2208                     {
2209                         EsOutSelect( out, es, true );
2210                         break;
2211                     }
2212                 }
2213                 else
2214                 {
2215                     if( i_cat == UNKNOWN_ES || p_sys->es[i]->fmt.i_cat == i_cat )
2216                     {
2217                         if( EsIsSelected( p_sys->es[i] ) )
2218                         {
2219                             if( i_query == ES_OUT_RESTART_ES )
2220                             {
2221                                 if( p_sys->es[i]->p_dec )
2222                                 {
2223                                     EsDestroyDecoder( out, p_sys->es[i] );
2224                                     EsCreateDecoder( out, p_sys->es[i] );
2225                                 }
2226                             }
2227                             else
2228                             {
2229                                 EsUnselect( out, p_sys->es[i],
2230                                             p_sys->es[i]->p_pgrm == p_sys->p_pgrm );
2231                             }
2232                         }
2233                     }
2234                 }
2235             }
2236             return VLC_SUCCESS;
2237         }
2238  
2239         case ES_OUT_SET_ES_DEFAULT:
2240         {
2241             es_out_id_t *es = va_arg( args, es_out_id_t * );
2242
2243             if( es == NULL )
2244             {
2245                 /*p_sys->i_default_video_id = -1;*/
2246                 /*p_sys->i_default_audio_id = -1;*/
2247                 p_sys->i_default_sub_id = -1;
2248             }
2249             else if( es == (es_out_id_t*)((uint8_t*)NULL+AUDIO_ES) )
2250             {
2251                 /*p_sys->i_default_video_id = -1;*/
2252             }
2253             else if( es == (es_out_id_t*)((uint8_t*)NULL+VIDEO_ES) )
2254             {
2255                 /*p_sys->i_default_audio_id = -1;*/
2256             }
2257             else if( es == (es_out_id_t*)((uint8_t*)NULL+SPU_ES) )
2258             {
2259                 p_sys->i_default_sub_id = -1;
2260             }
2261             else
2262             {
2263                 /*if( es->fmt.i_cat == VIDEO_ES )
2264                     p_sys->i_default_video_id = es->i_id;
2265                 else
2266                 if( es->fmt.i_cat == AUDIO_ES )
2267                     p_sys->i_default_audio_id = es->i_id;
2268                 else*/
2269                 if( es->fmt.i_cat == SPU_ES )
2270                     p_sys->i_default_sub_id = es->i_id;
2271             }
2272             return VLC_SUCCESS;
2273         }
2274
2275         case ES_OUT_SET_PCR:
2276         case ES_OUT_SET_GROUP_PCR:
2277         {
2278             es_out_pgrm_t *p_pgrm = NULL;
2279             int            i_group = 0;
2280             int64_t        i_pcr;
2281
2282             /* Search program */
2283             if( i_query == ES_OUT_SET_PCR )
2284             {
2285                 p_pgrm = p_sys->p_pgrm;
2286                 if( !p_pgrm )
2287                     p_pgrm = EsOutProgramAdd( out, i_group );   /* Create it */
2288             }
2289             else
2290             {
2291                 i_group = (int)va_arg( args, int );
2292                 p_pgrm = EsOutProgramFind( out, i_group );
2293             }
2294             if( !p_pgrm )
2295                 return VLC_EGENERIC;
2296
2297             i_pcr = (int64_t)va_arg( args, int64_t );
2298             if( i_pcr <= VLC_TS_INVALID )
2299             {
2300                 msg_Err( p_sys->p_input, "Invalid PCR value in ES_OUT_SET_(GROUP_)PCR !" );
2301                 return VLC_EGENERIC;
2302             }
2303
2304             /* TODO do not use mdate() but proper stream acquisition date */
2305             bool b_late;
2306             input_clock_Update( p_pgrm->p_clock, VLC_OBJECT(p_sys->p_input),
2307                                 &b_late,
2308                                 p_sys->p_input->p->b_can_pace_control || p_sys->b_buffering,
2309                                 EsOutIsExtraBufferingAllowed( out ),
2310                                 i_pcr, mdate() );
2311
2312             if( p_pgrm == p_sys->p_pgrm )
2313             {
2314                 if( p_sys->b_buffering )
2315                 {
2316                     /* Check buffering state on master clock update */
2317                     EsOutDecodersStopBuffering( out, false );
2318                 }
2319                 else if( b_late && ( !p_sys->p_input->p->p_sout ||
2320                                      !p_sys->p_input->p->b_out_pace_control ) )
2321                 {
2322                     const mtime_t i_pts_delay_base = p_sys->i_pts_delay - p_sys->i_pts_jitter;
2323                     mtime_t i_pts_delay = input_clock_GetJitter( p_pgrm->p_clock );
2324
2325                     /* Avoid dangerously high value */
2326                     const mtime_t i_jitter_max = INT64_C(1000) * var_InheritInteger( p_sys->p_input, "clock-jitter" );
2327                     if( i_pts_delay > __MIN( i_pts_delay_base + i_jitter_max, INPUT_PTS_DELAY_MAX ) )
2328                     {
2329                         msg_Err( p_sys->p_input,
2330                                  "ES_OUT_SET_(GROUP_)PCR  is called too late (jitter of %d ms ignored)",
2331                                  (int)(i_pts_delay - i_pts_delay_base) / 1000 );
2332                         i_pts_delay = p_sys->i_pts_delay;
2333                     }
2334                     else
2335                     {
2336                         msg_Err( p_sys->p_input,
2337                                  "ES_OUT_SET_(GROUP_)PCR  is called too late (pts_delay increased to %d ms)",
2338                                  (int)(i_pts_delay/1000) );
2339                     }
2340
2341                     /* Force a rebufferization when we are too late */
2342
2343                     /* It is not really good, as we throw away already buffered data
2344                      * TODO have a mean to correctly reenter bufferization */
2345                     es_out_Control( out, ES_OUT_RESET_PCR );
2346
2347                     es_out_SetJitter( out, i_pts_delay_base, i_pts_delay - i_pts_delay_base, p_sys->i_cr_average );
2348                 }
2349             }
2350             return VLC_SUCCESS;
2351         }
2352
2353         case ES_OUT_RESET_PCR:
2354             msg_Err( p_sys->p_input, "ES_OUT_RESET_PCR called" );
2355             EsOutChangePosition( out );
2356             return VLC_SUCCESS;
2357
2358         case ES_OUT_SET_GROUP:
2359         {
2360             int i = va_arg( args, int );
2361             for( int j = 0; j < p_sys->i_pgrm; j++ )
2362             {
2363                 es_out_pgrm_t *p_pgrm = p_sys->pgrm[j];
2364                 if( p_pgrm->i_id == i )
2365                 {
2366                     EsOutProgramSelect( out, p_pgrm );
2367                     return VLC_SUCCESS;
2368                 }
2369             }
2370             return VLC_EGENERIC;
2371         }
2372
2373         case ES_OUT_SET_ES_FMT:
2374         {
2375             /* This ain't pretty but is need by some demuxers (eg. Ogg )
2376              * to update the p_extra data */
2377             es_out_id_t *es = va_arg( args, es_out_id_t * );
2378             es_format_t *p_fmt = va_arg( args, es_format_t * );
2379             if( es == NULL )
2380                 return VLC_EGENERIC;
2381
2382             if( p_fmt->i_extra )
2383             {
2384                 es->fmt.i_extra = p_fmt->i_extra;
2385                 es->fmt.p_extra = xrealloc( es->fmt.p_extra, p_fmt->i_extra );
2386                 memcpy( es->fmt.p_extra, p_fmt->p_extra, p_fmt->i_extra );
2387
2388                 if( !es->p_dec )
2389                     return VLC_SUCCESS;
2390 #if 1
2391                 EsDestroyDecoder( out, es );
2392
2393                 EsCreateDecoder( out, es );
2394 #else
2395                 es->p_dec->fmt_in.i_extra = p_fmt->i_extra;
2396                 es->p_dec->fmt_in.p_extra =
2397                   xrealloc( es->p_dec->fmt_in.p_extra, p_fmt->i_extra );
2398                 memcpy( es->p_dec->fmt_in.p_extra,
2399                         p_fmt->p_extra, p_fmt->i_extra );
2400 #endif
2401             }
2402
2403             return VLC_SUCCESS;
2404         }
2405
2406         case ES_OUT_SET_ES_SCRAMBLED_STATE:
2407         {
2408             es_out_id_t *es = va_arg( args, es_out_id_t * );
2409             bool b_scrambled = (bool)va_arg( args, int );
2410
2411             if( !es->b_scrambled != !b_scrambled )
2412             {
2413                 es->b_scrambled = b_scrambled;
2414                 EsOutProgramUpdateScrambled( out, es->p_pgrm );
2415             }
2416             return VLC_SUCCESS;
2417         }
2418
2419         case ES_OUT_SET_NEXT_DISPLAY_TIME:
2420         {
2421             const int64_t i_date = (int64_t)va_arg( args, int64_t );
2422
2423             if( i_date < 0 )
2424                 return VLC_EGENERIC;
2425
2426             p_sys->i_preroll_end = i_date;
2427
2428             return VLC_SUCCESS;
2429         }
2430         case ES_OUT_SET_GROUP_META:
2431         {
2432             int i_group = (int)va_arg( args, int );
2433             const vlc_meta_t *p_meta = va_arg( args, const vlc_meta_t * );
2434
2435             EsOutProgramMeta( out, i_group, p_meta );
2436             return VLC_SUCCESS;
2437         }
2438         case ES_OUT_SET_GROUP_EPG:
2439         {
2440             int i_group = (int)va_arg( args, int );
2441             const vlc_epg_t *p_epg = va_arg( args, const vlc_epg_t * );
2442
2443             EsOutProgramEpg( out, i_group, p_epg );
2444             return VLC_SUCCESS;
2445         }
2446
2447         case ES_OUT_DEL_GROUP:
2448         {
2449             int i_group = (int)va_arg( args, int );
2450
2451             return EsOutProgramDel( out, i_group );
2452         }
2453
2454         case ES_OUT_SET_META:
2455         {
2456             const vlc_meta_t *p_meta = va_arg( args, const vlc_meta_t * );
2457
2458             EsOutMeta( out, p_meta );
2459             return VLC_SUCCESS;
2460         }
2461
2462         case ES_OUT_GET_WAKE_UP:
2463         {
2464             mtime_t *pi_wakeup = (mtime_t*)va_arg( args, mtime_t* );
2465             *pi_wakeup = EsOutGetWakeup( out );
2466             return VLC_SUCCESS;
2467         }
2468
2469         case ES_OUT_SET_ES_BY_ID:
2470         case ES_OUT_RESTART_ES_BY_ID:
2471         case ES_OUT_SET_ES_DEFAULT_BY_ID:
2472         {
2473             const int i_id = (int)va_arg( args, int );
2474             es_out_id_t *p_es = EsOutGetFromID( out, i_id );
2475             int i_new_query;
2476
2477             switch( i_query )
2478             {
2479             case ES_OUT_SET_ES_BY_ID:         i_new_query = ES_OUT_SET_ES; break;
2480             case ES_OUT_RESTART_ES_BY_ID:     i_new_query = ES_OUT_RESTART_ES; break;
2481             case ES_OUT_SET_ES_DEFAULT_BY_ID: i_new_query = ES_OUT_SET_ES_DEFAULT; break;
2482             default:
2483               assert(0);
2484             }
2485             /* TODO if the lock is made non recursive it should be changed */
2486             int i_ret = es_out_Control( out, i_new_query, p_es );
2487
2488             /* Clean up vout after user action (in active mode only).
2489              * FIXME it does not work well with multiple video windows */
2490             if( p_sys->b_active )
2491                 input_resource_TerminateVout( p_sys->p_input->p->p_resource );
2492             return i_ret;
2493         }
2494
2495         case ES_OUT_GET_ES_OBJECTS_BY_ID:
2496         {
2497             const int i_id = va_arg( args, int );
2498             es_out_id_t *p_es = EsOutGetFromID( out, i_id );
2499             if( !p_es )
2500                 return VLC_EGENERIC;
2501
2502             vlc_object_t    **pp_decoder = va_arg( args, vlc_object_t ** );
2503             vout_thread_t   **pp_vout    = va_arg( args, vout_thread_t ** );
2504             aout_instance_t **pp_aout    = va_arg( args, aout_instance_t ** );
2505             if( p_es->p_dec )
2506             {
2507                 if( pp_decoder )
2508                     *pp_decoder = vlc_object_hold( p_es->p_dec );
2509                 input_DecoderGetObjects( p_es->p_dec, pp_vout, pp_aout );
2510             }
2511             else
2512             {
2513                 if( pp_decoder )
2514                     *pp_decoder = NULL;
2515                 if( pp_vout )
2516                     *pp_vout = NULL;
2517                 if( pp_aout )
2518                     *pp_aout = NULL;
2519             }
2520             return VLC_SUCCESS;
2521         }
2522
2523         case ES_OUT_GET_BUFFERING:
2524         {
2525             bool *pb = va_arg( args, bool* );
2526             *pb = p_sys->b_buffering;
2527             return VLC_SUCCESS;
2528         }
2529
2530         case ES_OUT_GET_EMPTY:
2531         {
2532             bool *pb = va_arg( args, bool* );
2533             *pb = EsOutDecodersIsEmpty( out );
2534             return VLC_SUCCESS;
2535         }
2536
2537         case ES_OUT_SET_DELAY:
2538         {
2539             const int i_cat = (int)va_arg( args, int );
2540             const mtime_t i_delay = (mtime_t)va_arg( args, mtime_t );
2541             EsOutSetDelay( out, i_cat, i_delay );
2542             return VLC_SUCCESS;
2543         }
2544
2545         case ES_OUT_SET_RECORD_STATE:
2546         {
2547             bool b = va_arg( args, int );
2548             return EsOutSetRecord( out, b );
2549         }
2550
2551         case ES_OUT_SET_PAUSE_STATE:
2552         {
2553             const bool b_source_paused = (bool)va_arg( args, int );
2554             const bool b_paused = (bool)va_arg( args, int );
2555             const mtime_t i_date = (mtime_t) va_arg( args, mtime_t );
2556
2557             assert( !b_source_paused == !b_paused );
2558             EsOutChangePause( out, b_paused, i_date );
2559
2560             return VLC_SUCCESS;
2561         }
2562
2563         case ES_OUT_SET_RATE:
2564         {
2565             const int i_src_rate = (int)va_arg( args, int );
2566             const int i_rate = (int)va_arg( args, int );
2567
2568             assert( i_src_rate == i_rate );
2569             EsOutChangeRate( out, i_rate );
2570
2571             return VLC_SUCCESS;
2572         }
2573
2574         case ES_OUT_SET_TIME:
2575         {
2576             const mtime_t i_date = (mtime_t)va_arg( args, mtime_t );
2577
2578             assert( i_date == -1 );
2579             EsOutChangePosition( out );
2580
2581             return VLC_SUCCESS;
2582         }
2583
2584         case ES_OUT_SET_FRAME_NEXT:
2585             EsOutFrameNext( out );
2586             return VLC_SUCCESS;
2587
2588         case ES_OUT_SET_TIMES:
2589         {
2590             double f_position = (double)va_arg( args, double );
2591             mtime_t i_time = (mtime_t)va_arg( args, mtime_t );
2592             mtime_t i_length = (mtime_t)va_arg( args, mtime_t );
2593
2594             input_SendEventLength( p_sys->p_input, i_length );
2595
2596             if( !p_sys->b_buffering )
2597             {
2598                 mtime_t i_delay;
2599
2600                 /* Fix for buffering delay */
2601                 if( !p_sys->p_input->p->p_sout ||
2602                     !p_sys->p_input->p->b_out_pace_control )
2603                     i_delay = EsOutGetBuffering( out );
2604                 else
2605                     i_delay = 0;
2606
2607                 i_time -= i_delay;
2608                 if( i_time < 0 )
2609                     i_time = 0;
2610
2611                 if( i_length > 0 )
2612                     f_position -= (double)i_delay / i_length;
2613                 if( f_position < 0 )
2614                     f_position = 0;
2615
2616                 input_SendEventPosition( p_sys->p_input, f_position, i_time );
2617             }
2618             return VLC_SUCCESS;
2619         }
2620         case ES_OUT_SET_JITTER:
2621         {
2622             mtime_t i_pts_delay  = (mtime_t)va_arg( args, mtime_t );
2623             mtime_t i_pts_jitter = (mtime_t)va_arg( args, mtime_t );
2624             int     i_cr_average = (int)va_arg( args, int );
2625
2626             bool b_change_clock =
2627                 i_pts_delay + i_pts_jitter != p_sys->i_pts_delay ||
2628                 i_cr_average != p_sys->i_cr_average;
2629
2630             assert( i_pts_jitter >= 0 );
2631             p_sys->i_pts_delay  = i_pts_delay + i_pts_jitter;
2632             p_sys->i_pts_jitter = i_pts_jitter;
2633             p_sys->i_cr_average = i_cr_average;
2634
2635             for( int i = 0; i < p_sys->i_pgrm && b_change_clock; i++ )
2636                 input_clock_SetJitter( p_sys->pgrm[i]->p_clock,
2637                                        i_pts_delay + i_pts_jitter, i_cr_average );
2638             return VLC_SUCCESS;
2639         }
2640
2641         case ES_OUT_GET_PCR_SYSTEM:
2642         {
2643             if( p_sys->b_buffering )
2644                 return VLC_EGENERIC;
2645
2646             es_out_pgrm_t *p_pgrm = p_sys->p_pgrm;
2647             if( !p_pgrm )
2648                 return VLC_EGENERIC;
2649
2650             mtime_t *pi_system = va_arg( args, mtime_t *);
2651             mtime_t *pi_delay  = va_arg( args, mtime_t *);
2652             input_clock_GetSystemOrigin( p_pgrm->p_clock, pi_system, pi_delay );
2653             return VLC_SUCCESS;
2654         }
2655
2656         case ES_OUT_MODIFY_PCR_SYSTEM:
2657         {
2658             if( p_sys->b_buffering )
2659                 return VLC_EGENERIC;
2660
2661             es_out_pgrm_t *p_pgrm = p_sys->p_pgrm;
2662             if( !p_pgrm )
2663                 return VLC_EGENERIC;
2664
2665             const bool    b_absolute = va_arg( args, int );
2666             const mtime_t i_system   = va_arg( args, mtime_t );
2667             input_clock_ChangeSystemOrigin( p_pgrm->p_clock, b_absolute, i_system );
2668             return VLC_SUCCESS;
2669         }
2670
2671         default:
2672             msg_Err( p_sys->p_input, "unknown query in es_out_Control" );
2673             return VLC_EGENERIC;
2674     }
2675 }
2676 static int EsOutControl( es_out_t *out, int i_query, va_list args )
2677 {
2678     es_out_sys_t *p_sys = out->p_sys;
2679     int i_ret;
2680
2681     vlc_mutex_lock( &p_sys->lock );
2682     i_ret = EsOutControlLocked( out, i_query, args );
2683     vlc_mutex_unlock( &p_sys->lock );
2684
2685     return i_ret;
2686 }
2687
2688 /****************************************************************************
2689  * LanguageGetName: try to expend iso639 into plain name
2690  ****************************************************************************/
2691 static char *LanguageGetName( const char *psz_code )
2692 {
2693     const iso639_lang_t *pl;
2694
2695     if( psz_code == NULL )
2696     {
2697         return strdup( "" );
2698     }
2699
2700     if( strlen( psz_code ) == 2 )
2701     {
2702         pl = GetLang_1( psz_code );
2703     }
2704     else if( strlen( psz_code ) == 3 )
2705     {
2706         pl = GetLang_2B( psz_code );
2707         if( !strcmp( pl->psz_iso639_1, "??" ) )
2708         {
2709             pl = GetLang_2T( psz_code );
2710         }
2711     }
2712     else
2713     {
2714         return strdup( psz_code );
2715     }
2716
2717     if( !strcmp( pl->psz_iso639_1, "??" ) )
2718     {
2719        return strdup( psz_code );
2720     }
2721     else
2722     {
2723         if( *pl->psz_native_name )
2724         {
2725             return strdup( pl->psz_native_name );
2726         }
2727         return strdup( pl->psz_eng_name );
2728     }
2729 }
2730
2731 /* Get a 2 char code */
2732 static char *LanguageGetCode( const char *psz_lang )
2733 {
2734     const iso639_lang_t *pl;
2735
2736     if( psz_lang == NULL || *psz_lang == '\0' )
2737         return strdup("??");
2738
2739     for( pl = p_languages; pl->psz_eng_name != NULL; pl++ )
2740     {
2741         if( !strcasecmp( pl->psz_eng_name, psz_lang ) ||
2742             !strcasecmp( pl->psz_native_name, psz_lang ) ||
2743             !strcasecmp( pl->psz_iso639_1, psz_lang ) ||
2744             !strcasecmp( pl->psz_iso639_2T, psz_lang ) ||
2745             !strcasecmp( pl->psz_iso639_2B, psz_lang ) )
2746             break;
2747     }
2748
2749     if( pl->psz_eng_name != NULL )
2750         return strdup( pl->psz_iso639_1 );
2751
2752     return strdup("??");
2753 }
2754
2755 static char **LanguageSplit( const char *psz_langs, bool b_default_any )
2756 {
2757     char *psz_dup;
2758     char *psz_parser;
2759     char **ppsz = NULL;
2760     int i_psz = 0;
2761
2762     if( psz_langs == NULL ) return NULL;
2763
2764     psz_parser = psz_dup = strdup(psz_langs);
2765
2766     while( psz_parser && *psz_parser )
2767     {
2768         char *psz;
2769         char *psz_code;
2770
2771         psz = strchr(psz_parser, ',' );
2772         if( psz ) *psz++ = '\0';
2773
2774         if( !strcmp( psz_parser, "any" ) )
2775         {
2776             TAB_APPEND( i_psz, ppsz, strdup("any") );
2777         }
2778         else if( !strcmp( psz_parser, "none" ) )
2779         {
2780             TAB_APPEND( i_psz, ppsz, strdup("none") );
2781         }
2782         else
2783         {
2784             psz_code = LanguageGetCode( psz_parser );
2785             if( strcmp( psz_code, "??" ) )
2786             {
2787                 TAB_APPEND( i_psz, ppsz, psz_code );
2788             }
2789             else
2790             {
2791                 free( psz_code );
2792             }
2793         }
2794
2795         psz_parser = psz;
2796     }
2797
2798     if( i_psz )
2799     {
2800         if( b_default_any && strcmp( ppsz[i_psz - 1], "none" ) )
2801             TAB_APPEND( i_psz, ppsz, strdup("any") );
2802         TAB_APPEND( i_psz, ppsz, NULL );
2803     }
2804
2805     free( psz_dup );
2806     return ppsz;
2807 }
2808
2809 static int LanguageArrayIndex( char **ppsz_langs, char *psz_lang )
2810 {
2811     int i;
2812
2813     if( !ppsz_langs || !psz_lang ) return -1;
2814
2815     for( i = 0; ppsz_langs[i]; i++ )
2816     {
2817         if( !strcasecmp( ppsz_langs[i], psz_lang ) ||
2818             !strcasecmp( ppsz_langs[i], "any" ) )
2819             return i;
2820         if( !strcasecmp( ppsz_langs[i], "none" ) )
2821             break;
2822     }
2823
2824     return -1;
2825 }
2826
2827 /****************************************************************************
2828  * EsOutUpdateInfo:
2829  * - add meta info to the playlist item
2830  ****************************************************************************/
2831 static void EsOutUpdateInfo( es_out_t *out, es_out_id_t *es, const es_format_t *fmt, const vlc_meta_t *p_meta )
2832 {
2833     es_out_sys_t   *p_sys = out->p_sys;
2834     input_thread_t *p_input = p_sys->p_input;
2835     const es_format_t *p_fmt_es = &es->fmt;
2836     lldiv_t         div;
2837
2838     /* Create category */
2839     char psz_cat[128];
2840     snprintf( psz_cat, sizeof(psz_cat),_("Stream %d"), es->i_meta_id );
2841     info_category_t *p_cat = info_category_New( psz_cat );
2842     if( !p_cat )
2843         return;
2844
2845     /* Add informations */
2846     const char *psz_type;
2847     switch( fmt->i_cat )
2848     {
2849     case AUDIO_ES:
2850         psz_type = _("Audio");
2851         break;
2852     case VIDEO_ES:
2853         psz_type = _("Video");
2854         break;
2855     case SPU_ES:
2856         psz_type = _("Subtitle");
2857         break;
2858     default:
2859         psz_type = NULL;
2860         break;
2861     }
2862
2863     if( psz_type )
2864         info_category_AddInfo( p_cat, _("Type"), "%s", psz_type );
2865
2866     if( es->i_meta_id != es->i_id )
2867         info_category_AddInfo( p_cat, _("Original ID"),
2868                        "%d", es->i_id );
2869
2870     const char *psz_codec_description =
2871         vlc_fourcc_GetDescription( p_fmt_es->i_cat, p_fmt_es->i_codec );
2872     const vlc_fourcc_t i_codec_fourcc = p_fmt_es->i_original_fourcc ?: p_fmt_es->i_codec;
2873     if( psz_codec_description )
2874         info_category_AddInfo( p_cat, _("Codec"), "%s (%.4s)",
2875                                psz_codec_description, (char*)&i_codec_fourcc );
2876     else
2877         info_category_AddInfo( p_cat, _("Codec"), "%.4s",
2878                                (char*)&i_codec_fourcc );
2879
2880     if( es->psz_language && *es->psz_language )
2881         info_category_AddInfo( p_cat, _("Language"), "%s",
2882                                es->psz_language );
2883     if( fmt->psz_description && *fmt->psz_description )
2884         info_category_AddInfo( p_cat, _("Description"), "%s",
2885                                fmt->psz_description );
2886
2887     switch( fmt->i_cat )
2888     {
2889     case AUDIO_ES:
2890         info_category_AddInfo( p_cat, _("Type"), _("Audio") );
2891
2892         if( fmt->audio.i_physical_channels & AOUT_CHAN_PHYSMASK )
2893             info_category_AddInfo( p_cat, _("Channels"), "%s",
2894                                    _( aout_FormatPrintChannels( &fmt->audio ) ) );
2895         else if( fmt->audio.i_channels > 0 )
2896             info_category_AddInfo( p_cat, _("Channels"), "%u",
2897                                    fmt->audio.i_channels );
2898
2899         if( fmt->audio.i_rate > 0 )
2900         {
2901             info_category_AddInfo( p_cat, _("Sample rate"), _("%u Hz"),
2902                                    fmt->audio.i_rate );
2903             /* FIXME that should be removed or improved ! (used by text/strings.c) */
2904             var_SetInteger( p_input, "sample-rate", fmt->audio.i_rate );
2905         }
2906
2907         unsigned int i_bitspersample = fmt->audio.i_bitspersample;
2908         if( i_bitspersample <= 0 )
2909             i_bitspersample = aout_BitsPerSample( p_fmt_es->i_codec );
2910         if( i_bitspersample > 0 )
2911             info_category_AddInfo( p_cat, _("Bits per sample"), "%u",
2912                                    i_bitspersample );
2913
2914         if( fmt->i_bitrate > 0 )
2915         {
2916             info_category_AddInfo( p_cat, _("Bitrate"), _("%u kb/s"),
2917                                    fmt->i_bitrate / 1000 );
2918             /* FIXME that should be removed or improved ! (used by text/strings.c) */
2919             var_SetInteger( p_input, "bit-rate", fmt->i_bitrate );
2920         }
2921         for( int i = 0; i < AUDIO_REPLAY_GAIN_MAX; i++ )
2922         {
2923             const audio_replay_gain_t *p_rg = &fmt->audio_replay_gain;
2924             if( !p_rg->pb_gain[i] )
2925                 continue;
2926             const char *psz_name;
2927             if( i == AUDIO_REPLAY_GAIN_TRACK )
2928                 psz_name = _("Track replay gain");
2929             else
2930                 psz_name = _("Album replay gain");
2931             info_category_AddInfo( p_cat, psz_name, _("%.2f dB"),
2932                                    p_rg->pf_gain[i] );
2933         }
2934         break;
2935
2936     case VIDEO_ES:
2937         info_category_AddInfo( p_cat, _("Type"), _("Video") );
2938
2939         if( fmt->video.i_width > 0 && fmt->video.i_height > 0 )
2940             info_category_AddInfo( p_cat, _("Resolution"), "%ux%u",
2941                                    fmt->video.i_width, fmt->video.i_height );
2942
2943         if( fmt->video.i_visible_width > 0 &&
2944             fmt->video.i_visible_height > 0 )
2945             info_category_AddInfo( p_cat, _("Display resolution"), "%ux%u",
2946                                    fmt->video.i_visible_width,
2947                                    fmt->video.i_visible_height);
2948        if( fmt->video.i_frame_rate > 0 &&
2949            fmt->video.i_frame_rate_base > 0 )
2950        {
2951            div = lldiv( (float)fmt->video.i_frame_rate /
2952                                fmt->video.i_frame_rate_base * 1000000,
2953                                1000000 );
2954            if( div.rem > 0 )
2955                info_category_AddInfo( p_cat, _("Frame rate"), "%"PRId64".%06u",
2956                                       div.quot, (unsigned int )div.rem );
2957            else
2958                info_category_AddInfo( p_cat, _("Frame rate"), "%"PRId64,
2959                                       div.quot );
2960        }
2961        break;
2962
2963     case SPU_ES:
2964         info_category_AddInfo( p_cat, _("Type"), _("Subtitle") );
2965         break;
2966
2967     default:
2968         break;
2969     }
2970
2971     /* Append generic meta */
2972     if( p_meta )
2973     {
2974         char **ppsz_all_keys = vlc_meta_CopyExtraNames( p_meta );
2975         for( int i = 0; ppsz_all_keys && ppsz_all_keys[i]; i++ )
2976         {
2977             char *psz_key = ppsz_all_keys[i];
2978             const char *psz_value = vlc_meta_GetExtra( p_meta, psz_key );
2979
2980             if( psz_value )
2981                 info_category_AddInfo( p_cat, vlc_gettext(psz_key), "%s",
2982                                        vlc_gettext(psz_value) );
2983             free( psz_key );
2984         }
2985         free( ppsz_all_keys );
2986     }
2987     /* */
2988     input_Control( p_input, INPUT_REPLACE_INFOS, p_cat );
2989 }
2990