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