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