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