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