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