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