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