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