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