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