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