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