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