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