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