]> git.sesse.net Git - vlc/blob - modules/demux/ts.c
TS: remove useless --ts-silent option
[vlc] / modules / demux / ts.c
1 /*****************************************************************************
2  * ts.c: Transport Stream input module for VLC.
3  *****************************************************************************
4  * Copyright (C) 2004-2005 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Jean-Paul Saman <jpsaman #_at_# m2x.nl>
9  *
10  * This program is free software; you can redistribute it and/or modify it
11  * under the terms of the GNU Lesser General Public License as published by
12  * the Free Software Foundation; either version 2.1 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this program; if not, write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <vlc_common.h>
34 #include <vlc_plugin.h>
35
36 #include <assert.h>
37
38 #include <vlc_access.h>    /* DVB-specific things */
39 #include <vlc_demux.h>
40 #include <vlc_meta.h>
41 #include <vlc_epg.h>
42 #include <vlc_charset.h>   /* FromCharset, for EIT */
43
44 #include <vlc_network.h>   /* net_ for ts-out mode */
45
46 #include "../mux/mpeg/csa.h"
47
48 /* Include dvbpsi headers */
49 # include <dvbpsi/dvbpsi.h>
50 # include <dvbpsi/demux.h>
51 # include <dvbpsi/descriptor.h>
52 # include <dvbpsi/pat.h>
53 # include <dvbpsi/pmt.h>
54 # include <dvbpsi/sdt.h>
55 # include <dvbpsi/dr.h>
56 # include <dvbpsi/psi.h>
57
58 /* EIT support */
59 # include <dvbpsi/eit.h>
60
61 /* TDT support */
62 # include <dvbpsi/tot.h>
63
64 #undef TS_DEBUG
65 VLC_FORMAT(1, 2) static void ts_debug(const char *format, ...)
66 {
67 #ifdef TS_DEBUG
68     va_list ap;
69     va_start(ap, format);
70     vfprintf(stderr, format, ap);
71     va_end(ap);
72 #else
73     (void)format;
74 #endif
75 }
76
77 /*****************************************************************************
78  * Module descriptor
79  *****************************************************************************/
80 static int  Open  ( vlc_object_t * );
81 static void Close ( vlc_object_t * );
82
83 /* TODO
84  * - Rename "extra pmt" to "user pmt"
85  * - Update extra pmt description
86  *      pmt_pid[:pmt_number][=pid_description[,pid_description]]
87  *      where pid_description could take 3 forms:
88  *          1. pid:pcr (to force the pcr pid)
89  *          2. pid:stream_type
90  *          3. pid:type=fourcc where type=(video|audio|spu)
91  */
92 #define PMT_TEXT N_("Extra PMT")
93 #define PMT_LONGTEXT N_( \
94   "Allows a user to specify an extra pmt (pmt_pid=pid:stream_type[,...])." )
95
96 #define PID_TEXT N_("Set id of ES to PID")
97 #define PID_LONGTEXT N_("Set the internal ID of each elementary stream" \
98                        " handled by VLC to the same value as the PID in" \
99                        " the TS stream, instead of 1, 2, 3, etc. Useful to" \
100                        " do \'#duplicate{..., select=\"es=<pid>\"}\'.")
101
102 #define TSOUT_TEXT N_("Fast udp streaming")
103 #define TSOUT_LONGTEXT N_( \
104   "Sends TS to specific ip:port by udp (you must know what you are doing).")
105
106 #define MTUOUT_TEXT N_("MTU for out mode")
107 #define MTUOUT_LONGTEXT N_("MTU for out mode.")
108
109 #define CSA_TEXT N_("CSA Key")
110 #define CSA_LONGTEXT N_("CSA encryption key. This must be a " \
111   "16 char string (8 hexadecimal bytes).")
112
113 #define CSA2_TEXT N_("Second CSA Key")
114 #define CSA2_LONGTEXT N_("The even CSA encryption key. This must be a " \
115   "16 char string (8 hexadecimal bytes).")
116
117
118 #define CPKT_TEXT N_("Packet size in bytes to decrypt")
119 #define CPKT_LONGTEXT N_("Specify the size of the TS packet to decrypt. " \
120     "The decryption routines subtract the TS-header from the value before " \
121     "decrypting. " )
122
123 #define SPLIT_ES_TEXT N_("Separate sub-streams")
124 #define SPLIT_ES_LONGTEXT N_( \
125     "Separate teletex/dvbs pages into independent ES. " \
126     "It can be useful to turn off this option when using stream output." )
127
128 #define SEEK_PERCENT_TEXT N_("Seek based on percent not time")
129 #define SEEK_PERCENT_LONGTEXT N_( \
130     "Seek and position based on a percent byte position, not a PCR generated " \
131     "time position. If seeking doesn't work property, turn on this option." )
132
133
134 vlc_module_begin ()
135     set_description( N_("MPEG Transport Stream demuxer") )
136     set_shortname ( "MPEG-TS" )
137     set_category( CAT_INPUT )
138     set_subcategory( SUBCAT_INPUT_DEMUX )
139
140     add_string( "ts-extra-pmt", NULL, PMT_TEXT, PMT_LONGTEXT, true )
141     add_bool( "ts-es-id-pid", true, PID_TEXT, PID_LONGTEXT, true )
142         change_safe()
143     add_string( "ts-out", NULL, TSOUT_TEXT, TSOUT_LONGTEXT, true )
144     add_integer( "ts-out-mtu", 1400, MTUOUT_TEXT,
145                  MTUOUT_LONGTEXT, true )
146
147     add_string( "ts-csa-ck", NULL, CSA_TEXT, CSA_LONGTEXT, true )
148         change_safe()
149     add_string( "ts-csa2-ck", NULL, CSA2_TEXT, CSA2_LONGTEXT, true )
150         change_safe()
151     add_integer( "ts-csa-pkt", 188, CPKT_TEXT, CPKT_LONGTEXT, true )
152         change_safe()
153
154     add_bool( "ts-split-es", true, SPLIT_ES_TEXT, SPLIT_ES_LONGTEXT, false )
155     add_bool( "ts-seek-percent", false, SEEK_PERCENT_TEXT, SEEK_PERCENT_LONGTEXT, true )
156
157     add_obsolete_bool( "ts-silent" );
158
159     set_capability( "demux", 10 )
160     set_callbacks( Open, Close )
161     add_shortcut( "ts" )
162 vlc_module_end ()
163
164 /*****************************************************************************
165  * Local prototypes
166  *****************************************************************************/
167 static const char *const ppsz_teletext_type[] = {
168  "",
169  N_("Teletext"),
170  N_("Teletext subtitles"),
171  N_("Teletext: additional information"),
172  N_("Teletext: program schedule"),
173  N_("Teletext subtitles: hearing impaired")
174 };
175
176 typedef struct
177 {
178     uint8_t                 i_objectTypeIndication;
179     uint8_t                 i_streamType;
180
181     int                     i_extra;
182     uint8_t                 *p_extra;
183
184 } decoder_config_descriptor_t;
185
186 typedef struct
187 {
188     bool                    b_ok;
189     uint16_t                i_es_id;
190
191     char                    *psz_url;
192
193     decoder_config_descriptor_t    dec_descr;
194
195 } es_mpeg4_descriptor_t;
196
197 typedef struct
198 {
199     /* IOD */
200     char                    *psz_url;
201
202     es_mpeg4_descriptor_t   es_descr[255];
203
204 } iod_descriptor_t;
205
206 typedef struct
207 {
208     dvbpsi_handle   handle;
209
210     int             i_version;
211     int             i_number;
212     int             i_pid_pcr;
213     int             i_pid_pmt;
214     mtime_t         i_pcr_value;
215     /* IOD stuff (mpeg4) */
216     iod_descriptor_t *iod;
217
218 } ts_prg_psi_t;
219
220 typedef struct
221 {
222     /* for special PAT/SDT case */
223     dvbpsi_handle   handle; /* PAT/SDT/EIT */
224     int             i_pat_version;
225     int             i_sdt_version;
226
227     /* For PMT */
228     int             i_prg;
229     ts_prg_psi_t    **prg;
230
231 } ts_psi_t;
232
233 typedef enum
234 {
235     TS_ES_DATA_PES,
236     TS_ES_DATA_TABLE_SECTION
237 } ts_es_data_type_t;
238
239 typedef struct
240 {
241     es_format_t  fmt;
242     es_out_id_t *id;
243     ts_es_data_type_t data_type;
244     int         i_data_size;
245     int         i_data_gathered;
246     block_t     *p_data;
247     block_t     **pp_last;
248
249     es_mpeg4_descriptor_t *p_mpeg4desc;
250
251 } ts_es_t;
252
253 typedef struct
254 {
255     int         i_pid;
256
257     bool        b_seen;
258     bool        b_valid;
259     int         i_cc;   /* countinuity counter */
260     bool        b_scrambled;
261
262     /* PSI owner (ie PMT -> PAT, ES -> PMT */
263     ts_psi_t   *p_owner;
264     int         i_owner_number;
265
266     /* */
267     ts_psi_t    *psi;
268     ts_es_t     *es;
269
270     /* Some private streams encapsulate several ES (eg. DVB subtitles)*/
271     ts_es_t     **extra_es;
272     int         i_extra_es;
273
274 } ts_pid_t;
275
276 struct demux_sys_t
277 {
278     vlc_mutex_t     csa_lock;
279
280     /* TS packet size (188, 192, 204) */
281     int         i_packet_size;
282
283     /* how many TS packet we read at once */
284     int         i_ts_read;
285
286     /* to determine length and time */
287     int         i_pid_ref_pcr;
288     mtime_t     i_first_pcr;
289     mtime_t     i_current_pcr;
290     mtime_t     i_last_pcr;
291     bool        b_force_seek_per_percent;
292     int         i_pcrs_num;
293     mtime_t     *p_pcrs;
294     int64_t     *p_pos;
295
296     /* All pid */
297     ts_pid_t    pid[8192];
298
299     /* All PMT */
300     bool        b_user_pmt;
301     int         i_pmt;
302     ts_pid_t    **pmt;
303     int         i_pmt_es;
304
305     /* */
306     bool        b_es_id_pid;
307     csa_t       *csa;
308     int         i_csa_pkt_size;
309     bool        b_split_es;
310
311     bool        b_udp_out;
312     int         fd; /* udp socket */
313     uint8_t     *buffer;
314
315     /* */
316     bool        b_access_control;
317
318     /* */
319     bool        b_dvb_meta;
320     int64_t     i_tdt_delta;
321     int64_t     i_dvb_start;
322     int64_t     i_dvb_length;
323     bool        b_broken_charset; /* True if broken encoding is used in EPG/SDT */
324
325     /* */
326     int         i_current_program;
327     vlc_list_t  programs_list;
328
329     /* */
330     bool        b_start_record;
331 };
332
333 static int Demux    ( demux_t *p_demux );
334 static int Control( demux_t *p_demux, int i_query, va_list args );
335
336 static void PIDInit ( ts_pid_t *pid, bool b_psi, ts_psi_t *p_owner );
337 static void PIDClean( demux_t *, ts_pid_t *pid );
338 static void PIDFillFormat( ts_es_t *es, int i_stream_type );
339
340 static void PATCallBack( void*, dvbpsi_pat_t * );
341 static void PMTCallBack( void *data, dvbpsi_pmt_t *p_pmt );
342 static void PSINewTableCallBack( demux_t *, dvbpsi_handle,
343                                  uint8_t  i_table_id, uint16_t i_extension );
344 static int ChangeKeyCallback( vlc_object_t *, char const *, vlc_value_t, vlc_value_t, void * );
345
346 static inline int PIDGet( block_t *p )
347 {
348     return ( (p->p_buffer[1]&0x1f)<<8 )|p->p_buffer[2];
349 }
350
351 static bool GatherData( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk );
352
353 static block_t* ReadTSPacket( demux_t *p_demux );
354 static mtime_t GetPCR( block_t *p_pkt );
355 static int SeekToPCR( demux_t *p_demux, int64_t i_pos );
356 static int Seek( demux_t *p_demux, double f_percent );
357 static void GetFirstPCR( demux_t *p_demux );
358 static void GetLastPCR( demux_t *p_demux );
359 static void CheckPCR( demux_t *p_demux );
360 static void PCRHandle( demux_t *p_demux, ts_pid_t *, block_t * );
361
362 static void              IODFree( iod_descriptor_t * );
363
364 #define TS_USER_PMT_NUMBER (0)
365 static int UserPmt( demux_t *p_demux, const char * );
366
367 static int  SetPIDFilter( demux_t *, int i_pid, bool b_selected );
368 static void SetPrgFilter( demux_t *, int i_prg, bool b_selected );
369
370 #define TS_PACKET_SIZE_188 188
371 #define TS_PACKET_SIZE_192 192
372 #define TS_PACKET_SIZE_204 204
373 #define TS_PACKET_SIZE_MAX 204
374 #define TS_TOPFIELD_HEADER 1320
375
376 static int DetectPacketSize( demux_t *p_demux )
377 {
378     const uint8_t *p_peek;
379     if( stream_Peek( p_demux->s,
380                      &p_peek, TS_PACKET_SIZE_MAX ) < TS_PACKET_SIZE_MAX )
381         return -1;
382
383     if( memcmp( p_peek, "TFrc", 4 ) == 0 )
384     {
385 #if 0
386         /* I used the TF5000PVR 2004 Firmware .doc header documentation,
387          * http://www.i-topfield.com/data/product/firmware/Structure%20of%20Recorded%20File%20in%20TF5000PVR%20(Feb%2021%202004).doc
388          * but after the filename the offsets seem to be incorrect.  - DJ */
389         int i_duration, i_name;
390         char *psz_name = xmalloc(25);
391         char *psz_event_name;
392         char *psz_event_text = xmalloc(130);
393         char *psz_ext_text = xmalloc(1025);
394
395         // 2 bytes version Uimsbf (4,5)
396         // 2 bytes reserved (6,7)
397         // 2 bytes duration in minutes Uimsbf (8,9(
398         i_duration = (int) (p_peek[8] << 8) | p_peek[9];
399         msg_Dbg( p_demux, "Topfield recording length: +/- %d minutes", i_duration);
400         // 2 bytes service number in channel list (10, 11)
401         // 2 bytes service type Bslbf 0=TV 1=Radio Bslb (12, 13)
402         // 4 bytes of reserved + tuner info (14,15,16,17)
403         // 2 bytes of Service ID  Bslbf (18,19)
404         // 2 bytes of PMT PID  Uimsbf (20,21)
405         // 2 bytes of PCR PID  Uimsbf (22,23)
406         // 2 bytes of Video PID  Uimsbf (24,25)
407         // 2 bytes of Audio PID  Uimsbf (26,27)
408         // 24 bytes filename Bslbf
409         memcpy( psz_name, &p_peek[28], 24 );
410         psz_name[24] = '\0';
411         msg_Dbg( p_demux, "recordingname=%s", psz_name );
412         // 1 byte of sat index Uimsbf  (52)
413         // 3 bytes (1 bit of polarity Bslbf +23 bits reserved)
414         // 4 bytes of freq. Uimsbf (56,57,58,59)
415         // 2 bytes of symbol rate Uimsbf (60,61)
416         // 2 bytes of TS stream ID Uimsbf (62,63)
417         // 4 bytes reserved
418         // 2 bytes reserved
419         // 2 bytes duration Uimsbf (70,71)
420         //i_duration = (int) (p_peek[70] << 8) | p_peek[71];
421         //msg_Dbg( p_demux, "Topfield 2nd duration field: +/- %d minutes", i_duration);
422         // 4 bytes EventID Uimsbf (72-75)
423         // 8 bytes of Start and End time info (76-83)
424         // 1 byte reserved (84)
425         // 1 byte event name length Uimsbf (89)
426         i_name = (int)(p_peek[89]&~0x81);
427         msg_Dbg( p_demux, "event name length = %d", i_name);
428         psz_event_name = xmalloc( i_name+1 );
429         // 1 byte parental rating (90)
430         // 129 bytes of event text
431         memcpy( psz_event_name, &p_peek[91], i_name );
432         psz_event_name[i_name] = '\0';
433         memcpy( psz_event_text, &p_peek[91+i_name], 129-i_name );
434         psz_event_text[129-i_name] = '\0';
435         msg_Dbg( p_demux, "event name=%s", psz_event_name );
436         msg_Dbg( p_demux, "event text=%s", psz_event_text );
437         // 12 bytes reserved (220)
438         // 6 bytes reserved
439         // 2 bytes Event Text Length Uimsbf
440         // 4 bytes EventID Uimsbf
441         // FIXME We just have 613 bytes. not enough for this entire text
442         // 1024 bytes Extended Event Text Bslbf
443         memcpy( psz_ext_text, p_peek+372, 1024 );
444         psz_ext_text[1024] = '\0';
445         msg_Dbg( p_demux, "extended event text=%s", psz_ext_text );
446         // 52 bytes reserved Bslbf
447 #endif
448         msg_Dbg( p_demux, "this is a topfield file" );
449         return TS_PACKET_SIZE_188;
450     }
451
452     for( int i_sync = 0; i_sync < TS_PACKET_SIZE_MAX; i_sync++ )
453     {
454         if( p_peek[i_sync] != 0x47 )
455             continue;
456
457         /* Check next 3 sync bytes */
458         int i_peek = TS_PACKET_SIZE_MAX * 3 + i_sync + 1;
459         if( ( stream_Peek( p_demux->s, &p_peek, i_peek ) ) < i_peek )
460         {
461             msg_Err( p_demux, "cannot peek" );
462             return -1;
463         }
464         if( p_peek[i_sync + 1 * TS_PACKET_SIZE_188] == 0x47 &&
465             p_peek[i_sync + 2 * TS_PACKET_SIZE_188] == 0x47 &&
466             p_peek[i_sync + 3 * TS_PACKET_SIZE_188] == 0x47 )
467         {
468             return TS_PACKET_SIZE_188;
469         }
470         else if( p_peek[i_sync + 1 * TS_PACKET_SIZE_192] == 0x47 &&
471                  p_peek[i_sync + 2 * TS_PACKET_SIZE_192] == 0x47 &&
472                  p_peek[i_sync + 3 * TS_PACKET_SIZE_192] == 0x47 )
473         {
474             return TS_PACKET_SIZE_192;
475         }
476         else if( p_peek[i_sync + 1 * TS_PACKET_SIZE_204] == 0x47 &&
477                  p_peek[i_sync + 2 * TS_PACKET_SIZE_204] == 0x47 &&
478                  p_peek[i_sync + 3 * TS_PACKET_SIZE_204] == 0x47 )
479         {
480             return TS_PACKET_SIZE_204;
481         }
482     }
483
484     if( p_demux->b_force )
485     {
486         msg_Warn( p_demux, "this does not look like a TS stream, continuing" );
487         return TS_PACKET_SIZE_188;
488     }
489     msg_Dbg( p_demux, "TS module discarded (lost sync)" );
490     return -1;
491 }
492
493 /*****************************************************************************
494  * Open
495  *****************************************************************************/
496 static int Open( vlc_object_t *p_this )
497 {
498     demux_t     *p_demux = (demux_t*)p_this;
499     demux_sys_t *p_sys;
500
501     int          i_packet_size;
502
503     ts_pid_t    *pat;
504
505     /* Search first sync byte */
506     i_packet_size = DetectPacketSize( p_demux );
507     if( i_packet_size < 0 )
508         return VLC_EGENERIC;
509
510     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
511     if( !p_sys )
512         return VLC_ENOMEM;
513     memset( p_sys, 0, sizeof( demux_sys_t ) );
514     p_sys->i_packet_size = i_packet_size;
515     vlc_mutex_init( &p_sys->csa_lock );
516
517     p_sys->buffer = NULL;
518     p_demux->pf_demux = Demux;
519     p_demux->pf_control = Control;
520
521     /* Init p_sys field */
522     p_sys->b_dvb_meta = true;
523     p_sys->b_access_control = true;
524     p_sys->i_current_program = 0;
525     p_sys->programs_list.i_count = 0;
526     p_sys->programs_list.p_values = NULL;
527     p_sys->i_tdt_delta = 0;
528     p_sys->i_dvb_start = 0;
529     p_sys->i_dvb_length = 0;
530
531     p_sys->b_broken_charset = false;
532
533     for( int i = 0; i < 8192; i++ )
534     {
535         ts_pid_t *pid = &p_sys->pid[i];
536
537         pid->i_pid      = i;
538         pid->b_seen     = false;
539         pid->b_valid    = false;
540     }
541     /* PID 8191 is padding */
542     p_sys->pid[8191].b_seen = true;
543     p_sys->i_packet_size = i_packet_size;
544     p_sys->b_udp_out = false;
545     p_sys->fd = -1;
546     p_sys->i_ts_read = 50;
547     p_sys->csa = NULL;
548     p_sys->b_start_record = false;
549
550     /* Init PAT handler */
551     pat = &p_sys->pid[0];
552     PIDInit( pat, true, NULL );
553     pat->psi->handle = dvbpsi_AttachPAT( PATCallBack, p_demux );
554     if( p_sys->b_dvb_meta )
555     {
556         ts_pid_t *sdt = &p_sys->pid[0x11];
557         ts_pid_t *eit = &p_sys->pid[0x12];
558
559         PIDInit( sdt, true, NULL );
560         sdt->psi->handle =
561             dvbpsi_AttachDemux( (dvbpsi_demux_new_cb_t)PSINewTableCallBack,
562                                 p_demux );
563         PIDInit( eit, true, NULL );
564         eit->psi->handle =
565             dvbpsi_AttachDemux( (dvbpsi_demux_new_cb_t)PSINewTableCallBack,
566                                 p_demux );
567
568         ts_pid_t *tdt = &p_sys->pid[0x14];
569         PIDInit( tdt, true, NULL );
570         tdt->psi->handle =
571             dvbpsi_AttachDemux( (dvbpsi_demux_new_cb_t)PSINewTableCallBack,
572                                 p_demux );
573         if( p_sys->b_access_control )
574         {
575             if( SetPIDFilter( p_demux, 0x11, true ) ||
576                 SetPIDFilter( p_demux, 0x14, true ) ||
577                 SetPIDFilter( p_demux, 0x12, true ) )
578                 p_sys->b_access_control = false;
579         }
580     }
581
582     /* Init PMT array */
583     TAB_INIT( p_sys->i_pmt, p_sys->pmt );
584     p_sys->i_pmt_es = 0;
585
586     /* Read config */
587     p_sys->b_es_id_pid = var_CreateGetBool( p_demux, "ts-es-id-pid" );
588
589     char* psz_string = var_CreateGetString( p_demux, "ts-out" );
590     if( psz_string && *psz_string )
591     {
592         char *psz = strchr( psz_string, ':' );
593         int   i_port = 0;
594
595         p_sys->b_udp_out = true;
596
597         if( psz )
598         {
599             *psz++ = '\0';
600             i_port = atoi( psz );
601         }
602         if( i_port <= 0 ) i_port  = 1234;
603         msg_Dbg( p_demux, "resend ts to '%s:%d'", psz_string, i_port );
604
605         p_sys->fd = net_ConnectUDP( VLC_OBJECT(p_demux), psz_string, i_port, -1 );
606         if( p_sys->fd < 0 )
607         {
608             msg_Err( p_demux, "failed to open udp socket, send disabled" );
609             p_sys->b_udp_out = false;
610         }
611         else
612         {
613             int i_mtu = var_CreateGetInteger( p_demux, "ts-out-mtu" );
614             p_sys->i_ts_read = i_mtu / p_sys->i_packet_size;
615             if( p_sys->i_ts_read <= 0 )
616             {
617                 p_sys->i_ts_read = 1500 / p_sys->i_packet_size;
618             }
619             p_sys->buffer = xmalloc( p_sys->i_packet_size * p_sys->i_ts_read );
620         }
621     }
622     free( psz_string );
623
624     /* We handle description of an extra PMT */
625     psz_string = var_CreateGetString( p_demux, "ts-extra-pmt" );
626     p_sys->b_user_pmt = false;
627     if( psz_string && *psz_string )
628         UserPmt( p_demux, psz_string );
629     free( psz_string );
630
631     psz_string = var_CreateGetStringCommand( p_demux, "ts-csa-ck" );
632     if( psz_string && *psz_string )
633     {
634         int i_res;
635         char* psz_csa2;
636
637         p_sys->csa = csa_New();
638
639         psz_csa2 = var_CreateGetStringCommand( p_demux, "ts-csa2-ck" );
640         i_res = csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_string, true );
641         if( i_res == VLC_SUCCESS && psz_csa2 && *psz_csa2 )
642         {
643             if( csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_csa2, false ) != VLC_SUCCESS )
644             {
645                 csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_string, false );
646             }
647         }
648         else if ( i_res == VLC_SUCCESS )
649         {
650             csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_string, false );
651         }
652         else
653         {
654             csa_Delete( p_sys->csa );
655             p_sys->csa = NULL;
656         }
657
658         if( p_sys->csa )
659         {
660             var_AddCallback( p_demux, "ts-csa-ck", ChangeKeyCallback, (void *)1 );
661             var_AddCallback( p_demux, "ts-csa2-ck", ChangeKeyCallback, NULL );
662
663             int i_pkt = var_CreateGetInteger( p_demux, "ts-csa-pkt" );
664             if( i_pkt < 4 || i_pkt > 188 )
665             {
666                 msg_Err( p_demux, "wrong packet size %d specified.", i_pkt );
667                 msg_Warn( p_demux, "using default packet size of 188 bytes" );
668                 p_sys->i_csa_pkt_size = 188;
669             }
670             else
671                 p_sys->i_csa_pkt_size = i_pkt;
672             msg_Dbg( p_demux, "decrypting %d bytes of packet", p_sys->i_csa_pkt_size );
673         }
674         free( psz_csa2 );
675     }
676     free( psz_string );
677
678     p_sys->b_split_es = var_InheritBool( p_demux, "ts-split-es" );
679
680     p_sys->i_pid_ref_pcr = -1;
681     p_sys->i_first_pcr = -1;
682     p_sys->i_current_pcr = -1;
683     p_sys->i_last_pcr = -1;
684     p_sys->b_force_seek_per_percent = var_InheritBool( p_demux, "ts-seek-percent" );
685     p_sys->i_pcrs_num = 10;
686     p_sys->p_pcrs = (mtime_t *)calloc( p_sys->i_pcrs_num, sizeof( mtime_t ) );
687     p_sys->p_pos = (int64_t *)calloc( p_sys->i_pcrs_num, sizeof( int64_t ) );
688
689     bool can_seek = false;
690     stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &can_seek );
691     if( can_seek  )
692     {
693         GetFirstPCR( p_demux );
694         CheckPCR( p_demux );
695         GetLastPCR( p_demux );
696     }
697     if( p_sys->i_first_pcr < 0 || p_sys->i_last_pcr < 0 )
698     {
699         p_sys->b_force_seek_per_percent = true;
700     }
701
702     while( p_sys->i_pmt_es <= 0 && vlc_object_alive( p_demux ) )
703     {
704         if( p_demux->pf_demux( p_demux ) != 1 )
705             break;
706     }
707
708     return VLC_SUCCESS;
709 }
710
711 /*****************************************************************************
712  * Close
713  *****************************************************************************/
714 static void Close( vlc_object_t *p_this )
715 {
716     demux_t     *p_demux = (demux_t*)p_this;
717     demux_sys_t *p_sys = p_demux->p_sys;
718
719     msg_Dbg( p_demux, "pid list:" );
720     for( int i = 0; i < 8192; i++ )
721     {
722         ts_pid_t *pid = &p_sys->pid[i];
723
724         if( pid->b_valid && pid->psi )
725         {
726             switch( pid->i_pid )
727             {
728             case 0: /* PAT */
729                 dvbpsi_DetachPAT( pid->psi->handle );
730                 free( pid->psi );
731                 break;
732             case 1: /* CAT */
733                 free( pid->psi );
734                 break;
735             default:
736                 if( p_sys->b_dvb_meta && ( pid->i_pid == 0x11 || pid->i_pid == 0x12 || pid->i_pid == 0x14 ) )
737                 {
738                     /* SDT or EIT or TDT */
739                     dvbpsi_DetachDemux( pid->psi->handle );
740                     free( pid->psi );
741                 }
742                 else
743                 {
744                     PIDClean( p_demux, pid );
745                 }
746                 break;
747             }
748         }
749         else if( pid->b_valid && pid->es )
750         {
751             PIDClean( p_demux, pid );
752         }
753
754         if( pid->b_seen )
755         {
756             msg_Dbg( p_demux, "  - pid[%d] seen", pid->i_pid );
757         }
758
759         /* too much */
760         if( pid->i_pid > 0 )
761             SetPIDFilter( p_demux, pid->i_pid, false );
762     }
763
764     vlc_mutex_lock( &p_sys->csa_lock );
765     if( p_sys->csa )
766     {
767         var_DelCallback( p_demux, "ts-csa-ck", ChangeKeyCallback, NULL );
768         var_DelCallback( p_demux, "ts-csa2-ck", ChangeKeyCallback, NULL );
769         csa_Delete( p_sys->csa );
770     }
771     vlc_mutex_unlock( &p_sys->csa_lock );
772
773     TAB_CLEAN( p_sys->i_pmt, p_sys->pmt );
774
775     free( p_sys->programs_list.p_values );
776
777     /* When streaming, close the port */
778     if( p_sys->fd > -1 )
779     {
780         net_Close( p_sys->fd );
781     }
782
783     free( p_sys->buffer );
784
785     free( p_sys->p_pcrs );
786     free( p_sys->p_pos );
787
788     vlc_mutex_destroy( &p_sys->csa_lock );
789     free( p_sys );
790 }
791
792 /*****************************************************************************
793  * ChangeKeyCallback: called when changing the odd encryption key on the fly.
794  *****************************************************************************/
795 static int ChangeKeyCallback( vlc_object_t *p_this, char const *psz_cmd,
796                            vlc_value_t oldval, vlc_value_t newval,
797                            void *p_data )
798 {
799     VLC_UNUSED(psz_cmd); VLC_UNUSED(oldval);
800     demux_t     *p_demux = (demux_t*)p_this;
801     demux_sys_t *p_sys = p_demux->p_sys;
802     int         i_tmp = (intptr_t)p_data;
803
804     vlc_mutex_lock( &p_sys->csa_lock );
805     if ( i_tmp )
806         i_tmp = csa_SetCW( p_this, p_sys->csa, newval.psz_string, true );
807     else
808         i_tmp = csa_SetCW( p_this, p_sys->csa, newval.psz_string, false );
809
810     vlc_mutex_unlock( &p_sys->csa_lock );
811     return i_tmp;
812 }
813
814 /*****************************************************************************
815  * Demux:
816  *****************************************************************************/
817 static int Demux( demux_t *p_demux )
818 {
819     demux_sys_t *p_sys = p_demux->p_sys;
820     bool b_wait_es = p_sys->i_pmt_es <= 0;
821
822     /* We read at most 100 TS packet or until a frame is completed */
823     for( int i_pkt = 0; i_pkt < p_sys->i_ts_read; i_pkt++ )
824     {
825         bool         b_frame = false;
826         block_t     *p_pkt;
827         if( !(p_pkt = ReadTSPacket( p_demux )) )
828         {
829             return 0;
830         }
831
832         if( p_sys->b_start_record )
833         {
834             /* Enable recording once synchronized */
835             stream_Control( p_demux->s, STREAM_SET_RECORD_STATE, true, "ts" );
836             p_sys->b_start_record = false;
837         }
838
839         if( p_sys->b_udp_out )
840         {
841             memcpy( &p_sys->buffer[i_pkt * p_sys->i_packet_size],
842                     p_pkt->p_buffer, p_sys->i_packet_size );
843         }
844
845         /* Parse the TS packet */
846         ts_pid_t *p_pid = &p_sys->pid[PIDGet( p_pkt )];
847
848         if( p_pid->b_valid )
849         {
850             if( p_pid->psi )
851             {
852                 if( p_pid->i_pid == 0 || ( p_sys->b_dvb_meta && ( p_pid->i_pid == 0x11 || p_pid->i_pid == 0x12 || p_pid->i_pid == 0x14 ) ) )
853                 {
854                     dvbpsi_PushPacket( p_pid->psi->handle, p_pkt->p_buffer );
855                 }
856                 else
857                 {
858                     for( int i_prg = 0; i_prg < p_pid->psi->i_prg; i_prg++ )
859                     {
860                         dvbpsi_PushPacket( p_pid->psi->prg[i_prg]->handle,
861                                            p_pkt->p_buffer );
862                     }
863                 }
864                 block_Release( p_pkt );
865             }
866             else if( !p_sys->b_udp_out )
867             {
868                 b_frame = GatherData( p_demux, p_pid, p_pkt );
869             }
870             else
871             {
872                 PCRHandle( p_demux, p_pid, p_pkt );
873                 block_Release( p_pkt );
874             }
875         }
876         else
877         {
878             if( !p_pid->b_seen )
879             {
880                 msg_Dbg( p_demux, "pid[%d] unknown", p_pid->i_pid );
881             }
882             /* We have to handle PCR if present */
883             PCRHandle( p_demux, p_pid, p_pkt );
884             block_Release( p_pkt );
885         }
886         p_pid->b_seen = true;
887
888         if( b_frame || ( b_wait_es && p_sys->i_pmt_es > 0 ) )
889             break;
890     }
891
892     if( p_sys->b_udp_out )
893     {
894         /* Send the complete block */
895         net_Write( p_demux, p_sys->fd, NULL, p_sys->buffer,
896                    p_sys->i_ts_read * p_sys->i_packet_size );
897     }
898
899     return 1;
900 }
901
902 /*****************************************************************************
903  * Control:
904  *****************************************************************************/
905 static int DVBEventInformation( demux_t *p_demux, int64_t *pi_time, int64_t *pi_length )
906 {
907     demux_sys_t *p_sys = p_demux->p_sys;
908     if( pi_length )
909         *pi_length = 0;
910     if( pi_time )
911         *pi_time = 0;
912
913     if( p_sys->i_dvb_length > 0 )
914     {
915         const int64_t t = mdate() + p_sys->i_tdt_delta;
916
917         if( p_sys->i_dvb_start <= t && t < p_sys->i_dvb_start + p_sys->i_dvb_length )
918         {
919             if( pi_length )
920                 *pi_length = p_sys->i_dvb_length;
921             if( pi_time )
922                 *pi_time   = t - p_sys->i_dvb_start;
923             return VLC_SUCCESS;
924         }
925     }
926     return VLC_EGENERIC;
927 }
928
929 static int Control( demux_t *p_demux, int i_query, va_list args )
930 {
931     demux_sys_t *p_sys = p_demux->p_sys;
932     double f, *pf;
933     bool b_bool, *pb_bool;
934     int64_t i64;
935     int64_t *pi64;
936     int i_int;
937
938     switch( i_query )
939     {
940     case DEMUX_GET_POSITION:
941         pf = (double*) va_arg( args, double* );
942
943         if( p_sys->b_force_seek_per_percent ||
944             (p_sys->b_dvb_meta && p_sys->b_access_control) ||
945             p_sys->i_current_pcr - p_sys->i_first_pcr < 0 ||
946             p_sys->i_last_pcr - p_sys->i_first_pcr <= 0 )
947         {
948             int64_t i_time, i_length;
949             if( !DVBEventInformation( p_demux, &i_time, &i_length ) && i_length > 0 )
950                 *pf = (double)i_time/(double)i_length;
951             else if( (i64 = stream_Size( p_demux->s) ) > 0 )
952                 *pf = (double)stream_Tell( p_demux->s ) / (double)i64;
953             else
954                 *pf = 0.0;
955         }
956         else
957         {
958             *pf = (double)(p_sys->i_current_pcr - p_sys->i_first_pcr) / (double)(p_sys->i_last_pcr - p_sys->i_first_pcr);
959         }
960         return VLC_SUCCESS;
961
962     case DEMUX_SET_POSITION:
963         f = (double) va_arg( args, double );
964
965         if( p_sys->b_force_seek_per_percent ||
966             (p_sys->b_dvb_meta && p_sys->b_access_control) ||
967             p_sys->i_last_pcr - p_sys->i_first_pcr <= 0 )
968         {
969             i64 = stream_Size( p_demux->s );
970             if( stream_Seek( p_demux->s, (int64_t)(i64 * f) ) )
971                 return VLC_EGENERIC;
972         }
973         else
974         {
975             if( Seek( p_demux, f ) )
976             {
977                 p_sys->b_force_seek_per_percent = true;
978                 return VLC_EGENERIC;
979             }
980         }
981         return VLC_SUCCESS;
982
983     case DEMUX_GET_TIME:
984         pi64 = (int64_t*)va_arg( args, int64_t * );
985         if( (p_sys->b_dvb_meta && p_sys->b_access_control) ||
986             p_sys->b_force_seek_per_percent ||
987             p_sys->i_current_pcr - p_sys->i_first_pcr < 0 )
988         {
989             if( DVBEventInformation( p_demux, pi64, NULL ) )
990             {
991                 *pi64 = 0;
992             }
993         }
994         else
995         {
996             *pi64 = (p_sys->i_current_pcr - p_sys->i_first_pcr) * 100 / 9;
997         }
998         return VLC_SUCCESS;
999
1000     case DEMUX_GET_LENGTH:
1001         pi64 = (int64_t*)va_arg( args, int64_t * );
1002         if( (p_sys->b_dvb_meta && p_sys->b_access_control) ||
1003             p_sys->b_force_seek_per_percent ||
1004             p_sys->i_last_pcr - p_sys->i_first_pcr <= 0 )
1005         {
1006             if( DVBEventInformation( p_demux, NULL, pi64 ) )
1007             {
1008                 *pi64 = 0;
1009             }
1010         }
1011         else
1012         {
1013             *pi64 = (p_sys->i_last_pcr - p_sys->i_first_pcr) * 100 / 9;
1014         }
1015         return VLC_SUCCESS;
1016
1017     case DEMUX_SET_GROUP:
1018     {
1019         vlc_list_t *p_list;
1020
1021         i_int = (int)va_arg( args, int );
1022         p_list = (vlc_list_t *)va_arg( args, vlc_list_t * );
1023         msg_Dbg( p_demux, "DEMUX_SET_GROUP %d %p", i_int, p_list );
1024
1025         if( i_int == 0 && p_sys->i_current_program > 0 )
1026             i_int = p_sys->i_current_program;
1027
1028         if( p_sys->i_current_program > 0 )
1029         {
1030             if( p_sys->i_current_program != i_int )
1031                 SetPrgFilter( p_demux, p_sys->i_current_program, false );
1032         }
1033         else if( p_sys->i_current_program < 0 )
1034         {
1035             for( int i = 0; i < p_sys->programs_list.i_count; i++ )
1036                 SetPrgFilter( p_demux, p_sys->programs_list.p_values[i].i_int, false );
1037         }
1038
1039         if( i_int > 0 )
1040         {
1041             p_sys->i_current_program = i_int;
1042             SetPrgFilter( p_demux, p_sys->i_current_program, true );
1043         }
1044         else if( i_int < 0 )
1045         {
1046             p_sys->i_current_program = -1;
1047             p_sys->programs_list.i_count = 0;
1048             if( p_list )
1049             {
1050                 vlc_list_t *p_dst = &p_sys->programs_list;
1051                 free( p_dst->p_values );
1052
1053                 p_dst->p_values = calloc( p_list->i_count,
1054                                           sizeof(*p_dst->p_values) );
1055                 if( p_dst->p_values )
1056                 {
1057                     p_dst->i_count = p_list->i_count;
1058                     for( int i = 0; i < p_list->i_count; i++ )
1059                     {
1060                         p_dst->p_values[i] = p_list->p_values[i];
1061                         SetPrgFilter( p_demux, p_dst->p_values[i].i_int, true );
1062                     }
1063                 }
1064             }
1065         }
1066         return VLC_SUCCESS;
1067     }
1068
1069     case DEMUX_CAN_RECORD:
1070         pb_bool = (bool*)va_arg( args, bool * );
1071         *pb_bool = true;
1072         return VLC_SUCCESS;
1073
1074     case DEMUX_SET_RECORD_STATE:
1075         b_bool = (bool)va_arg( args, int );
1076
1077         if( !b_bool )
1078             stream_Control( p_demux->s, STREAM_SET_RECORD_STATE, false );
1079         p_sys->b_start_record = b_bool;
1080         return VLC_SUCCESS;
1081
1082     case DEMUX_GET_FPS:
1083     case DEMUX_SET_TIME:
1084     default:
1085         return VLC_EGENERIC;
1086     }
1087 }
1088
1089 /*****************************************************************************
1090  *
1091  *****************************************************************************/
1092 static int UserPmt( demux_t *p_demux, const char *psz_fmt )
1093 {
1094     demux_sys_t *p_sys = p_demux->p_sys;
1095     char *psz_dup = strdup( psz_fmt );
1096     char *psz = psz_dup;
1097     int  i_pid;
1098     int  i_number;
1099
1100     if( !psz_dup )
1101         return VLC_ENOMEM;
1102
1103     /* Parse PID */
1104     i_pid = strtol( psz, &psz, 0 );
1105     if( i_pid < 2 || i_pid >= 8192 )
1106         goto error;
1107
1108     /* Parse optional program number */
1109     i_number = 0;
1110     if( *psz == ':' )
1111         i_number = strtol( &psz[1], &psz, 0 );
1112
1113     /* */
1114     ts_pid_t *pmt = &p_sys->pid[i_pid];
1115     ts_prg_psi_t *prg;
1116
1117     msg_Dbg( p_demux, "user pmt specified (pid=%d,number=%d)", i_pid, i_number );
1118     PIDInit( pmt, true, NULL );
1119
1120     /* Dummy PMT */
1121     prg = malloc( sizeof( ts_prg_psi_t ) );
1122     if( !prg )
1123         goto error;
1124
1125     memset( prg, 0, sizeof( ts_prg_psi_t ) );
1126     prg->i_pid_pcr  = -1;
1127     prg->i_pid_pmt  = -1;
1128     prg->i_version  = -1;
1129     prg->i_number   = i_number != 0 ? i_number : TS_USER_PMT_NUMBER;
1130     prg->handle     = dvbpsi_AttachPMT(
1131         i_number != TS_USER_PMT_NUMBER ? i_number : 1,
1132         PMTCallBack, p_demux );
1133     TAB_APPEND( pmt->psi->i_prg, pmt->psi->prg, prg );
1134
1135     psz = strchr( psz, '=' );
1136     if( psz )
1137         psz++;
1138     while( psz && *psz )
1139     {
1140         char *psz_next = strchr( psz, ',' );
1141         int i_pid;
1142
1143         if( psz_next )
1144             *psz_next++ = '\0';
1145
1146         i_pid = strtol( psz, &psz, 0 );
1147         if( *psz != ':' || i_pid < 2 || i_pid >= 8192 )
1148             goto next;
1149
1150         char *psz_opt = &psz[1];
1151         if( !strcmp( psz_opt, "pcr" ) )
1152         {
1153             prg->i_pid_pcr = i_pid;
1154         }
1155         else if( !p_sys->pid[i_pid].b_valid )
1156         {
1157             ts_pid_t *pid = &p_sys->pid[i_pid];
1158
1159             char *psz_arg = strchr( psz_opt, '=' );
1160             if( psz_arg )
1161                 *psz_arg++ = '\0';
1162
1163             PIDInit( pid, false, pmt->psi);
1164             if( prg->i_pid_pcr <= 0 )
1165                 prg->i_pid_pcr = i_pid;
1166
1167             if( psz_arg && strlen( psz_arg ) == 4 )
1168             {
1169                 const vlc_fourcc_t i_codec = VLC_FOURCC( psz_arg[0], psz_arg[1],
1170                                                          psz_arg[2], psz_arg[3] );
1171                 int i_cat = UNKNOWN_ES;
1172                 es_format_t *fmt = &pid->es->fmt;
1173
1174                 if( !strcmp( psz_opt, "video" ) )
1175                     i_cat = VIDEO_ES;
1176                 else if( !strcmp( psz_opt, "audio" ) )
1177                     i_cat = AUDIO_ES;
1178                 else if( !strcmp( psz_opt, "spu" ) )
1179                     i_cat = SPU_ES;
1180
1181                 es_format_Init( fmt, i_cat, i_codec );
1182                 fmt->b_packetized = false;
1183             }
1184             else
1185             {
1186                 const int i_stream_type = strtol( psz_opt, NULL, 0 );
1187                 PIDFillFormat( pid->es, i_stream_type );
1188             }
1189             pid->es->fmt.i_group = i_number;
1190             if( p_sys->b_es_id_pid )
1191                 pid->es->fmt.i_id = i_pid;
1192
1193             if( pid->es->fmt.i_cat != UNKNOWN_ES )
1194             {
1195                 msg_Dbg( p_demux, "  * es pid=%d fcc=%4.4s", i_pid,
1196                          (char*)&pid->es->fmt.i_codec );
1197                 pid->es->id = es_out_Add( p_demux->out,
1198                                           &pid->es->fmt );
1199                 p_sys->i_pmt_es++;
1200             }
1201         }
1202
1203     next:
1204         psz = psz_next;
1205     }
1206
1207     p_sys->b_user_pmt = true;
1208     TAB_APPEND( p_sys->i_pmt, p_sys->pmt, pmt );
1209     free( psz_dup );
1210     return VLC_SUCCESS;
1211
1212 error:
1213     free( psz_dup );
1214     return VLC_EGENERIC;
1215 }
1216
1217 static int SetPIDFilter( demux_t *p_demux, int i_pid, bool b_selected )
1218 {
1219     demux_sys_t *p_sys = p_demux->p_sys;
1220
1221     if( !p_sys->b_access_control )
1222         return VLC_EGENERIC;
1223
1224     return stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
1225                            ACCESS_SET_PRIVATE_ID_STATE, i_pid, b_selected );
1226 }
1227
1228 static void SetPrgFilter( demux_t *p_demux, int i_prg_id, bool b_selected )
1229 {
1230     demux_sys_t *p_sys = p_demux->p_sys;
1231     ts_prg_psi_t *p_prg = NULL;
1232     int i_pmt_pid = -1;
1233
1234     /* Search pmt to be unselected */
1235     for( int i = 0; i < p_sys->i_pmt; i++ )
1236     {
1237         ts_pid_t *pmt = p_sys->pmt[i];
1238
1239         for( int i_prg = 0; i_prg < pmt->psi->i_prg; i_prg++ )
1240         {
1241             if( pmt->psi->prg[i_prg]->i_number == i_prg_id )
1242             {
1243                 i_pmt_pid = p_sys->pmt[i]->i_pid;
1244                 p_prg = p_sys->pmt[i]->psi->prg[i_prg];
1245                 break;
1246             }
1247         }
1248         if( i_pmt_pid > 0 )
1249             break;
1250     }
1251     if( i_pmt_pid <= 0 )
1252         return;
1253     assert( p_prg );
1254
1255     SetPIDFilter( p_demux, i_pmt_pid, b_selected );
1256     if( p_prg->i_pid_pcr > 0 )
1257         SetPIDFilter( p_demux, p_prg->i_pid_pcr, b_selected );
1258
1259     /* All ES */
1260     for( int i = 2; i < 8192; i++ )
1261     {
1262         ts_pid_t *pid = &p_sys->pid[i];
1263
1264         if( !pid->b_valid || pid->psi )
1265             continue;
1266
1267         for( int i_prg = 0; i_prg < pid->p_owner->i_prg; i_prg++ )
1268         {
1269             if( pid->p_owner->prg[i_prg]->i_pid_pmt == i_pmt_pid && pid->es->id )
1270             {
1271                 /* We only remove/select es that aren't defined by extra pmt */
1272                 SetPIDFilter( p_demux, i, b_selected );
1273                 break;
1274             }
1275         }
1276     }
1277 }
1278
1279 static void PIDInit( ts_pid_t *pid, bool b_psi, ts_psi_t *p_owner )
1280 {
1281     bool b_old_valid = pid->b_valid;
1282
1283     pid->b_valid    = true;
1284     pid->i_cc       = 0xff;
1285     pid->b_scrambled = false;
1286     pid->p_owner    = p_owner;
1287     pid->i_owner_number = 0;
1288
1289     TAB_INIT( pid->i_extra_es, pid->extra_es );
1290
1291     if( b_psi )
1292     {
1293         pid->es  = NULL;
1294
1295         if( !b_old_valid )
1296         {
1297             pid->psi = xmalloc( sizeof( ts_psi_t ) );
1298             pid->psi->handle = NULL;
1299             TAB_INIT( pid->psi->i_prg, pid->psi->prg );
1300         }
1301         assert( pid->psi );
1302
1303         pid->psi->i_pat_version  = -1;
1304         pid->psi->i_sdt_version  = -1;
1305         if( p_owner )
1306         {
1307             ts_prg_psi_t *prg = malloc( sizeof( ts_prg_psi_t ) );
1308             if( !prg )
1309                 return;
1310             /* PMT */
1311             prg->i_version  = -1;
1312             prg->i_number   = -1;
1313             prg->i_pid_pcr  = -1;
1314             prg->i_pid_pmt  = -1;
1315             prg->i_pcr_value= -1;
1316             prg->iod        = NULL;
1317             prg->handle     = NULL;
1318
1319             TAB_APPEND( pid->psi->i_prg, pid->psi->prg, prg );
1320         }
1321     }
1322     else
1323     {
1324         pid->psi = NULL;
1325         pid->es  = calloc( 1, sizeof( ts_es_t ) );
1326         if( !pid->es )
1327             return;
1328
1329         es_format_Init( &pid->es->fmt, UNKNOWN_ES, 0 );
1330         pid->es->data_type = TS_ES_DATA_PES;
1331         pid->es->pp_last = &pid->es->p_data;
1332     }
1333 }
1334
1335 static void PIDClean( demux_t *p_demux, ts_pid_t *pid )
1336 {
1337     demux_sys_t *p_sys = p_demux->p_sys;
1338     es_out_t *out = p_demux->out;
1339
1340     if( pid->psi )
1341     {
1342         if( pid->psi->handle )
1343             dvbpsi_DetachPMT( pid->psi->handle );
1344         for( int i = 0; i < pid->psi->i_prg; i++ )
1345         {
1346             if( pid->psi->prg[i]->iod )
1347                 IODFree( pid->psi->prg[i]->iod );
1348             if( pid->psi->prg[i]->handle )
1349                 dvbpsi_DetachPMT( pid->psi->prg[i]->handle );
1350             free( pid->psi->prg[i] );
1351         }
1352         free( pid->psi->prg );
1353         free( pid->psi );
1354     }
1355     else
1356     {
1357         if( pid->es->id )
1358         {
1359             es_out_Del( out, pid->es->id );
1360             p_sys->i_pmt_es--;
1361         }
1362
1363         if( pid->es->p_data )
1364             block_ChainRelease( pid->es->p_data );
1365
1366         es_format_Clean( &pid->es->fmt );
1367
1368         free( pid->es );
1369
1370         for( int i = 0; i < pid->i_extra_es; i++ )
1371         {
1372             if( pid->extra_es[i]->id )
1373             {
1374                 es_out_Del( out, pid->extra_es[i]->id );
1375                 p_sys->i_pmt_es--;
1376             }
1377
1378             if( pid->extra_es[i]->p_data )
1379                 block_ChainRelease( pid->extra_es[i]->p_data );
1380
1381             es_format_Clean( &pid->extra_es[i]->fmt );
1382
1383             free( pid->extra_es[i] );
1384         }
1385         if( pid->i_extra_es )
1386             free( pid->extra_es );
1387     }
1388
1389     pid->b_valid = false;
1390 }
1391
1392 /****************************************************************************
1393  * gathering stuff
1394  ****************************************************************************/
1395 static void ParsePES( demux_t *p_demux, ts_pid_t *pid, block_t *p_pes )
1396 {
1397     uint8_t header[34];
1398     unsigned i_pes_size = 0;
1399     unsigned i_skip = 0;
1400     mtime_t i_dts = -1;
1401     mtime_t i_pts = -1;
1402     mtime_t i_length = 0;
1403
1404     /* FIXME find real max size */
1405     /* const int i_max = */ block_ChainExtract( p_pes, header, 34 );
1406
1407     if( header[0] != 0 || header[1] != 0 || header[2] != 1 )
1408     {
1409         msg_Warn( p_demux, "invalid header [0x%02x:%02x:%02x:%02x] (pid: %d)",
1410                     header[0], header[1],header[2],header[3], pid->i_pid );
1411         block_ChainRelease( p_pes );
1412         return;
1413     }
1414
1415     /* TODO check size */
1416     switch( header[3] )
1417     {
1418     case 0xBC:  /* Program stream map */
1419     case 0xBE:  /* Padding */
1420     case 0xBF:  /* Private stream 2 */
1421     case 0xF0:  /* ECM */
1422     case 0xF1:  /* EMM */
1423     case 0xFF:  /* Program stream directory */
1424     case 0xF2:  /* DSMCC stream */
1425     case 0xF8:  /* ITU-T H.222.1 type E stream */
1426         i_skip = 6;
1427         break;
1428     default:
1429         if( ( header[6]&0xC0 ) == 0x80 )
1430         {
1431             /* mpeg2 PES */
1432             i_skip = header[8] + 9;
1433
1434             if( header[7]&0x80 )    /* has pts */
1435             {
1436                 i_pts = ((mtime_t)(header[ 9]&0x0e ) << 29)|
1437                          (mtime_t)(header[10] << 22)|
1438                         ((mtime_t)(header[11]&0xfe) << 14)|
1439                          (mtime_t)(header[12] << 7)|
1440                          (mtime_t)(header[13] >> 1);
1441
1442                 if( header[7]&0x40 )    /* has dts */
1443                 {
1444                      i_dts = ((mtime_t)(header[14]&0x0e ) << 29)|
1445                              (mtime_t)(header[15] << 22)|
1446                             ((mtime_t)(header[16]&0xfe) << 14)|
1447                              (mtime_t)(header[17] << 7)|
1448                              (mtime_t)(header[18] >> 1);
1449                 }
1450             }
1451         }
1452         else
1453         {
1454             i_skip = 6;
1455             while( i_skip < 23 && header[i_skip] == 0xff )
1456             {
1457                 i_skip++;
1458             }
1459             if( i_skip == 23 )
1460             {
1461                 msg_Err( p_demux, "too much MPEG-1 stuffing" );
1462                 block_ChainRelease( p_pes );
1463                 return;
1464             }
1465             if( ( header[i_skip] & 0xC0 ) == 0x40 )
1466             {
1467                 i_skip += 2;
1468             }
1469
1470             if(  header[i_skip]&0x20 )
1471             {
1472                  i_pts = ((mtime_t)(header[i_skip]&0x0e ) << 29)|
1473                           (mtime_t)(header[i_skip+1] << 22)|
1474                          ((mtime_t)(header[i_skip+2]&0xfe) << 14)|
1475                           (mtime_t)(header[i_skip+3] << 7)|
1476                           (mtime_t)(header[i_skip+4] >> 1);
1477
1478                 if( header[i_skip]&0x10 )    /* has dts */
1479                 {
1480                      i_dts = ((mtime_t)(header[i_skip+5]&0x0e ) << 29)|
1481                               (mtime_t)(header[i_skip+6] << 22)|
1482                              ((mtime_t)(header[i_skip+7]&0xfe) << 14)|
1483                               (mtime_t)(header[i_skip+8] << 7)|
1484                               (mtime_t)(header[i_skip+9] >> 1);
1485                      i_skip += 10;
1486                 }
1487                 else
1488                 {
1489                     i_skip += 5;
1490                 }
1491             }
1492             else
1493             {
1494                 i_skip += 1;
1495             }
1496         }
1497         break;
1498     }
1499
1500     if( pid->es->fmt.i_codec == VLC_FOURCC( 'a', '5', '2', 'b' ) ||
1501         pid->es->fmt.i_codec == VLC_FOURCC( 'd', 't', 's', 'b' ) )
1502     {
1503         i_skip += 4;
1504     }
1505     else if( pid->es->fmt.i_codec == VLC_FOURCC( 'l', 'p', 'c', 'b' ) ||
1506              pid->es->fmt.i_codec == VLC_FOURCC( 's', 'p', 'u', 'b' ) ||
1507              pid->es->fmt.i_codec == VLC_FOURCC( 's', 'd', 'd', 'b' ) )
1508     {
1509         i_skip += 1;
1510     }
1511     else if( pid->es->fmt.i_codec == VLC_CODEC_SUBT &&
1512              pid->es->p_mpeg4desc )
1513     {
1514         decoder_config_descriptor_t *dcd = &pid->es->p_mpeg4desc->dec_descr;
1515
1516         if( dcd->i_extra > 2 &&
1517             dcd->p_extra[0] == 0x10 &&
1518             ( dcd->p_extra[1]&0x10 ) )
1519         {
1520             /* display length */
1521             if( p_pes->i_buffer + 2 <= i_skip )
1522                 i_length = GetWBE( &p_pes->p_buffer[i_skip] );
1523
1524             i_skip += 2;
1525         }
1526         if( p_pes->i_buffer + 2 <= i_skip )
1527             i_pes_size = GetWBE( &p_pes->p_buffer[i_skip] );
1528         /* */
1529         i_skip += 2;
1530     }
1531
1532     /* skip header */
1533     while( p_pes && i_skip > 0 )
1534     {
1535         if( p_pes->i_buffer <= i_skip )
1536         {
1537             block_t *p_next = p_pes->p_next;
1538
1539             i_skip -= p_pes->i_buffer;
1540             block_Release( p_pes );
1541             p_pes = p_next;
1542         }
1543         else
1544         {
1545             p_pes->i_buffer -= i_skip;
1546             p_pes->p_buffer += i_skip;
1547             break;
1548         }
1549     }
1550
1551     /* ISO/IEC 13818-1 2.7.5: if no pts and no dts, then dts == pts */
1552     if( i_pts >= 0 && i_dts < 0 )
1553         i_dts = i_pts;
1554
1555     if( p_pes )
1556     {
1557         block_t *p_block;
1558
1559         if( i_dts >= 0 )
1560             p_pes->i_dts = VLC_TS_0 + i_dts * 100 / 9;
1561
1562         if( i_pts >= 0 )
1563             p_pes->i_pts = VLC_TS_0 + i_pts * 100 / 9;
1564
1565         p_pes->i_length = i_length * 100 / 9;
1566
1567         p_block = block_ChainGather( p_pes );
1568         if( pid->es->fmt.i_codec == VLC_CODEC_SUBT )
1569         {
1570             if( i_pes_size > 0 && p_block->i_buffer > i_pes_size )
1571             {
1572                 p_block->i_buffer = i_pes_size;
1573             }
1574             /* Append a \0 */
1575             p_block = block_Realloc( p_block, 0, p_block->i_buffer + 1 );
1576             if( !p_block )
1577                 abort();
1578             p_block->p_buffer[p_block->i_buffer -1] = '\0';
1579         }
1580         else if( pid->es->fmt.i_codec == VLC_CODEC_TELETEXT )
1581         {
1582             if( p_block->i_pts <= VLC_TS_INVALID )
1583             {
1584                 /* Teletext may have missing PTS (ETSI EN 300 472 Annexe A)
1585                  * In this case use the last PCR + 40ms */
1586                 for( int i = 0; pid->p_owner && i < pid->p_owner->i_prg; i++ )
1587                 {
1588                     if( pid->i_owner_number == pid->p_owner->prg[i]->i_number )
1589                     {
1590                         mtime_t i_pcr = pid->p_owner->prg[i]->i_pcr_value;
1591                         if( i_pcr > VLC_TS_INVALID )
1592                             p_block->i_pts = VLC_TS_0 + i_pcr * 100 / 9 + 40000;
1593                         break;
1594                     }
1595                 }
1596             }
1597         }
1598
1599         for( int i = 0; i < pid->i_extra_es; i++ )
1600         {
1601             es_out_Send( p_demux->out, pid->extra_es[i]->id,
1602                          block_Duplicate( p_block ) );
1603         }
1604
1605         es_out_Send( p_demux->out, pid->es->id, p_block );
1606     }
1607     else
1608     {
1609         msg_Warn( p_demux, "empty pes" );
1610     }
1611 }
1612
1613 static void ParseTableSection( demux_t *p_demux, ts_pid_t *pid, block_t *p_data )
1614 {
1615     block_t *p_content = block_ChainGather( p_data );
1616     mtime_t i_date = -1;
1617     for( int i = 0; pid->p_owner && i < pid->p_owner->i_prg; i++ )
1618     {
1619         if( pid->i_owner_number == pid->p_owner->prg[i]->i_number )
1620         {
1621             i_date = pid->p_owner->prg[i]->i_pcr_value;
1622             if( i_date >= 0 )
1623                 break;
1624         }
1625     }
1626     if( i_date >= 0 )
1627     {
1628         if( pid->es->fmt.i_codec == VLC_CODEC_SCTE_27 )
1629         {
1630             /* We need to extract the truncated pts stored inside the payload */
1631             if( p_content->i_buffer > 9 && p_content->p_buffer[0] == 0xc6 )
1632             {
1633                 int i_index = 0;
1634                 int i_offset = 4;
1635                 if( p_content->p_buffer[3] & 0x40 )
1636                 {
1637                     i_index = ((p_content->p_buffer[7] & 0x0f) << 8) |
1638                               p_content->p_buffer[8];
1639                     i_offset = 9;
1640                 }
1641                 if( i_index == 0 && p_content->i_buffer > i_offset + 8 )
1642                 {
1643                     bool is_immediate = p_content->p_buffer[i_offset + 3] & 0x40;
1644                     if( !is_immediate )
1645                     {
1646                         mtime_t i_display_in = GetDWBE( &p_content->p_buffer[i_offset + 4] );
1647                         if( i_display_in < i_date )
1648                             i_date = i_display_in + (1ll << 32);
1649                         else
1650                             i_date = i_display_in;
1651                     }
1652
1653                 }
1654             }
1655         }
1656         p_content->i_dts =
1657         p_content->i_pts = VLC_TS_0 + i_date * 100 / 9;
1658     }
1659     es_out_Send( p_demux->out, pid->es->id, p_content );
1660 }
1661 static void ParseData( demux_t *p_demux, ts_pid_t *pid )
1662 {
1663     block_t *p_data = pid->es->p_data;
1664
1665     /* remove the pes from pid */
1666     pid->es->p_data = NULL;
1667     pid->es->i_data_size = 0;
1668     pid->es->i_data_gathered = 0;
1669     pid->es->pp_last = &pid->es->p_data;
1670
1671     if( pid->es->data_type == TS_ES_DATA_PES )
1672     {
1673         ParsePES( p_demux, pid, p_data );
1674     }
1675     else if( pid->es->data_type == TS_ES_DATA_TABLE_SECTION )
1676     {
1677         ParseTableSection( p_demux, pid, p_data );
1678     }
1679     else
1680     {
1681         block_ChainRelease( p_data );
1682     }
1683 }
1684
1685 static block_t* ReadTSPacket( demux_t *p_demux )
1686 {
1687     demux_sys_t *p_sys = p_demux->p_sys;
1688
1689     block_t     *p_pkt;
1690
1691     /* Get a new TS packet */
1692     if( !( p_pkt = stream_Block( p_demux->s, p_sys->i_packet_size ) ) )
1693     {
1694         msg_Dbg( p_demux, "eof ?" );
1695         return NULL;
1696     }
1697
1698     /* Check sync byte and re-sync if needed */
1699     if( p_pkt->p_buffer[0] != 0x47 )
1700     {
1701         msg_Warn( p_demux, "lost synchro" );
1702         block_Release( p_pkt );
1703         while( vlc_object_alive (p_demux) )
1704         {
1705             const uint8_t *p_peek;
1706             int i_peek, i_skip = 0;
1707
1708             i_peek = stream_Peek( p_demux->s, &p_peek,
1709                     p_sys->i_packet_size * 10 );
1710             if( i_peek < p_sys->i_packet_size + 1 )
1711             {
1712                 msg_Dbg( p_demux, "eof ?" );
1713                 return NULL;
1714             }
1715
1716             while( i_skip < i_peek - p_sys->i_packet_size )
1717             {
1718                 if( p_peek[i_skip] == 0x47 &&
1719                         p_peek[i_skip + p_sys->i_packet_size] == 0x47 )
1720                 {
1721                     break;
1722                 }
1723                 i_skip++;
1724             }
1725             msg_Dbg( p_demux, "skipping %d bytes of garbage", i_skip );
1726             stream_Read( p_demux->s, NULL, i_skip );
1727
1728             if( i_skip < i_peek - p_sys->i_packet_size )
1729             {
1730                 break;
1731             }
1732         }
1733         if( !( p_pkt = stream_Block( p_demux->s, p_sys->i_packet_size ) ) )
1734         {
1735             msg_Dbg( p_demux, "eof ?" );
1736             return NULL;
1737         }
1738     }
1739     return p_pkt;
1740 }
1741
1742 static mtime_t AdjustPCRWrapAround( demux_t *p_demux, mtime_t i_pcr )
1743 {
1744     demux_sys_t   *p_sys = p_demux->p_sys;
1745     /*
1746      * PCR is 33bit. If PCR reaches to 0x1FFFFFFFF (26:30:43.717), ressets from 0.
1747      * So, need to add 0x1FFFFFFFF, for calculating duration or current position.
1748      */
1749     mtime_t i_adjust = 0;
1750     int64_t i_pos = stream_Tell( p_demux->s );
1751     int i;
1752     for( i = 1; i < p_sys->i_pcrs_num && p_sys->p_pos[i] <= i_pos; ++i )
1753     {
1754         if( p_sys->p_pcrs[i-1] > p_sys->p_pcrs[i] )
1755             i_adjust += 0x1FFFFFFFF;
1756     }
1757     if( p_sys->p_pcrs[i-1] > i_pcr )
1758         i_adjust += 0x1FFFFFFFF;
1759
1760     return i_pcr + i_adjust;
1761 }
1762
1763 static mtime_t GetPCR( block_t *p_pkt )
1764 {
1765     const uint8_t *p = p_pkt->p_buffer;
1766
1767     mtime_t i_pcr = -1;
1768
1769     if( ( p[3]&0x20 ) && /* adaptation */
1770         ( p[5]&0x10 ) &&
1771         ( p[4] >= 7 ) )
1772     {
1773         /* PCR is 33 bits */
1774         i_pcr = ( (mtime_t)p[6] << 25 ) |
1775                 ( (mtime_t)p[7] << 17 ) |
1776                 ( (mtime_t)p[8] << 9 ) |
1777                 ( (mtime_t)p[9] << 1 ) |
1778                 ( (mtime_t)p[10] >> 7 );
1779     }
1780     return i_pcr;
1781 }
1782
1783 static int SeekToPCR( demux_t *p_demux, int64_t i_pos )
1784 {
1785     demux_sys_t *p_sys = p_demux->p_sys;
1786
1787     mtime_t i_pcr = -1;
1788     int64_t i_initial_pos = stream_Tell( p_demux->s );
1789
1790     if( i_pos < 0 )
1791         return VLC_EGENERIC;
1792
1793     int64_t i_last_pos = i_pos + p_sys->i_packet_size * 4500; //XXX
1794     if( i_last_pos > stream_Size( p_demux->s ) - p_sys->i_packet_size )
1795     {
1796         i_last_pos = stream_Size( p_demux->s ) - p_sys->i_packet_size;
1797     }
1798
1799     if( stream_Seek( p_demux->s, i_pos ) )
1800         return VLC_EGENERIC;
1801
1802     while( vlc_object_alive( p_demux ) )
1803     {
1804         block_t     *p_pkt;
1805         if( !( p_pkt = ReadTSPacket( p_demux ) ) )
1806         {
1807             break;
1808         }
1809         if( PIDGet( p_pkt ) == p_sys->i_pid_ref_pcr )
1810         {
1811             i_pcr = GetPCR( p_pkt );
1812         }
1813         block_Release( p_pkt );
1814         if( i_pcr >= 0 )
1815             break;
1816         if( stream_Tell( p_demux->s ) >= i_last_pos )
1817             break;
1818     }
1819     if( i_pcr < 0 )
1820     {
1821         stream_Seek( p_demux->s, i_initial_pos );
1822         return VLC_EGENERIC;
1823     }
1824     else
1825     {
1826         p_sys->i_current_pcr = i_pcr;
1827         return VLC_SUCCESS;
1828     }
1829 }
1830
1831 static int Seek( demux_t *p_demux, double f_percent )
1832 {
1833     demux_sys_t *p_sys = p_demux->p_sys;
1834
1835     int64_t i_initial_pos = stream_Tell( p_demux->s );
1836     mtime_t i_initial_pcr = p_sys->i_current_pcr;
1837
1838     /*
1839      * Find the time position by using binary search algorithm.
1840      */
1841     mtime_t i_target_pcr = (p_sys->i_last_pcr - p_sys->i_first_pcr) * f_percent + p_sys->i_first_pcr;
1842
1843     int64_t i_head_pos = 0;
1844     int64_t i_tail_pos = stream_Size( p_demux->s );
1845     {
1846         mtime_t i_adjust = 0;
1847         int i;
1848         for( i = 1; i < p_sys->i_pcrs_num; ++i )
1849         {
1850             if( p_sys->p_pcrs[i-1] > p_sys->p_pcrs[i] )
1851                 i_adjust += 0x1FFFFFFFF;
1852             if( p_sys->p_pcrs[i] + i_adjust > i_target_pcr )
1853                 break;
1854         }
1855         i_head_pos = p_sys->p_pos[i-1];
1856         i_tail_pos = ( i < p_sys->i_pcrs_num ) ?  p_sys->p_pos[i] : stream_Size( p_demux->s );
1857     }
1858     msg_Dbg( p_demux, "Seek():i_head_pos:%"PRId64", i_tail_pos:%"PRId64, i_head_pos, i_tail_pos);
1859
1860     bool b_found = false;
1861     int i_cnt = 0;
1862     while( i_head_pos <= i_tail_pos )
1863     {
1864         int64_t i_pos = i_head_pos + (i_tail_pos - i_head_pos) / 2;
1865         if( SeekToPCR( p_demux, i_pos ) )
1866             break;
1867         p_sys->i_current_pcr = AdjustPCRWrapAround( p_demux, p_sys->i_current_pcr );
1868         int64_t i_diff_msec = (p_sys->i_current_pcr - i_target_pcr) * 100 / 9 / 1000;
1869         if( i_diff_msec > 500 )
1870         {
1871             i_tail_pos = i_pos - p_sys->i_packet_size;
1872         }
1873         else if( i_diff_msec < -500 )
1874         {
1875             i_head_pos = i_pos + p_sys->i_packet_size;
1876         }
1877         else
1878         {
1879             // diff time <= 500msec
1880             b_found = true;
1881             break;
1882         }
1883         ++i_cnt;
1884     }
1885     if( !b_found )
1886     {
1887         msg_Dbg( p_demux, "Seek():cannot find a time position. i_cnt:%d", i_cnt );
1888         stream_Seek( p_demux->s, i_initial_pos );
1889         p_sys->i_current_pcr = i_initial_pcr;
1890         return VLC_EGENERIC;
1891     }
1892     else
1893     {
1894         msg_Dbg( p_demux, "Seek():can find a time position. i_cnt:%d", i_cnt );
1895         return VLC_SUCCESS;
1896     }
1897 }
1898
1899 static void GetFirstPCR( demux_t *p_demux )
1900 {
1901     demux_sys_t *p_sys = p_demux->p_sys;
1902
1903     int64_t i_initial_pos = stream_Tell( p_demux->s );
1904
1905     if( stream_Seek( p_demux->s, 0 ) )
1906         return;
1907
1908     while( vlc_object_alive (p_demux) )
1909     {
1910         block_t     *p_pkt;
1911         if( !( p_pkt = ReadTSPacket( p_demux ) ) )
1912         {
1913             break;
1914         }
1915         mtime_t i_pcr = GetPCR( p_pkt );
1916         if( i_pcr >= 0 )
1917         {
1918             p_sys->i_pid_ref_pcr = PIDGet( p_pkt );
1919             p_sys->i_first_pcr = i_pcr;
1920             p_sys->i_current_pcr = i_pcr;
1921         }
1922         block_Release( p_pkt );
1923         if( p_sys->i_first_pcr >= 0 )
1924             break;
1925     }
1926     stream_Seek( p_demux->s, i_initial_pos );
1927 }
1928
1929 static void GetLastPCR( demux_t *p_demux )
1930 {
1931     demux_sys_t *p_sys = p_demux->p_sys;
1932
1933     int64_t i_initial_pos = stream_Tell( p_demux->s );
1934     mtime_t i_initial_pcr = p_sys->i_current_pcr;
1935
1936     int64_t i_last_pos = stream_Size( p_demux->s ) - p_sys->i_packet_size;
1937     int64_t i_pos = i_last_pos - p_sys->i_packet_size * 4500; /* FIXME if the value is not reasonable, please change it. */
1938     if( i_pos < 0 )
1939         return;
1940
1941     while( vlc_object_alive( p_demux ) )
1942     {
1943         if( SeekToPCR( p_demux, i_pos ) )
1944             break;
1945         p_sys->i_last_pcr = AdjustPCRWrapAround( p_demux, p_sys->i_current_pcr );
1946         if( ( i_pos = stream_Tell( p_demux->s ) ) >= i_last_pos )
1947             break;
1948     }
1949     if( p_sys->i_last_pcr >= 0 )
1950     {
1951         int64_t i_size = stream_Size( p_demux->s );
1952         mtime_t i_duration_msec = ( p_sys->i_last_pcr - p_sys->i_first_pcr ) * 100 / 9 / 1000;
1953         int64_t i_rate = ( i_size < 0 || i_duration_msec <= 0 ) ? 0 : i_size * 1000 * 8 / i_duration_msec;
1954         const int64_t TS_SUPPOSED_MAXRATE = 55 * 1000 * 1000; //FIXME I think it's enough.
1955         const int64_t TS_SUPPOSED_MINRATE = 0.5 * 1000 * 1000; //FIXME
1956         if( i_rate < TS_SUPPOSED_MINRATE || i_rate > TS_SUPPOSED_MAXRATE )
1957         {
1958             msg_Dbg( p_demux, "calculated bitrate (%"PRId64"bit/s) is too low or too high. min bitrate (%"PRId64"bit/s) max bitrate (%"PRId64"bit/s)",
1959                      i_rate, TS_SUPPOSED_MINRATE, TS_SUPPOSED_MAXRATE );
1960             p_sys->i_last_pcr = -1;
1961         }
1962     }
1963     stream_Seek( p_demux->s, i_initial_pos );
1964     p_sys->i_current_pcr = i_initial_pcr;
1965 }
1966
1967 static void CheckPCR( demux_t *p_demux )
1968 {
1969     demux_sys_t   *p_sys = p_demux->p_sys;
1970
1971     int64_t i_initial_pos = stream_Tell( p_demux->s );
1972     mtime_t i_initial_pcr = p_sys->i_current_pcr;
1973
1974     int64_t i_size = stream_Size( p_demux->s );
1975
1976     int i = 0;
1977     p_sys->p_pcrs[0] = p_sys->i_first_pcr;
1978     p_sys->p_pos[0] = i_initial_pos;
1979
1980     for( i = 1; i < p_sys->i_pcrs_num && vlc_object_alive( p_demux ); ++i )
1981     {
1982         int64_t i_pos = i_size / p_sys->i_pcrs_num * i;
1983         if( SeekToPCR( p_demux, i_pos ) )
1984             break;
1985         p_sys->p_pcrs[i] = p_sys->i_current_pcr;
1986         p_sys->p_pos[i] = stream_Tell( p_demux->s );
1987         if( p_sys->p_pcrs[i-1] > p_sys->p_pcrs[i] )
1988         {
1989             msg_Dbg( p_demux, "PCR Wrap Around found between %d%% and %d%% (pcr:%"PRId64"(0x%09"PRIx64") pcr:%"PRId64"(0x%09"PRIx64"))",
1990                     (int)((i-1)*100/p_sys->i_pcrs_num), (int)(i*100/p_sys->i_pcrs_num), p_sys->p_pcrs[i-1], p_sys->p_pcrs[i-1], p_sys->p_pcrs[i], p_sys->p_pcrs[i] );
1991         }
1992     }
1993     if( i < p_sys->i_pcrs_num )
1994     {
1995         msg_Dbg( p_demux, "Force Seek Per Percent: Seeking failed at %d%%.", (int)(i*100/p_sys->i_pcrs_num) );
1996         p_sys->b_force_seek_per_percent = true;
1997     }
1998
1999     stream_Seek( p_demux->s, i_initial_pos );
2000     p_sys->i_current_pcr = i_initial_pcr;
2001 }
2002
2003 static void PCRHandle( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
2004 {
2005     demux_sys_t   *p_sys = p_demux->p_sys;
2006
2007     if( p_sys->i_pmt_es <= 0 )
2008         return;
2009
2010     mtime_t i_pcr = GetPCR( p_bk );
2011     if( i_pcr < 0 )
2012         return;
2013
2014     if( p_sys->i_pid_ref_pcr == pid->i_pid )
2015         p_sys->i_current_pcr = AdjustPCRWrapAround( p_demux, i_pcr );
2016
2017     /* Search program and set the PCR */
2018     for( int i = 0; i < p_sys->i_pmt; i++ )
2019         for( int i_prg = 0; i_prg < p_sys->pmt[i]->psi->i_prg; i_prg++ )
2020             if( pid->i_pid == p_sys->pmt[i]->psi->prg[i_prg]->i_pid_pcr )
2021             {
2022                 p_sys->pmt[i]->psi->prg[i_prg]->i_pcr_value = i_pcr;
2023                 es_out_Control( p_demux->out, ES_OUT_SET_GROUP_PCR,
2024                                 (int)p_sys->pmt[i]->psi->prg[i_prg]->i_number,
2025                                 (int64_t)(VLC_TS_0 + i_pcr * 100 / 9) );
2026             }
2027 }
2028
2029 static bool GatherData( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
2030 {
2031     const uint8_t *p = p_bk->p_buffer;
2032     const bool b_unit_start = p[1]&0x40;
2033     const bool b_scrambled  = p[3]&0x80;
2034     const bool b_adaptation = p[3]&0x20;
2035     const bool b_payload    = p[3]&0x10;
2036     const int  i_cc         = p[3]&0x0f; /* continuity counter */
2037     bool       b_discontinuity = false;  /* discontinuity */
2038
2039     /* transport_scrambling_control is ignored */
2040     int         i_skip = 0;
2041     bool        i_ret  = false;
2042
2043 #if 0
2044     msg_Dbg( p_demux, "pid=%d unit_start=%d adaptation=%d payload=%d "
2045              "cc=0x%x", pid->i_pid, b_unit_start, b_adaptation,
2046              b_payload, i_cc );
2047 #endif
2048
2049     /* For now, ignore additional error correction
2050      * TODO: handle Reed-Solomon 204,188 error correction */
2051     p_bk->i_buffer = TS_PACKET_SIZE_188;
2052
2053     if( p[1]&0x80 )
2054     {
2055         msg_Dbg( p_demux, "transport_error_indicator set (pid=%d)",
2056                  pid->i_pid );
2057         if( pid->es->p_data ) //&& pid->es->fmt.i_cat == VIDEO_ES )
2058             pid->es->p_data->i_flags |= BLOCK_FLAG_CORRUPTED;
2059     }
2060
2061     if( p_demux->p_sys->csa )
2062     {
2063         vlc_mutex_lock( &p_demux->p_sys->csa_lock );
2064         csa_Decrypt( p_demux->p_sys->csa, p_bk->p_buffer, p_demux->p_sys->i_csa_pkt_size );
2065         vlc_mutex_unlock( &p_demux->p_sys->csa_lock );
2066     }
2067
2068     if( !b_adaptation )
2069     {
2070         /* We don't have any adaptation_field, so payload starts
2071          * immediately after the 4 byte TS header */
2072         i_skip = 4;
2073     }
2074     else
2075     {
2076         /* p[4] is adaptation_field_length minus one */
2077         i_skip = 5 + p[4];
2078         if( p[4] > 0 )
2079         {
2080             /* discontinuity indicator found in stream */
2081             b_discontinuity = (p[5]&0x80) ? true : false;
2082             if( b_discontinuity && pid->es->p_data )
2083             {
2084                 msg_Warn( p_demux, "discontinuity indicator (pid=%d) ",
2085                             pid->i_pid );
2086                 /* pid->es->p_data->i_flags |= BLOCK_FLAG_DISCONTINUITY; */
2087             }
2088 #if 0
2089             if( p[5]&0x40 )
2090                 msg_Dbg( p_demux, "random access indicator (pid=%d) ", pid->i_pid );
2091 #endif
2092         }
2093     }
2094
2095     /* Test continuity counter */
2096     /* continuous when (one of this):
2097         * diff == 1
2098         * diff == 0 and payload == 0
2099         * diff == 0 and duplicate packet (playload != 0) <- should we
2100         *   test the content ?
2101      */
2102     const int i_diff = ( i_cc - pid->i_cc )&0x0f;
2103     if( b_payload && i_diff == 1 )
2104     {
2105         pid->i_cc = ( pid->i_cc + 1 ) & 0xf;
2106     }
2107     else
2108     {
2109         if( pid->i_cc == 0xff )
2110         {
2111             msg_Warn( p_demux, "first packet for pid=%d cc=0x%x",
2112                       pid->i_pid, i_cc );
2113             pid->i_cc = i_cc;
2114         }
2115         else if( i_diff != 0 && !b_discontinuity )
2116         {
2117             msg_Warn( p_demux, "discontinuity received 0x%x instead of 0x%x (pid=%d)",
2118                       i_cc, ( pid->i_cc + 1 )&0x0f, pid->i_pid );
2119
2120             pid->i_cc = i_cc;
2121             if( pid->es->p_data && pid->es->fmt.i_cat != VIDEO_ES )
2122             {
2123                 /* Small video artifacts are usually better than
2124                  * dropping full frames */
2125                 pid->es->p_data->i_flags |= BLOCK_FLAG_CORRUPTED;
2126             }
2127         }
2128     }
2129
2130     PCRHandle( p_demux, pid, p_bk );
2131
2132     if( i_skip >= 188 || pid->es->id == NULL || p_demux->p_sys->b_udp_out )
2133     {
2134         block_Release( p_bk );
2135         return i_ret;
2136     }
2137
2138     /* */
2139     if( !pid->b_scrambled != !b_scrambled )
2140     {
2141         msg_Warn( p_demux, "scrambled state changed on pid %d (%d->%d)",
2142                   pid->i_pid, pid->b_scrambled, b_scrambled );
2143
2144         pid->b_scrambled = b_scrambled;
2145
2146         for( int i = 0; i < pid->i_extra_es; i++ )
2147         {
2148             es_out_Control( p_demux->out, ES_OUT_SET_ES_SCRAMBLED_STATE,
2149                             pid->extra_es[i]->id, b_scrambled );
2150         }
2151         es_out_Control( p_demux->out, ES_OUT_SET_ES_SCRAMBLED_STATE,
2152                         pid->es->id, b_scrambled );
2153     }
2154
2155     /* We have to gather it */
2156     p_bk->p_buffer += i_skip;
2157     p_bk->i_buffer -= i_skip;
2158
2159     if( b_unit_start )
2160     {
2161         if( pid->es->data_type == TS_ES_DATA_TABLE_SECTION && p_bk->i_buffer > 0 )
2162         {
2163             int i_pointer_field = __MIN( p_bk->p_buffer[0], p_bk->i_buffer - 1 );
2164             block_t *p = block_Duplicate( p_bk );
2165             if( p )
2166             {
2167                 p->i_buffer = i_pointer_field;
2168                 p->p_buffer++;
2169                 block_ChainLastAppend( &pid->es->pp_last, p );
2170             }
2171             p_bk->i_buffer -= 1 + i_pointer_field;
2172             p_bk->p_buffer += 1 + i_pointer_field;
2173         }
2174         if( pid->es->p_data )
2175         {
2176             ParseData( p_demux, pid );
2177             i_ret = true;
2178         }
2179
2180         block_ChainLastAppend( &pid->es->pp_last, p_bk );
2181         if( pid->es->data_type == TS_ES_DATA_PES )
2182         {
2183             if( p_bk->i_buffer > 6 )
2184             {
2185                 pid->es->i_data_size = GetWBE( &p_bk->p_buffer[4] );
2186                 if( pid->es->i_data_size > 0 )
2187                 {
2188                     pid->es->i_data_size += 6;
2189                 }
2190             }
2191         }
2192         else if( pid->es->data_type == TS_ES_DATA_TABLE_SECTION )
2193         {
2194             if( p_bk->i_buffer > 3 && p_bk->p_buffer[0] != 0xff )
2195             {
2196                 pid->es->i_data_size = 3 + (((p_bk->p_buffer[1] & 0xf) << 8) | p_bk->p_buffer[2]);
2197             }
2198         }
2199         pid->es->i_data_gathered += p_bk->i_buffer;
2200         if( pid->es->i_data_size > 0 &&
2201             pid->es->i_data_gathered >= pid->es->i_data_size )
2202         {
2203             ParseData( p_demux, pid );
2204             i_ret = true;
2205         }
2206     }
2207     else
2208     {
2209         if( pid->es->p_data == NULL )
2210         {
2211             /* msg_Dbg( p_demux, "broken packet" ); */
2212             block_Release( p_bk );
2213         }
2214         else
2215         {
2216             block_ChainLastAppend( &pid->es->pp_last, p_bk );
2217             pid->es->i_data_gathered += p_bk->i_buffer;
2218
2219             if( pid->es->i_data_size > 0 &&
2220                 pid->es->i_data_gathered >= pid->es->i_data_size )
2221             {
2222                 ParseData( p_demux, pid );
2223                 i_ret = true;
2224             }
2225         }
2226     }
2227
2228     return i_ret;
2229 }
2230
2231 static void PIDFillFormat( ts_es_t *es, int i_stream_type )
2232 {
2233     es_format_t *fmt = &es->fmt;
2234
2235     switch( i_stream_type )
2236     {
2237     case 0x01:  /* MPEG-1 video */
2238     case 0x02:  /* MPEG-2 video */
2239     case 0x80:  /* MPEG-2 MOTO video */
2240         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_MPGV );
2241         break;
2242     case 0x03:  /* MPEG-1 audio */
2243     case 0x04:  /* MPEG-2 audio */
2244         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_MPGA );
2245         break;
2246     case 0x11:  /* MPEG4 (audio) LATM */
2247     case 0x0f:  /* ISO/IEC 13818-7 Audio with ADTS transport syntax */
2248         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_MP4A );
2249         break;
2250     case 0x10:  /* MPEG4 (video) */
2251         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_MP4V );
2252         break;
2253     case 0x1B:  /* H264 <- check transport syntax/needed descriptor */
2254         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_H264 );
2255         break;
2256     case 0x42:  /* CAVS (Chinese AVS) */
2257         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_CAVS );
2258         break;
2259
2260     case 0x81:  /* A52 (audio) */
2261         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_A52 );
2262         break;
2263     case 0x82:  /* SCTE-27 (sub) */
2264         es_format_Init( fmt, SPU_ES, VLC_CODEC_SCTE_27 );
2265         es->data_type = TS_ES_DATA_TABLE_SECTION;
2266         break;
2267     case 0x83:  /* LPCM (audio) */
2268         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_DVD_LPCM );
2269         break;
2270     case 0x84:  /* SDDS (audio) */
2271         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_SDDS );
2272         break;
2273     case 0x85:  /* DTS (audio) */
2274         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_DTS );
2275         break;
2276     case 0x87: /* E-AC3 */
2277         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_EAC3 );
2278         break;
2279
2280     case 0x91:  /* A52 vls (audio) */
2281         es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'a', '5', '2', 'b' ) );
2282         break;
2283     case 0x92:  /* DVD_SPU vls (sub) */
2284         es_format_Init( fmt, SPU_ES, VLC_FOURCC( 's', 'p', 'u', 'b' ) );
2285         break;
2286
2287     case 0x94:  /* SDDS (audio) */
2288         es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 's', 'd', 'd', 'b' ) );
2289         break;
2290
2291     case 0xa0:  /* MSCODEC vlc (video) (fixed later) */
2292         es_format_Init( fmt, UNKNOWN_ES, 0 );
2293         break;
2294
2295     case 0x06:  /* PES_PRIVATE  (fixed later) */
2296     case 0x12:  /* MPEG-4 generic (sub/scene/...) (fixed later) */
2297     case 0xEA:  /* Privately managed ES (VC-1) (fixed later */
2298     default:
2299         es_format_Init( fmt, UNKNOWN_ES, 0 );
2300         break;
2301     }
2302
2303     /* PES packets usually contain truncated frames */
2304     fmt->b_packetized = false;
2305 }
2306
2307 /*****************************************************************************
2308  * MP4 specific functions (IOD parser)
2309  *****************************************************************************/
2310 static int  IODDescriptorLength( int *pi_data, uint8_t **pp_data )
2311 {
2312     unsigned int i_b;
2313     unsigned int i_len = 0;
2314     do
2315     {
2316         i_b = **pp_data;
2317         (*pp_data)++;
2318         (*pi_data)--;
2319         i_len = ( i_len << 7 ) + ( i_b&0x7f );
2320
2321     } while( i_b&0x80 && *pi_data > 0 );
2322
2323     if (i_len > *pi_data)
2324         i_len = *pi_data;
2325
2326     return i_len;
2327 }
2328
2329 static int IODGetBytes( int *pi_data, uint8_t **pp_data, size_t bytes )
2330 {
2331     uint32_t res = 0;
2332     while( *pi_data > 0 && bytes-- )
2333     {
2334         res <<= 8;
2335         res |= **pp_data;
2336         (*pp_data)++;
2337         (*pi_data)--;
2338     }
2339
2340     return res;
2341 }
2342
2343 static char* IODGetURL( int *pi_data, uint8_t **pp_data )
2344 {
2345     int len = IODGetBytes( pi_data, pp_data, 1 );
2346     if (len > *pi_data)
2347         len = *pi_data;
2348     char *url = strndup( (char*)*pp_data, len );
2349     *pp_data += len;
2350     *pi_data -= len;
2351     return url;
2352 }
2353
2354 static iod_descriptor_t *IODNew( int i_data, uint8_t *p_data )
2355 {
2356     uint8_t i_iod_tag, i_iod_label, byte1, byte2, byte3;
2357
2358     iod_descriptor_t *p_iod = calloc( 1, sizeof( iod_descriptor_t ) );
2359     if( !p_iod )
2360         return NULL;
2361
2362     if( i_data < 3 )
2363     {
2364         return p_iod;
2365     }
2366
2367     byte1 = IODGetBytes( &i_data, &p_data, 1 );
2368     byte2 = IODGetBytes( &i_data, &p_data, 1 );
2369     byte3 = IODGetBytes( &i_data, &p_data, 1 );
2370     if( byte2 == 0x02 ) //old vlc's buggy implementation of the IOD_descriptor
2371     {
2372         i_iod_label = byte1;
2373         i_iod_tag = byte2;
2374     }
2375     else  //correct implementation of the IOD_descriptor
2376     {
2377         i_iod_label = byte2;
2378         i_iod_tag = byte3;
2379     }
2380
2381     ts_debug( "\n* iod label:%d tag:0x%x", i_iod_label, i_iod_tag );
2382
2383     if( i_iod_tag != 0x02 )
2384     {
2385         ts_debug( "\n ERR: tag %02x != 0x02", i_iod_tag );
2386         return p_iod;
2387     }
2388
2389     IODDescriptorLength( &i_data, &p_data );
2390
2391     uint16_t i_od_id = ( IODGetBytes( &i_data, &p_data, 1 ) << 2 );
2392     uint8_t i_flags = IODGetBytes( &i_data, &p_data, 1 );
2393     i_od_id |= i_flags >> 6;
2394     ts_debug( "\n* od_id:%d", i_od_id );
2395     ts_debug( "\n* includeInlineProfileLevel flag:%d", ( i_flags >> 4 )&0x01 );
2396     if ((i_flags >> 5) & 0x01)
2397     {
2398         p_iod->psz_url = IODGetURL( &i_data, &p_data );
2399         ts_debug( "\n* url string:%s", p_iod->psz_url );
2400         ts_debug( "\n*****************************\n" );
2401         return p_iod;
2402     }
2403     else
2404     {
2405         p_iod->psz_url = NULL;
2406     }
2407
2408     /* Profile Level Indication */
2409     IODGetBytes( &i_data, &p_data, 1 ); /* OD */
2410     IODGetBytes( &i_data, &p_data, 1 ); /* scene */
2411     IODGetBytes( &i_data, &p_data, 1 ); /* audio */
2412     IODGetBytes( &i_data, &p_data, 1 ); /* visual */
2413     IODGetBytes( &i_data, &p_data, 1 ); /* graphics */
2414
2415     int i_length = 0;
2416     int i_data_sav = i_data;
2417     uint8_t *p_data_sav = p_data;
2418     for (int i = 0; i_data > 0 && i < 255; i++)
2419     {
2420         es_mpeg4_descriptor_t *es_descr = &p_iod->es_descr[i];
2421
2422         p_data = p_data_sav + i_length;
2423         i_data = i_data_sav - i_length;
2424
2425         int i_tag = IODGetBytes( &i_data, &p_data, 1 );
2426         i_length = IODDescriptorLength( &i_data, &p_data );
2427
2428         i_data_sav = i_data;
2429         p_data_sav = p_data;
2430
2431         i_data = i_length;
2432
2433         if ( i_tag != 0x03 )
2434         {
2435             ts_debug( "\n* - OD tag:0x%x Unsupported", i_tag );
2436             continue;
2437         }
2438
2439         es_descr->i_es_id = IODGetBytes( &i_data, &p_data, 2 );
2440         int i_flags = IODGetBytes( &i_data, &p_data, 1 );
2441         bool b_streamDependenceFlag = ( i_flags >> 7 )&0x01;
2442         if( b_streamDependenceFlag )
2443             IODGetBytes( &i_data, &p_data, 2 ); /* dependOn_es_id */
2444
2445         if( (i_flags >> 6) & 0x01 )
2446             es_descr->psz_url = IODGetURL( &i_data, &p_data );
2447
2448         bool b_OCRStreamFlag = ( i_flags >> 5 )&0x01;
2449         if( b_OCRStreamFlag )
2450             IODGetBytes( &i_data, &p_data, 2 ); /* OCR_es_id */
2451
2452         if( IODGetBytes( &i_data, &p_data, 1 ) != 0x04 )
2453         {
2454             ts_debug( "\n* ERR missing DecoderConfigDescr" );
2455             continue;
2456         }
2457         decoder_config_descriptor_t *dec_descr = &es_descr->dec_descr;
2458         dec_descr->i_objectTypeIndication = IODGetBytes( &i_data, &p_data, 1 );
2459         i_flags = IODGetBytes( &i_data, &p_data, 1 );
2460         dec_descr->i_streamType = i_flags >> 2;
2461
2462         IODGetBytes( &i_data, &p_data, 3); /* bufferSizeDB */
2463         IODGetBytes( &i_data, &p_data, 4); /* maxBitrate */
2464         IODGetBytes( &i_data, &p_data, 4 ); /* avgBitrate */
2465
2466         int i_decoderConfigDescr_length = IODDescriptorLength( &i_data, &p_data );
2467         if( i_decoderConfigDescr_length > 13 && IODGetBytes( &i_data, &p_data, 1 ) == 0x05 )
2468         {
2469             dec_descr->i_extra = IODDescriptorLength( &i_data, &p_data );
2470             if( dec_descr->i_extra > 0 )
2471             {
2472                 dec_descr->p_extra = xmalloc( dec_descr->i_extra );
2473                 memcpy(dec_descr->p_extra, p_data, dec_descr->i_extra);
2474                 p_data += dec_descr->i_extra;
2475                 i_data -= dec_descr->i_extra;
2476             }
2477         }
2478         else
2479         {
2480             dec_descr->i_extra = 0;
2481             dec_descr->p_extra = NULL;
2482         }
2483
2484         if( IODGetBytes( &i_data, &p_data, 1 ) != 0x06 )
2485         {
2486             ts_debug( "\n* ERR missing SLConfigDescr" );
2487             continue;
2488         }
2489         IODDescriptorLength( &i_data, &p_data ); /* SLConfigDescr_length */
2490         switch( IODGetBytes( &i_data, &p_data, 1 ) /* predefined */ )
2491         {
2492         default:
2493             ts_debug( "\n* ERR unsupported SLConfigDescr predefined" );
2494         case 0x01:
2495             // FIXME
2496             break;
2497         }
2498         es_descr->b_ok = true;
2499     }
2500
2501     return p_iod;
2502 }
2503
2504 static void IODFree( iod_descriptor_t *p_iod )
2505 {
2506     if( p_iod->psz_url )
2507     {
2508         free( p_iod->psz_url );
2509         free( p_iod );
2510         return;
2511     }
2512
2513     for( int i = 0; i < 255; i++ )
2514     {
2515 #define es_descr p_iod->es_descr[i]
2516         if( es_descr.b_ok )
2517         {
2518             if( es_descr.psz_url )
2519                 free( es_descr.psz_url );
2520             else
2521                 free( es_descr.dec_descr.p_extra );
2522         }
2523 #undef  es_descr
2524     }
2525     free( p_iod );
2526 }
2527
2528 /****************************************************************************
2529  ****************************************************************************
2530  ** libdvbpsi callbacks
2531  ****************************************************************************
2532  ****************************************************************************/
2533 static bool ProgramIsSelected( demux_t *p_demux, uint16_t i_pgrm )
2534 {
2535     demux_sys_t          *p_sys = p_demux->p_sys;
2536
2537     if( ( p_sys->i_current_program == -1 && p_sys->programs_list.i_count == 0 ) ||
2538         p_sys->i_current_program == 0 )
2539         return true;
2540     if( p_sys->i_current_program == i_pgrm )
2541         return true;
2542
2543     if( p_sys->programs_list.i_count != 0 )
2544     {
2545         for( int i = 0; i < p_sys->programs_list.i_count; i++ )
2546         {
2547             if( i_pgrm == p_sys->programs_list.p_values[i].i_int )
2548                 return true;
2549         }
2550     }
2551     return false;
2552 }
2553
2554 static void ValidateDVBMeta( demux_t *p_demux, int i_pid )
2555 {
2556     demux_sys_t *p_sys = p_demux->p_sys;
2557
2558     if( !p_sys->b_dvb_meta || ( i_pid != 0x11 && i_pid != 0x12 && i_pid != 0x14 ) )
2559         return;
2560
2561     msg_Warn( p_demux, "Switching to non DVB mode" );
2562
2563     /* This doesn't look like a DVB stream so don't try
2564      * parsing the SDT/EDT/TDT */
2565
2566     for( int i = 0x11; i <= 0x14; i++ )
2567     {
2568         if( i == 0x13 ) continue;
2569         ts_pid_t *p_pid = &p_sys->pid[i];
2570         if( p_pid->psi )
2571         {
2572             dvbpsi_DetachDemux( p_pid->psi->handle );
2573             free( p_pid->psi );
2574             p_pid->psi = NULL;
2575             p_pid->b_valid = false;
2576         }
2577         SetPIDFilter( p_demux, i, false );
2578     }
2579     p_sys->b_dvb_meta = false;
2580 }
2581
2582 #include "dvb-text.h"
2583
2584 static char *EITConvertToUTF8( const unsigned char *psz_instring,
2585                                size_t i_length,
2586                                bool b_broken )
2587 {
2588     /* Deal with no longer broken providers (no switch byte
2589       but sending ISO_8859-1 instead of ISO_6937) without
2590       removing them from the broken providers table
2591       (keep the entry for correctly handling recorded TS).
2592     */
2593     b_broken = b_broken && i_length && *psz_instring > 0x20;
2594
2595     if( b_broken )
2596         return FromCharset( "ISO_8859-1", psz_instring, i_length );
2597     return vlc_from_EIT( psz_instring, i_length );
2598 }
2599
2600 static void SDTCallBack( demux_t *p_demux, dvbpsi_sdt_t *p_sdt )
2601 {
2602     demux_sys_t          *p_sys = p_demux->p_sys;
2603     ts_pid_t             *sdt = &p_sys->pid[0x11];
2604     dvbpsi_sdt_service_t *p_srv;
2605
2606     msg_Dbg( p_demux, "SDTCallBack called" );
2607
2608     if( sdt->psi->i_sdt_version != -1 &&
2609         ( !p_sdt->b_current_next ||
2610           p_sdt->i_version == sdt->psi->i_sdt_version ) )
2611     {
2612         dvbpsi_DeleteSDT( p_sdt );
2613         return;
2614     }
2615
2616     msg_Dbg( p_demux, "new SDT ts_id=%d version=%d current_next=%d "
2617              "network_id=%d",
2618              p_sdt->i_ts_id, p_sdt->i_version, p_sdt->b_current_next,
2619              p_sdt->i_network_id );
2620
2621     p_sys->b_broken_charset = false;
2622
2623     for( p_srv = p_sdt->p_first_service; p_srv; p_srv = p_srv->p_next )
2624     {
2625         vlc_meta_t          *p_meta;
2626         dvbpsi_descriptor_t *p_dr;
2627
2628         const char *psz_type = NULL;
2629         const char *psz_status = NULL;
2630
2631         msg_Dbg( p_demux, "  * service id=%d eit schedule=%d present=%d "
2632                  "running=%d free_ca=%d",
2633                  p_srv->i_service_id, p_srv->b_eit_schedule,
2634                  p_srv->b_eit_present, p_srv->i_running_status,
2635                  p_srv->b_free_ca );
2636
2637         p_meta = vlc_meta_New();
2638         for( p_dr = p_srv->p_first_descriptor; p_dr; p_dr = p_dr->p_next )
2639         {
2640             if( p_dr->i_tag == 0x48 )
2641             {
2642                 static const char *ppsz_type[17] = {
2643                     "Reserved",
2644                     "Digital television service",
2645                     "Digital radio sound service",
2646                     "Teletext service",
2647                     "NVOD reference service",
2648                     "NVOD time-shifted service",
2649                     "Mosaic service",
2650                     "PAL coded signal",
2651                     "SECAM coded signal",
2652                     "D/D2-MAC",
2653                     "FM Radio",
2654                     "NTSC coded signal",
2655                     "Data broadcast service",
2656                     "Reserved for Common Interface Usage",
2657                     "RCS Map (see EN 301 790 [35])",
2658                     "RCS FLS (see EN 301 790 [35])",
2659                     "DVB MHP service"
2660                 };
2661                 dvbpsi_service_dr_t *pD = dvbpsi_DecodeServiceDr( p_dr );
2662                 char *str1 = NULL;
2663                 char *str2 = NULL;
2664
2665                 /* Workarounds for broadcasters with broken EPG */
2666
2667                 if( p_sdt->i_network_id == 133 )
2668                     p_sys->b_broken_charset = true;  /* SKY DE & BetaDigital use ISO8859-1 */
2669
2670                 /* List of providers using ISO8859-1 */
2671                 static const char ppsz_broken_providers[][8] = {
2672                     "CSAT",     /* CanalSat FR */
2673                     "GR1",      /* France televisions */
2674                     "MULTI4",   /* NT1 */
2675                     "MR5",      /* France 2/M6 HD */
2676                     ""
2677                 };
2678                 for( int i = 0; *ppsz_broken_providers[i]; i++ )
2679                 {
2680                     const size_t i_length = strlen(ppsz_broken_providers[i]);
2681                     if( pD->i_service_provider_name_length == i_length &&
2682                         !strncmp( (char *)pD->i_service_provider_name, ppsz_broken_providers[i], i_length ) )
2683                         p_sys->b_broken_charset = true;
2684                 }
2685
2686                 /* FIXME: Digital+ ES also uses ISO8859-1 */
2687
2688                 str1 = EITConvertToUTF8(pD->i_service_provider_name,
2689                                         pD->i_service_provider_name_length,
2690                                         p_sys->b_broken_charset );
2691                 str2 = EITConvertToUTF8(pD->i_service_name,
2692                                         pD->i_service_name_length,
2693                                         p_sys->b_broken_charset );
2694
2695                 msg_Dbg( p_demux, "    - type=%d provider=%s name=%s",
2696                          pD->i_service_type, str1, str2 );
2697
2698                 vlc_meta_SetTitle( p_meta, str2 );
2699                 vlc_meta_SetPublisher( p_meta, str1 );
2700                 if( pD->i_service_type >= 0x01 && pD->i_service_type <= 0x10 )
2701                     psz_type = ppsz_type[pD->i_service_type];
2702                 free( str1 );
2703                 free( str2 );
2704             }
2705         }
2706
2707         if( p_srv->i_running_status >= 0x01 && p_srv->i_running_status <= 0x04 )
2708         {
2709             static const char *ppsz_status[5] = {
2710                 "Unknown",
2711                 "Not running",
2712                 "Starts in a few seconds",
2713                 "Pausing",
2714                 "Running"
2715             };
2716             psz_status = ppsz_status[p_srv->i_running_status];
2717         }
2718
2719         if( psz_type )
2720             vlc_meta_AddExtra( p_meta, "Type", psz_type );
2721         if( psz_status )
2722             vlc_meta_AddExtra( p_meta, "Status", psz_status );
2723
2724         es_out_Control( p_demux->out, ES_OUT_SET_GROUP_META,
2725                         p_srv->i_service_id, p_meta );
2726         vlc_meta_Delete( p_meta );
2727     }
2728
2729     sdt->psi->i_sdt_version = p_sdt->i_version;
2730     dvbpsi_DeleteSDT( p_sdt );
2731 }
2732
2733 /* i_year: year - 1900  i_month: 0-11  i_mday: 1-31 i_hour: 0-23 i_minute: 0-59 i_second: 0-59 */
2734 static int64_t vlc_timegm( int i_year, int i_month, int i_mday, int i_hour, int i_minute, int i_second )
2735 {
2736     static const int pn_day[12+1] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
2737     int64_t i_day;
2738
2739     if( i_year < 70 ||
2740         i_month < 0 || i_month > 11 || i_mday < 1 || i_mday > 31 ||
2741         i_hour < 0 || i_hour > 23 || i_minute < 0 || i_minute > 59 || i_second < 0 || i_second > 59 )
2742         return -1;
2743
2744     /* Count the number of days */
2745     i_day = 365 * (i_year-70) + pn_day[i_month] + i_mday - 1;
2746 #define LEAP(y) ( ((y)%4) == 0 && (((y)%100) != 0 || ((y)%400) == 0) ? 1 : 0)
2747     for( int i = 70; i < i_year; i++ )
2748         i_day += LEAP(1900+i);
2749     if( i_month > 1 )
2750         i_day += LEAP(1900+i_year);
2751 #undef LEAP
2752     /**/
2753     return ((24*i_day + i_hour)*60 + i_minute)*60 + i_second;
2754 }
2755
2756 static void EITDecodeMjd( int i_mjd, int *p_y, int *p_m, int *p_d )
2757 {
2758     const int yp = (int)( ( (double)i_mjd - 15078.2)/365.25 );
2759     const int mp = (int)( ((double)i_mjd - 14956.1 - (int)(yp * 365.25)) / 30.6001 );
2760     const int c = ( mp == 14 || mp == 15 ) ? 1 : 0;
2761
2762     *p_y = 1900 + yp + c*1;
2763     *p_m = mp - 1 - c*12;
2764     *p_d = i_mjd - 14956 - (int)(yp*365.25) - (int)(mp*30.6001);
2765 }
2766 #define CVT_FROM_BCD(v) ((((v) >> 4)&0xf)*10 + ((v)&0xf))
2767 static int64_t EITConvertStartTime( uint64_t i_date )
2768 {
2769     const int i_mjd = i_date >> 24;
2770     const int i_hour   = CVT_FROM_BCD(i_date >> 16);
2771     const int i_minute = CVT_FROM_BCD(i_date >>  8);
2772     const int i_second = CVT_FROM_BCD(i_date      );
2773     int i_year;
2774     int i_month;
2775     int i_day;
2776
2777     /* if all 40 bits are 1, the start is unknown */
2778     if( i_date == UINT64_C(0xffffffffff) )
2779         return -1;
2780
2781     EITDecodeMjd( i_mjd, &i_year, &i_month, &i_day );
2782     return vlc_timegm( i_year - 1900, i_month - 1, i_day, i_hour, i_minute, i_second );
2783 }
2784 static int EITConvertDuration( uint32_t i_duration )
2785 {
2786     return CVT_FROM_BCD(i_duration >> 16) * 3600 +
2787            CVT_FROM_BCD(i_duration >> 8 ) * 60 +
2788            CVT_FROM_BCD(i_duration      );
2789 }
2790 #undef CVT_FROM_BCD
2791
2792 static void TDTCallBack( demux_t *p_demux, dvbpsi_tot_t *p_tdt )
2793 {
2794     demux_sys_t        *p_sys = p_demux->p_sys;
2795
2796     p_sys->i_tdt_delta = CLOCK_FREQ * EITConvertStartTime( p_tdt->i_utc_time )
2797                          - mdate();
2798     dvbpsi_DeleteTOT(p_tdt);
2799 }
2800
2801
2802 static void EITCallBack( demux_t *p_demux,
2803                          dvbpsi_eit_t *p_eit, bool b_current_following )
2804 {
2805     demux_sys_t        *p_sys = p_demux->p_sys;
2806     dvbpsi_eit_event_t *p_evt;
2807     vlc_epg_t *p_epg;
2808
2809     msg_Dbg( p_demux, "EITCallBack called" );
2810     if( !p_eit->b_current_next )
2811     {
2812         dvbpsi_DeleteEIT( p_eit );
2813         return;
2814     }
2815
2816     msg_Dbg( p_demux, "new EIT service_id=%d version=%d current_next=%d "
2817              "ts_id=%d network_id=%d segment_last_section_number=%d "
2818              "last_table_id=%d",
2819              p_eit->i_service_id, p_eit->i_version, p_eit->b_current_next,
2820              p_eit->i_ts_id, p_eit->i_network_id,
2821              p_eit->i_segment_last_section_number, p_eit->i_last_table_id );
2822
2823     p_epg = vlc_epg_New( NULL );
2824     for( p_evt = p_eit->p_first_event; p_evt; p_evt = p_evt->p_next )
2825     {
2826         dvbpsi_descriptor_t *p_dr;
2827         char                *psz_name = NULL;
2828         char                *psz_text = NULL;
2829         char                *psz_extra = strdup("");
2830         int64_t i_start;
2831         int i_duration;
2832         int i_min_age = 0;
2833
2834         i_start = EITConvertStartTime( p_evt->i_start_time );
2835         i_duration = EITConvertDuration( p_evt->i_duration );
2836
2837         msg_Dbg( p_demux, "  * event id=%d start_time:%d duration=%d "
2838                           "running=%d free_ca=%d",
2839                  p_evt->i_event_id, (int)i_start, (int)i_duration,
2840                  p_evt->i_running_status, p_evt->b_free_ca );
2841
2842         for( p_dr = p_evt->p_first_descriptor; p_dr; p_dr = p_dr->p_next )
2843         {
2844             if( p_dr->i_tag == 0x4d )
2845             {
2846                 dvbpsi_short_event_dr_t *pE = dvbpsi_DecodeShortEventDr( p_dr );
2847
2848                 /* Only take first description, as we don't handle language-info
2849                    for epg atm*/
2850                 if( pE && psz_name == NULL)
2851                 {
2852                     psz_name = EITConvertToUTF8( pE->i_event_name, pE->i_event_name_length,
2853                                                  p_sys->b_broken_charset );
2854                     psz_text = EITConvertToUTF8( pE->i_text, pE->i_text_length,
2855                                                  p_sys->b_broken_charset );
2856                     msg_Dbg( p_demux, "    - short event lang=%3.3s '%s' : '%s'",
2857                              pE->i_iso_639_code, psz_name, psz_text );
2858                 }
2859             }
2860             else if( p_dr->i_tag == 0x4e )
2861             {
2862                 dvbpsi_extended_event_dr_t *pE = dvbpsi_DecodeExtendedEventDr( p_dr );
2863                 if( pE )
2864                 {
2865                     msg_Dbg( p_demux, "    - extended event lang=%3.3s [%d/%d]",
2866                              pE->i_iso_639_code,
2867                              pE->i_descriptor_number, pE->i_last_descriptor_number );
2868
2869                     if( pE->i_text_length > 0 )
2870                     {
2871                         char *psz_text = EITConvertToUTF8( pE->i_text, pE->i_text_length,
2872                                                            p_sys->b_broken_charset );
2873                         if( psz_text )
2874                         {
2875                             msg_Dbg( p_demux, "       - text='%s'", psz_text );
2876
2877                             psz_extra = xrealloc( psz_extra,
2878                                    strlen(psz_extra) + strlen(psz_text) + 1 );
2879                             strcat( psz_extra, psz_text );
2880                             free( psz_text );
2881                         }
2882                     }
2883
2884                     for( int i = 0; i < pE->i_entry_count; i++ )
2885                     {
2886                         char *psz_dsc = EITConvertToUTF8( pE->i_item_description[i],
2887                                                           pE->i_item_description_length[i],
2888                                                           p_sys->b_broken_charset );
2889                         char *psz_itm = EITConvertToUTF8( pE->i_item[i], pE->i_item_length[i],
2890                                                           p_sys->b_broken_charset );
2891
2892                         if( psz_dsc && psz_itm )
2893                         {
2894                             msg_Dbg( p_demux, "       - desc='%s' item='%s'", psz_dsc, psz_itm );
2895 #if 0
2896                             psz_extra = xrealloc( psz_extra,
2897                                          strlen(psz_extra) + strlen(psz_dsc) +
2898                                          strlen(psz_itm) + 3 + 1 );
2899                             strcat( psz_extra, "(" );
2900                             strcat( psz_extra, psz_dsc );
2901                             strcat( psz_extra, " " );
2902                             strcat( psz_extra, psz_itm );
2903                             strcat( psz_extra, ")" );
2904 #endif
2905                         }
2906                         free( psz_dsc );
2907                         free( psz_itm );
2908                     }
2909                 }
2910             }
2911             else if( p_dr->i_tag == 0x55 )
2912             {
2913                 dvbpsi_parental_rating_dr_t *pR = dvbpsi_DecodeParentalRatingDr( p_dr );
2914                 if ( pR )
2915                 {
2916                     for ( int i = 0; i < pR->i_ratings_number; i++ )
2917                     {
2918                         const dvbpsi_parental_rating_t *p_rating = & pR->p_parental_rating[ i ];
2919                         if ( p_rating->i_rating > 0x00 && p_rating->i_rating <= 0x0F )
2920                         {
2921                             if ( p_rating->i_rating + 3 > i_min_age )
2922                                 i_min_age = p_rating->i_rating + 3;
2923                             msg_Dbg( p_demux, "..* event parental control set to %d years",
2924                                      i_min_age );
2925                         }
2926                     }
2927                 }
2928             }
2929             else
2930             {
2931                 msg_Dbg( p_demux, "    - tag=0x%x(%d)", p_dr->i_tag, p_dr->i_tag );
2932             }
2933         }
2934
2935         /* */
2936         if( i_start > 0 )
2937             vlc_epg_AddEvent( p_epg, i_start, i_duration, psz_name, psz_text,
2938                               *psz_extra ? psz_extra : NULL, i_min_age );
2939
2940         /* Update "now playing" field */
2941         if( p_evt->i_running_status == 0x04 && i_start > 0 )
2942             vlc_epg_SetCurrent( p_epg, i_start );
2943
2944         free( psz_name );
2945         free( psz_text );
2946
2947         free( psz_extra );
2948     }
2949     if( p_epg->i_event > 0 )
2950     {
2951         if( b_current_following &&
2952             (  p_sys->i_current_program == -1 ||
2953                p_sys->i_current_program == p_eit->i_service_id ) )
2954         {
2955             p_sys->i_dvb_length = 0;
2956             p_sys->i_dvb_start = 0;
2957
2958             if( p_epg->p_current )
2959             {
2960                 p_sys->i_dvb_start = CLOCK_FREQ * p_epg->p_current->i_start;
2961                 p_sys->i_dvb_length = CLOCK_FREQ * p_epg->p_current->i_duration;
2962             }
2963         }
2964         es_out_Control( p_demux->out, ES_OUT_SET_GROUP_EPG, p_eit->i_service_id, p_epg );
2965     }
2966     vlc_epg_Delete( p_epg );
2967
2968     dvbpsi_DeleteEIT( p_eit );
2969 }
2970 static void EITCallBackCurrentFollowing( demux_t *p_demux, dvbpsi_eit_t *p_eit )
2971 {
2972     EITCallBack( p_demux, p_eit, true );
2973 }
2974 static void EITCallBackSchedule( demux_t *p_demux, dvbpsi_eit_t *p_eit )
2975 {
2976     EITCallBack( p_demux, p_eit, false );
2977 }
2978
2979 static void PSINewTableCallBack( demux_t *p_demux, dvbpsi_handle h,
2980                                  uint8_t  i_table_id, uint16_t i_extension )
2981 {
2982 #if 0
2983     msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
2984              i_table_id, i_table_id, i_extension, i_extension );
2985 #endif
2986     if( p_demux->p_sys->pid[0].psi->i_pat_version != -1 && i_table_id == 0x42 )
2987     {
2988         msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
2989                  i_table_id, i_table_id, i_extension, i_extension );
2990
2991         dvbpsi_AttachSDT( h, i_table_id, i_extension,
2992                           (dvbpsi_sdt_callback)SDTCallBack, p_demux );
2993     }
2994     else if( p_demux->p_sys->pid[0x11].psi->i_sdt_version != -1 &&
2995              ( i_table_id == 0x4e || /* Current/Following */
2996                (i_table_id >= 0x50 && i_table_id <= 0x5f) ) ) /* Schedule */
2997     {
2998         msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
2999                  i_table_id, i_table_id, i_extension, i_extension );
3000
3001         dvbpsi_eit_callback cb = i_table_id == 0x4e ?
3002                                     (dvbpsi_eit_callback)EITCallBackCurrentFollowing :
3003                                     (dvbpsi_eit_callback)EITCallBackSchedule;
3004         dvbpsi_AttachEIT( h, i_table_id, i_extension, cb, p_demux );
3005     }
3006     else if( p_demux->p_sys->pid[0x11].psi->i_sdt_version != -1 &&
3007               i_table_id == 0x70 )  /* TDT */
3008     {
3009          msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
3010                  i_table_id, i_table_id, i_extension, i_extension );
3011          dvbpsi_AttachTOT( h, i_table_id, i_extension,
3012                            (dvbpsi_tot_callback)TDTCallBack, p_demux);
3013     }
3014 }
3015
3016 /*****************************************************************************
3017  * PMT callback and helpers
3018  *****************************************************************************/
3019 static dvbpsi_descriptor_t *PMTEsFindDescriptor( const dvbpsi_pmt_es_t *p_es,
3020                                                  int i_tag )
3021 {
3022     dvbpsi_descriptor_t *p_dr = p_es->p_first_descriptor;;
3023     while( p_dr && ( p_dr->i_tag != i_tag ) )
3024         p_dr = p_dr->p_next;
3025     return p_dr;
3026 }
3027 static bool PMTEsHasRegistration( demux_t *p_demux,
3028                                   const dvbpsi_pmt_es_t *p_es,
3029                                   const char *psz_tag )
3030 {
3031     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x05 );
3032     if( !p_dr )
3033         return false;
3034
3035     if( p_dr->i_length < 4 )
3036     {
3037         msg_Warn( p_demux, "invalid Registration Descriptor" );
3038         return false;
3039     }
3040
3041     assert( strlen(psz_tag) == 4 );
3042     return !memcmp( p_dr->p_data, psz_tag, 4 );
3043 }
3044 static void PMTSetupEsISO14496( demux_t *p_demux, ts_pid_t *pid,
3045                                 const ts_prg_psi_t *prg, const dvbpsi_pmt_es_t *p_es )
3046 {
3047     es_format_t *p_fmt = &pid->es->fmt;
3048
3049     /* MPEG-4 stream: search SL_DESCRIPTOR */
3050     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x1f );
3051
3052     if( p_dr && p_dr->i_length == 2 )
3053     {
3054         const int i_es_id = ( p_dr->p_data[0] << 8 ) | p_dr->p_data[1];
3055
3056         msg_Warn( p_demux, "found SL_descriptor es_id=%d", i_es_id );
3057
3058         pid->es->p_mpeg4desc = NULL;
3059
3060         for( int i = 0; i < 255; i++ )
3061         {
3062             iod_descriptor_t *iod = prg->iod;
3063
3064             if( iod->es_descr[i].b_ok && iod->es_descr[i].i_es_id == i_es_id )
3065             {
3066                 pid->es->p_mpeg4desc = &iod->es_descr[i];
3067                 break;
3068             }
3069         }
3070     }
3071     if( !pid->es->p_mpeg4desc )
3072     {
3073         msg_Err( p_demux, "MPEG-4 descriptor not found" );
3074         return;
3075     }
3076
3077     const decoder_config_descriptor_t *dcd = &pid->es->p_mpeg4desc->dec_descr;
3078     if( dcd->i_streamType == 0x04 )    /* VisualStream */
3079     {
3080         p_fmt->i_cat = VIDEO_ES;
3081         switch( dcd->i_objectTypeIndication )
3082         {
3083         case 0x0B: /* mpeg4 sub */
3084             p_fmt->i_cat = SPU_ES;
3085             p_fmt->i_codec = VLC_CODEC_SUBT;
3086             break;
3087
3088         case 0x20: /* mpeg4 */
3089             p_fmt->i_codec = VLC_CODEC_MP4V;
3090             break;
3091         case 0x21: /* h264 */
3092             p_fmt->i_codec = VLC_CODEC_H264;
3093             break;
3094         case 0x60:
3095         case 0x61:
3096         case 0x62:
3097         case 0x63:
3098         case 0x64:
3099         case 0x65: /* mpeg2 */
3100             p_fmt->i_codec = VLC_CODEC_MPGV;
3101             break;
3102         case 0x6a: /* mpeg1 */
3103             p_fmt->i_codec = VLC_CODEC_MPGV;
3104             break;
3105         case 0x6c: /* mpeg1 */
3106             p_fmt->i_codec = VLC_CODEC_JPEG;
3107             break;
3108         default:
3109             p_fmt->i_cat = UNKNOWN_ES;
3110             break;
3111         }
3112     }
3113     else if( dcd->i_streamType == 0x05 )    /* AudioStream */
3114     {
3115         p_fmt->i_cat = AUDIO_ES;
3116         switch( dcd->i_objectTypeIndication )
3117         {
3118         case 0x40: /* mpeg4 */
3119             p_fmt->i_codec = VLC_CODEC_MP4A;
3120             break;
3121         case 0x66:
3122         case 0x67:
3123         case 0x68: /* mpeg2 aac */
3124             p_fmt->i_codec = VLC_CODEC_MP4A;
3125             break;
3126         case 0x69: /* mpeg2 */
3127             p_fmt->i_codec = VLC_CODEC_MPGA;
3128             break;
3129         case 0x6b: /* mpeg1 */
3130             p_fmt->i_codec = VLC_CODEC_MPGA;
3131             break;
3132         default:
3133             p_fmt->i_cat = UNKNOWN_ES;
3134             break;
3135         }
3136     }
3137     else
3138     {
3139         p_fmt->i_cat = UNKNOWN_ES;
3140     }
3141
3142     if( p_fmt->i_cat != UNKNOWN_ES )
3143     {
3144         p_fmt->i_extra = dcd->i_extra;
3145         if( p_fmt->i_extra > 0 )
3146         {
3147             p_fmt->p_extra = malloc( p_fmt->i_extra );
3148             if( p_fmt->p_extra )
3149                 memcpy( p_fmt->p_extra, dcd->p_extra, p_fmt->i_extra );
3150             else
3151                 p_fmt->i_extra = 0;
3152         }
3153     }
3154 }
3155
3156 typedef struct
3157 {
3158     int  i_type;
3159     int  i_magazine;
3160     int  i_page;
3161     char p_iso639[3];
3162 } ts_teletext_page_t;
3163
3164 static void PMTSetupEsTeletext( demux_t *p_demux, ts_pid_t *pid,
3165                                 const dvbpsi_pmt_es_t *p_es )
3166 {
3167     es_format_t *p_fmt = &pid->es->fmt;
3168
3169     ts_teletext_page_t p_page[2 * 64 + 20];
3170     unsigned i_page = 0;
3171
3172     /* Gather pages information */
3173 #if defined _DVBPSI_DR_56_H_ && \
3174     defined DVBPSI_VERSION && DVBPSI_VERSION_INT > ((0<<16)+(1<<8)+5)
3175     for( unsigned i_tag_idx = 0; i_tag_idx < 2; i_tag_idx++ )
3176     {
3177         dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, i_tag_idx == 0 ? 0x46 : 0x56 );
3178         if( !p_dr )
3179             continue;
3180
3181         dvbpsi_teletext_dr_t *p_sub = dvbpsi_DecodeTeletextDr( p_dr );
3182         if( !p_sub )
3183             continue;
3184
3185         for( int i = 0; i < p_sub->i_pages_number; i++ )
3186         {
3187             const dvbpsi_teletextpage_t *p_src = &p_sub->p_pages[i];
3188
3189             if( p_src->i_teletext_type >= 0x06 )
3190                 continue;
3191
3192             assert( i_page < sizeof(p_page)/sizeof(*p_page) );
3193
3194             ts_teletext_page_t *p_dst = &p_page[i_page++];
3195
3196             p_dst->i_type = p_src->i_teletext_type;
3197             p_dst->i_magazine = p_src->i_teletext_magazine_number
3198                 ? p_src->i_teletext_magazine_number : 8;
3199             p_dst->i_page = p_src->i_teletext_page_number;
3200             memcpy( p_dst->p_iso639, p_src->i_iso6392_language_code, 3 );
3201         }
3202     }
3203 #endif
3204
3205     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x59 );
3206     if( p_dr )
3207     {
3208         dvbpsi_subtitling_dr_t *p_sub = dvbpsi_DecodeSubtitlingDr( p_dr );
3209         for( int i = 0; p_sub && i < p_sub->i_subtitles_number; i++ )
3210         {
3211             dvbpsi_subtitle_t *p_src = &p_sub->p_subtitle[i];
3212
3213             if( p_src->i_subtitling_type < 0x01 || p_src->i_subtitling_type > 0x03 )
3214                 continue;
3215
3216             assert( i_page < sizeof(p_page)/sizeof(*p_page) );
3217
3218             ts_teletext_page_t *p_dst = &p_page[i_page++];
3219
3220             switch( p_src->i_subtitling_type )
3221             {
3222             case 0x01:
3223                 p_dst->i_type = 0x02;
3224                 break;
3225             default:
3226                 p_dst->i_type = 0x03;
3227                 break;
3228             }
3229             /* FIXME check if it is the right split */
3230             p_dst->i_magazine = (p_src->i_composition_page_id >> 8)
3231                 ? (p_src->i_composition_page_id >> 8) : 8;
3232             p_dst->i_page = p_src->i_composition_page_id & 0xff;
3233             memcpy( p_dst->p_iso639, p_src->i_iso6392_language_code, 3 );
3234         }
3235     }
3236
3237     /* */
3238     es_format_Init( p_fmt, SPU_ES, VLC_CODEC_TELETEXT );
3239
3240     if( !p_demux->p_sys->b_split_es || i_page <= 0 )
3241     {
3242         p_fmt->subs.teletext.i_magazine = -1;
3243         p_fmt->subs.teletext.i_page = 0;
3244         p_fmt->psz_description = strdup( vlc_gettext(ppsz_teletext_type[1]) );
3245
3246         dvbpsi_descriptor_t *p_dr;
3247         p_dr = PMTEsFindDescriptor( p_es, 0x46 );
3248         if( !p_dr )
3249             p_dr = PMTEsFindDescriptor( p_es, 0x56 );
3250
3251         if( !p_demux->p_sys->b_split_es && p_dr && p_dr->i_length > 0 )
3252         {
3253             /* Descriptor pass-through */
3254             p_fmt->p_extra = malloc( p_dr->i_length );
3255             if( p_fmt->p_extra )
3256             {
3257                 p_fmt->i_extra = p_dr->i_length;
3258                 memcpy( p_fmt->p_extra, p_dr->p_data, p_dr->i_length );
3259             }
3260         }
3261     }
3262     else
3263     {
3264         for( unsigned i = 0; i < i_page; i++ )
3265         {
3266             ts_es_t *p_es;
3267
3268             /* */
3269             if( i == 0 )
3270             {
3271                 p_es = pid->es;
3272             }
3273             else
3274             {
3275                 p_es = malloc( sizeof(*p_es) );
3276                 if( !p_es )
3277                     break;
3278
3279                 es_format_Copy( &p_es->fmt, &pid->es->fmt );
3280                 free( p_es->fmt.psz_language );
3281                 free( p_es->fmt.psz_description );
3282                 p_es->fmt.psz_language = NULL;
3283                 p_es->fmt.psz_description = NULL;
3284
3285                 p_es->id      = NULL;
3286                 p_es->p_data  = NULL;
3287                 p_es->i_data_size = 0;
3288                 p_es->i_data_gathered = 0;
3289                 p_es->pp_last = &p_es->p_data;
3290                 p_es->data_type = TS_ES_DATA_PES;
3291                 p_es->p_mpeg4desc = NULL;
3292
3293                 TAB_APPEND( pid->i_extra_es, pid->extra_es, p_es );
3294             }
3295
3296             /* */
3297             const ts_teletext_page_t *p = &p_page[i];
3298             p_es->fmt.i_priority = (p->i_type == 0x02 || p->i_type == 0x05) ? 0 : -1;
3299             p_es->fmt.psz_language = strndup( p->p_iso639, 3 );
3300             p_es->fmt.psz_description = strdup(vlc_gettext(ppsz_teletext_type[p->i_type]));
3301             p_es->fmt.subs.teletext.i_magazine = p->i_magazine;
3302             p_es->fmt.subs.teletext.i_page = p->i_page;
3303
3304             msg_Dbg( p_demux,
3305                          "    * ttxt type=%s lan=%s page=%d%02x",
3306                          p_es->fmt.psz_description,
3307                          p_es->fmt.psz_language,
3308                          p->i_magazine, p->i_page );
3309         }
3310     }
3311 }
3312 static void PMTSetupEsDvbSubtitle( demux_t *p_demux, ts_pid_t *pid,
3313                                    const dvbpsi_pmt_es_t *p_es )
3314 {
3315     es_format_t *p_fmt = &pid->es->fmt;
3316
3317     es_format_Init( p_fmt, SPU_ES, VLC_CODEC_DVBS );
3318
3319     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x59 );
3320     int i_page = 0;
3321     dvbpsi_subtitling_dr_t *p_sub = dvbpsi_DecodeSubtitlingDr( p_dr );
3322     for( int i = 0; p_sub && i < p_sub->i_subtitles_number; i++ )
3323     {
3324         const int i_type = p_sub->p_subtitle[i].i_subtitling_type;
3325         if( ( i_type >= 0x10 && i_type <= 0x14 ) ||
3326             ( i_type >= 0x20 && i_type <= 0x24 ) )
3327             i_page++;
3328     }
3329
3330     if( !p_demux->p_sys->b_split_es  || i_page <= 0 )
3331     {
3332         p_fmt->subs.dvb.i_id = -1;
3333         p_fmt->psz_description = strdup( _("DVB subtitles") );
3334
3335         if( !p_demux->p_sys->b_split_es && p_dr && p_dr->i_length > 0 )
3336         {
3337             /* Descriptor pass-through */
3338             p_fmt->p_extra = malloc( p_dr->i_length );
3339             if( p_fmt->p_extra )
3340             {
3341                 p_fmt->i_extra = p_dr->i_length;
3342                 memcpy( p_fmt->p_extra, p_dr->p_data, p_dr->i_length );
3343             }
3344         }
3345     }
3346     else
3347     {
3348         for( int i = 0; i < p_sub->i_subtitles_number; i++ )
3349         {
3350             ts_es_t *p_es;
3351
3352             /* */
3353             if( i == 0 )
3354             {
3355                 p_es = pid->es;
3356             }
3357             else
3358             {
3359                 p_es = malloc( sizeof(*p_es) );
3360                 if( !p_es )
3361                     break;
3362
3363                 es_format_Copy( &p_es->fmt, &pid->es->fmt );
3364                 free( p_es->fmt.psz_language );
3365                 free( p_es->fmt.psz_description );
3366                 p_es->fmt.psz_language = NULL;
3367                 p_es->fmt.psz_description = NULL;
3368
3369                 p_es->id      = NULL;
3370                 p_es->p_data   = NULL;
3371                 p_es->i_data_size = 0;
3372                 p_es->i_data_gathered = 0;
3373                 p_es->pp_last = &p_es->p_data;
3374                 p_es->data_type = TS_ES_DATA_PES;
3375                 p_es->p_mpeg4desc = NULL;
3376
3377                 TAB_APPEND( pid->i_extra_es, pid->extra_es, p_es );
3378             }
3379
3380             /* */
3381             const dvbpsi_subtitle_t *p = &p_sub->p_subtitle[i];
3382             p_es->fmt.psz_language = strndup( (char *)p->i_iso6392_language_code, 3 );
3383             switch( p->i_subtitling_type )
3384             {
3385             case 0x10: /* unspec. */
3386             case 0x11: /* 4:3 */
3387             case 0x12: /* 16:9 */
3388             case 0x13: /* 2.21:1 */
3389             case 0x14: /* HD monitor */
3390                 p_es->fmt.psz_description = strdup( _("DVB subtitles") );
3391                 break;
3392             case 0x20: /* Hearing impaired unspec. */
3393             case 0x21: /* h.i. 4:3 */
3394             case 0x22: /* h.i. 16:9 */
3395             case 0x23: /* h.i. 2.21:1 */
3396             case 0x24: /* h.i. HD monitor */
3397                 p_es->fmt.psz_description = strdup( _("DVB subtitles: hearing impaired") );
3398                 break;
3399             default:
3400                 break;
3401             }
3402
3403             /* Hack, FIXME */
3404             p_es->fmt.subs.dvb.i_id = ( p->i_composition_page_id <<  0 ) |
3405                                       ( p->i_ancillary_page_id   << 16 );
3406         }
3407     }
3408 }
3409 static void PMTSetupEs0x06( demux_t *p_demux, ts_pid_t *pid,
3410                             const dvbpsi_pmt_es_t *p_es )
3411 {
3412     es_format_t *p_fmt = &pid->es->fmt;
3413
3414     if( PMTEsHasRegistration( p_demux, p_es, "AC-3" ) ||
3415         PMTEsFindDescriptor( p_es, 0x6a ) ||
3416         PMTEsFindDescriptor( p_es, 0x81 ) )
3417     {
3418         p_fmt->i_cat = AUDIO_ES;
3419         p_fmt->i_codec = VLC_CODEC_A52;
3420     }
3421     else if( PMTEsFindDescriptor( p_es, 0x7a ) )
3422     {
3423         /* DVB with stream_type 0x06 (ETS EN 300 468) */
3424         p_fmt->i_cat = AUDIO_ES;
3425         p_fmt->i_codec = VLC_CODEC_EAC3;
3426     }
3427     else if( PMTEsHasRegistration( p_demux, p_es, "DTS1" ) ||
3428              PMTEsHasRegistration( p_demux, p_es, "DTS2" ) ||
3429              PMTEsHasRegistration( p_demux, p_es, "DTS3" ) ||
3430              PMTEsFindDescriptor( p_es, 0x73 ) )
3431     {
3432         /*registration descriptor(ETSI TS 101 154 Annex F)*/
3433         p_fmt->i_cat = AUDIO_ES;
3434         p_fmt->i_codec = VLC_CODEC_DTS;
3435     }
3436     else if( PMTEsHasRegistration( p_demux, p_es, "BSSD" ) )
3437     {
3438         p_fmt->i_cat = AUDIO_ES;
3439         p_fmt->b_packetized = true;
3440         p_fmt->i_codec = VLC_CODEC_302M;
3441     }
3442     else
3443     {
3444         /* Subtitle/Teletext/VBI fallbacks */
3445         dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x59 );
3446
3447         dvbpsi_subtitling_dr_t *p_sub;
3448         if( p_dr && ( p_sub = dvbpsi_DecodeSubtitlingDr( p_dr ) ) )
3449         {
3450             for( int i = 0; i < p_sub->i_subtitles_number; i++ )
3451             {
3452                 if( p_fmt->i_cat != UNKNOWN_ES )
3453                     break;
3454
3455                 switch( p_sub->p_subtitle[i].i_subtitling_type )
3456                 {
3457                 case 0x01: /* EBU Teletext subtitles */
3458                 case 0x02: /* Associated EBU Teletext */
3459                 case 0x03: /* VBI data */
3460                     PMTSetupEsTeletext( p_demux, pid, p_es );
3461                     break;
3462                 case 0x10: /* DVB Subtitle (normal) with no monitor AR critical */
3463                 case 0x11: /*                 ...   on 4:3 AR monitor */
3464                 case 0x12: /*                 ...   on 16:9 AR monitor */
3465                 case 0x13: /*                 ...   on 2.21:1 AR monitor */
3466                 case 0x14: /*                 ...   for display on a high definition monitor */
3467                 case 0x20: /* DVB Subtitle (impaired) with no monitor AR critical */
3468                 case 0x21: /*                 ...   on 4:3 AR monitor */
3469                 case 0x22: /*                 ...   on 16:9 AR monitor */
3470                 case 0x23: /*                 ...   on 2.21:1 AR monitor */
3471                 case 0x24: /*                 ...   for display on a high definition monitor */
3472                     PMTSetupEsDvbSubtitle( p_demux, pid, p_es );
3473                     break;
3474                 default:
3475                     msg_Err( p_demux, "Unrecognized DVB subtitle type (0x%x)",
3476                              p_sub->p_subtitle[i].i_subtitling_type );
3477                     break;
3478                 }
3479             }
3480         }
3481
3482         if( p_fmt->i_cat == UNKNOWN_ES &&
3483             ( PMTEsFindDescriptor( p_es, 0x45 ) ||  /* VBI Data descriptor */
3484               PMTEsFindDescriptor( p_es, 0x46 ) ||  /* VBI Teletext descriptor */
3485               PMTEsFindDescriptor( p_es, 0x56 ) ) ) /* EBU Teletext descriptor */
3486         {
3487             /* Teletext/VBI */
3488             PMTSetupEsTeletext( p_demux, pid, p_es );
3489         }
3490     }
3491
3492     /* FIXME is it useful ? */
3493     if( PMTEsFindDescriptor( p_es, 0x52 ) )
3494     {
3495         dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x52 );
3496         dvbpsi_stream_identifier_dr_t *p_si = dvbpsi_DecodeStreamIdentifierDr( p_dr );
3497
3498         msg_Dbg( p_demux, "    * Stream Component Identifier: %d", p_si->i_component_tag );
3499     }
3500 }
3501
3502 static void PMTSetupEs0xEA( demux_t *p_demux, ts_pid_t *pid,
3503                            const dvbpsi_pmt_es_t *p_es )
3504 {
3505     /* Registration Descriptor */
3506     if( !PMTEsHasRegistration( p_demux, p_es, "VC-1" ) )
3507     {
3508         msg_Err( p_demux, "Registration descriptor not found or invalid" );
3509         return;
3510     }
3511
3512     es_format_t *p_fmt = &pid->es->fmt;
3513
3514     /* registration descriptor for VC-1 (SMPTE rp227) */
3515     p_fmt->i_cat = VIDEO_ES;
3516     p_fmt->i_codec = VLC_CODEC_VC1;
3517
3518     /* XXX With Simple and Main profile the SEQUENCE
3519      * header is modified: video width and height are
3520      * inserted just after the start code as 2 int16_t
3521      * The packetizer will take care of that. */
3522 }
3523
3524 static void PMTSetupEs0xD1( demux_t *p_demux, ts_pid_t *pid,
3525                            const dvbpsi_pmt_es_t *p_es )
3526 {
3527     /* Registration Descriptor */
3528     if( !PMTEsHasRegistration( p_demux, p_es, "drac" ) )
3529     {
3530         msg_Err( p_demux, "Registration descriptor not found or invalid" );
3531         return;
3532     }
3533
3534     es_format_t *p_fmt = &pid->es->fmt;
3535
3536     /* registration descriptor for Dirac
3537      * (backwards compatable with VC-2 (SMPTE Sxxxx:2008)) */
3538     p_fmt->i_cat = VIDEO_ES;
3539     p_fmt->i_codec = VLC_CODEC_DIRAC;
3540 }
3541
3542 static void PMTSetupEs0xA0( demux_t *p_demux, ts_pid_t *pid,
3543                            const dvbpsi_pmt_es_t *p_es )
3544 {
3545     /* MSCODEC sent by vlc */
3546     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0xa0 );
3547     if( !p_dr || p_dr->i_length < 10 )
3548     {
3549         msg_Warn( p_demux,
3550                   "private MSCODEC (vlc) without bih private descriptor" );
3551         return;
3552     }
3553
3554     es_format_t *p_fmt = &pid->es->fmt;
3555     p_fmt->i_cat = VIDEO_ES;
3556     p_fmt->i_codec = VLC_FOURCC( p_dr->p_data[0], p_dr->p_data[1],
3557                                  p_dr->p_data[2], p_dr->p_data[3] );
3558     p_fmt->video.i_width = GetWBE( &p_dr->p_data[4] );
3559     p_fmt->video.i_height = GetWBE( &p_dr->p_data[6] );
3560     p_fmt->i_extra = GetWBE( &p_dr->p_data[8] );
3561
3562     if( p_fmt->i_extra > 0 )
3563     {
3564         p_fmt->p_extra = malloc( p_fmt->i_extra );
3565         if( p_fmt->p_extra )
3566             memcpy( p_fmt->p_extra, &p_dr->p_data[10],
3567                     __MIN( p_fmt->i_extra, p_dr->i_length - 10 ) );
3568         else
3569             p_fmt->i_extra = 0;
3570     }
3571     /* For such stream we will gather them ourself and don't launch a
3572      * packetizer.
3573      * Yes it's ugly but it's the only way to have DIV3 working */
3574     p_fmt->b_packetized = true;
3575 }
3576
3577 static void PMTSetupEsHDMV( ts_pid_t *pid, const dvbpsi_pmt_es_t *p_es )
3578 {
3579     es_format_t *p_fmt = &pid->es->fmt;
3580
3581     /* Blu-Ray mapping */
3582     switch( p_es->i_type )
3583     {
3584     case 0x80:
3585         p_fmt->i_cat = AUDIO_ES;
3586         p_fmt->i_codec = VLC_CODEC_BD_LPCM;
3587         break;
3588     case 0x82:
3589     case 0x85: /* DTS-HD High resolution audio */
3590     case 0x86: /* DTS-HD Master audio */
3591     case 0xA2: /* Secondary DTS audio */
3592         p_fmt->i_cat = AUDIO_ES;
3593         p_fmt->i_codec = VLC_CODEC_DTS;
3594         break;
3595
3596     case 0x83: /* TrueHD AC3 */
3597         p_fmt->i_cat = AUDIO_ES;
3598         p_fmt->i_codec = VLC_CODEC_TRUEHD;
3599         break;
3600
3601     case 0x84: /* E-AC3 */
3602     case 0xA1: /* Secondary E-AC3 */
3603         p_fmt->i_cat = AUDIO_ES;
3604         p_fmt->i_codec = VLC_CODEC_EAC3;
3605         break;
3606     case 0x90: /* Presentation graphics */
3607         p_fmt->i_cat = SPU_ES;
3608         p_fmt->i_codec = VLC_CODEC_BD_PG;
3609         break;
3610     case 0x91: /* Interactive graphics */
3611     case 0x92: /* Subtitle */
3612     default:
3613         break;
3614     }
3615 }
3616
3617 static void PMTSetupEsRegistration( demux_t *p_demux, ts_pid_t *pid,
3618                                     const dvbpsi_pmt_es_t *p_es )
3619 {
3620     static const struct
3621     {
3622         char         psz_tag[5];
3623         int          i_cat;
3624         vlc_fourcc_t i_codec;
3625     } p_regs[] = {
3626         { "AC-3", AUDIO_ES, VLC_CODEC_A52   },
3627         { "DTS1", AUDIO_ES, VLC_CODEC_DTS   },
3628         { "DTS2", AUDIO_ES, VLC_CODEC_DTS   },
3629         { "DTS3", AUDIO_ES, VLC_CODEC_DTS   },
3630         { "BSSD", AUDIO_ES, VLC_CODEC_302M  },
3631         { "VC-1", VIDEO_ES, VLC_CODEC_VC1   },
3632         { "drac", VIDEO_ES, VLC_CODEC_DIRAC },
3633         { "", UNKNOWN_ES, 0 }
3634     };
3635     es_format_t *p_fmt = &pid->es->fmt;
3636
3637     for( int i = 0; p_regs[i].i_cat != UNKNOWN_ES; i++ )
3638     {
3639         if( PMTEsHasRegistration( p_demux, p_es, p_regs[i].psz_tag ) )
3640         {
3641             p_fmt->i_cat   = p_regs[i].i_cat;
3642             p_fmt->i_codec = p_regs[i].i_codec;
3643             if (p_es->i_type == 0x87)
3644                 p_fmt->i_codec = VLC_CODEC_EAC3;
3645             return;
3646         }
3647     }
3648 }
3649
3650 static char *GetAudioTypeDesc(demux_t *p_demux, int type)
3651 {
3652     static const char *audio_type[] = {
3653         NULL,
3654         N_("clean effects"),
3655         N_("hearing impaired"),
3656         N_("visual impaired commentary"),
3657     };
3658
3659     if (type < 0 || type > 3)
3660         msg_Dbg( p_demux, "unknown audio type: %d", type);
3661     else if (type > 0)
3662         return strdup(audio_type[type]);
3663
3664     return NULL;
3665 }
3666 static void PMTParseEsIso639( demux_t *p_demux, ts_pid_t *pid,
3667                               const dvbpsi_pmt_es_t *p_es )
3668 {
3669     /* get language descriptor */
3670     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x0a );
3671
3672     if( !p_dr )
3673         return;
3674
3675     dvbpsi_iso639_dr_t *p_decoded = dvbpsi_DecodeISO639Dr( p_dr );
3676     if( !p_decoded )
3677     {
3678         msg_Err( p_demux, "Failed to decode a ISO 639 descriptor" );
3679         return;
3680     }
3681
3682 #if defined(DR_0A_API_VER) && (DR_0A_API_VER >= 2)
3683     pid->es->fmt.psz_language = malloc( 4 );
3684     if( pid->es->fmt.psz_language )
3685     {
3686         memcpy( pid->es->fmt.psz_language, p_decoded->code[0].iso_639_code, 3 );
3687         pid->es->fmt.psz_language[3] = 0;
3688         msg_Dbg( p_demux, "found language: %s", pid->es->fmt.psz_language);
3689     }
3690     int type = p_decoded->code[0].i_audio_type;
3691     pid->es->fmt.psz_description = GetAudioTypeDesc(p_demux, type);
3692     if (type == 0)
3693         pid->es->fmt.i_priority = 1; // prioritize normal audio tracks
3694
3695     pid->es->fmt.i_extra_languages = p_decoded->i_code_count-1;
3696     if( pid->es->fmt.i_extra_languages > 0 )
3697         pid->es->fmt.p_extra_languages =
3698             malloc( sizeof(*pid->es->fmt.p_extra_languages) *
3699                     pid->es->fmt.i_extra_languages );
3700     if( pid->es->fmt.p_extra_languages )
3701     {
3702         for( int i = 0; i < pid->es->fmt.i_extra_languages; i++ )
3703         {
3704             pid->es->fmt.p_extra_languages[i].psz_language = malloc(4);
3705             if( pid->es->fmt.p_extra_languages[i].psz_language )
3706             {
3707                 memcpy( pid->es->fmt.p_extra_languages[i].psz_language,
3708                     p_decoded->code[i+1].iso_639_code, 3 );
3709                 pid->es->fmt.p_extra_languages[i].psz_language[3] = '\0';
3710             }
3711             int type = p_decoded->code[i].i_audio_type;
3712             pid->es->fmt.psz_description = GetAudioTypeDesc(p_demux, type);
3713         }
3714     }
3715 #else
3716     pid->es->fmt.psz_language = malloc( 4 );
3717     if( pid->es->fmt.psz_language )
3718     {
3719         memcpy( pid->es->fmt.psz_language,
3720                 p_decoded->i_iso_639_code, 3 );
3721         pid->es->fmt.psz_language[3] = 0;
3722     }
3723 #endif
3724 }
3725
3726 static void PMTCallBack( void *data, dvbpsi_pmt_t *p_pmt )
3727 {
3728     demux_t      *p_demux = data;
3729     demux_sys_t  *p_sys = p_demux->p_sys;
3730
3731     ts_pid_t     *pmt = NULL;
3732     ts_prg_psi_t *prg;
3733
3734     msg_Dbg( p_demux, "PMTCallBack called" );
3735
3736     /* First find this PMT declared in PAT */
3737     for( int i = 0; !pmt && i < p_sys->i_pmt; i++ )
3738         for( int i_prg = 0; !pmt && i_prg < p_sys->pmt[i]->psi->i_prg; i_prg++ )
3739         {
3740             const int i_pmt_number = p_sys->pmt[i]->psi->prg[i_prg]->i_number;
3741             if( i_pmt_number != TS_USER_PMT_NUMBER &&
3742                 i_pmt_number == p_pmt->i_program_number )
3743             {
3744                 pmt = p_sys->pmt[i];
3745                 prg = p_sys->pmt[i]->psi->prg[i_prg];
3746             }
3747         }
3748
3749     if( pmt == NULL )
3750     {
3751         msg_Warn( p_demux, "unreferenced program (broken stream)" );
3752         dvbpsi_DeletePMT(p_pmt);
3753         return;
3754     }
3755
3756
3757     if( prg->i_version != -1 &&
3758         ( !p_pmt->b_current_next || prg->i_version == p_pmt->i_version ) )
3759     {
3760         dvbpsi_DeletePMT( p_pmt );
3761         return;
3762     }
3763
3764     ts_pid_t **pp_clean = NULL;
3765     int      i_clean = 0;
3766     /* Clean this program (remove all es) */
3767     for( int i = 0; i < 8192; i++ )
3768     {
3769         ts_pid_t *pid = &p_sys->pid[i];
3770
3771         if( pid->b_valid && pid->p_owner == pmt->psi &&
3772             pid->i_owner_number == prg->i_number && pid->psi == NULL )
3773         {
3774             TAB_APPEND( i_clean, pp_clean, pid );
3775         }
3776     }
3777     if( prg->iod )
3778     {
3779         IODFree( prg->iod );
3780         prg->iod = NULL;
3781     }
3782
3783     msg_Dbg( p_demux, "new PMT program number=%d version=%d pid_pcr=%d",
3784              p_pmt->i_program_number, p_pmt->i_version, p_pmt->i_pcr_pid );
3785     prg->i_pid_pcr = p_pmt->i_pcr_pid;
3786     prg->i_version = p_pmt->i_version;
3787
3788     ValidateDVBMeta( p_demux, prg->i_pid_pcr );
3789     if( ProgramIsSelected( p_demux, prg->i_number ) )
3790         SetPIDFilter( p_demux, prg->i_pid_pcr, true ); /* Set demux filter */
3791
3792     /* Parse descriptor */
3793     bool b_hdmv = false;
3794     dvbpsi_descriptor_t  *p_dr;
3795     for( p_dr = p_pmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
3796         switch(p_dr->i_tag)
3797         {
3798         case 0x1d: /* We have found an IOD descriptor */
3799             msg_Dbg( p_demux, " * descriptor : IOD (0x1d)" );
3800             prg->iod = IODNew( p_dr->i_length, p_dr->p_data );
3801             break;
3802
3803         case 0x9:
3804             msg_Dbg( p_demux, " * descriptor : CA (0x9) SysID 0x%x",
3805                     (p_dr->p_data[0] << 8) | p_dr->p_data[1] );
3806             break;
3807
3808         case 0x5: /* Registration Descriptor */
3809             if( p_dr->i_length != 4 )
3810             {
3811                 msg_Warn( p_demux, "invalid Registration Descriptor" );
3812             }
3813             else
3814             {
3815                 msg_Dbg( p_demux, " * descriptor : registration %4.4s", p_dr->p_data );
3816                 if( !memcmp( p_dr->p_data, "HDMV", 4 ) )
3817                     b_hdmv = true; /* Blu-Ray */
3818             }
3819             break;
3820
3821         default:
3822             msg_Dbg( p_demux, " * descriptor : unknown (0x%x)", p_dr->i_tag );
3823         }
3824
3825     dvbpsi_pmt_es_t      *p_es;
3826     for( p_es = p_pmt->p_first_es; p_es != NULL; p_es = p_es->p_next )
3827     {
3828         ts_pid_t tmp_pid, *old_pid = 0, *pid = &tmp_pid;
3829
3830         /* Find out if the PID was already declared */
3831         for( int i = 0; i < i_clean; i++ )
3832         {
3833             if( pp_clean[i] == &p_sys->pid[p_es->i_pid] )
3834             {
3835                 old_pid = pp_clean[i];
3836                 break;
3837             }
3838         }
3839         ValidateDVBMeta( p_demux, p_es->i_pid );
3840
3841         if( !old_pid && p_sys->pid[p_es->i_pid].b_valid )
3842         {
3843             msg_Warn( p_demux, "pmt error: pid=%d already defined",
3844                       p_es->i_pid );
3845             continue;
3846         }
3847
3848         for( p_dr = p_es->p_first_descriptor; p_dr != NULL;
3849              p_dr = p_dr->p_next )
3850         {
3851             msg_Dbg( p_demux, "  * es pid=%d type=%d dr->i_tag=0x%x",
3852                      p_es->i_pid, p_es->i_type, p_dr->i_tag );
3853         }
3854
3855         PIDInit( pid, false, pmt->psi );
3856         PIDFillFormat( pid->es, p_es->i_type );
3857         pid->i_owner_number = prg->i_number;
3858         pid->i_pid          = p_es->i_pid;
3859         pid->b_seen         = p_sys->pid[p_es->i_pid].b_seen;
3860
3861         if( p_es->i_type == 0x10 || p_es->i_type == 0x11 ||
3862             p_es->i_type == 0x12 || p_es->i_type == 0x0f )
3863         {
3864             PMTSetupEsISO14496( p_demux, pid, prg, p_es );
3865         }
3866         else if( p_es->i_type == 0x06 )
3867         {
3868             PMTSetupEs0x06(  p_demux, pid, p_es );
3869         }
3870         else if( p_es->i_type == 0xEA )
3871         {
3872             PMTSetupEs0xEA( p_demux, pid, p_es );
3873         }
3874         else if( p_es->i_type == 0xd1 )
3875         {
3876             PMTSetupEs0xD1( p_demux, pid, p_es );
3877         }
3878         else if( p_es->i_type == 0xa0 )
3879         {
3880             PMTSetupEs0xA0( p_demux, pid, p_es );
3881         }
3882         else if( b_hdmv )
3883         {
3884             PMTSetupEsHDMV( pid, p_es );
3885         }
3886         else if( p_es->i_type >= 0x80 )
3887         {
3888             PMTSetupEsRegistration( p_demux, pid, p_es );
3889         }
3890
3891         if( pid->es->fmt.i_cat == AUDIO_ES ||
3892             ( pid->es->fmt.i_cat == SPU_ES &&
3893               pid->es->fmt.i_codec != VLC_CODEC_DVBS &&
3894               pid->es->fmt.i_codec != VLC_CODEC_TELETEXT ) )
3895         {
3896             PMTParseEsIso639( p_demux, pid, p_es );
3897         }
3898
3899         pid->es->fmt.i_group = p_pmt->i_program_number;
3900         for( int i = 0; i < pid->i_extra_es; i++ )
3901             pid->extra_es[i]->fmt.i_group = p_pmt->i_program_number;
3902
3903         if( pid->es->fmt.i_cat == UNKNOWN_ES )
3904         {
3905             msg_Dbg( p_demux, "  * es pid=%d type=%d *unknown*",
3906                      p_es->i_pid, p_es->i_type );
3907         }
3908         else if( !p_sys->b_udp_out )
3909         {
3910             msg_Dbg( p_demux, "  * es pid=%d type=%d fcc=%4.4s",
3911                      p_es->i_pid, p_es->i_type, (char*)&pid->es->fmt.i_codec );
3912
3913             if( p_sys->b_es_id_pid ) pid->es->fmt.i_id = p_es->i_pid;
3914
3915             /* Check if we can avoid restarting the ES */
3916             if( old_pid &&
3917                 pid->es->fmt.i_codec == old_pid->es->fmt.i_codec &&
3918                 pid->es->fmt.i_extra == old_pid->es->fmt.i_extra &&
3919                 pid->es->fmt.i_extra == 0 &&
3920                 pid->i_extra_es == old_pid->i_extra_es &&
3921                 ( ( !pid->es->fmt.psz_language &&
3922                     !old_pid->es->fmt.psz_language ) ||
3923                   ( pid->es->fmt.psz_language &&
3924                     old_pid->es->fmt.psz_language &&
3925                     !strcmp( pid->es->fmt.psz_language,
3926                              old_pid->es->fmt.psz_language ) ) ) )
3927             {
3928                 pid->i_cc = old_pid->i_cc;
3929                 ts_es_t *e = pid->es;
3930                 pid->es = old_pid->es;
3931                 old_pid->es = e;
3932                 for( int i = 0; i < pid->i_extra_es; i++ )
3933                 {
3934                     e = pid->extra_es[i];
3935                     pid->extra_es[i] = old_pid->extra_es[i];
3936                     old_pid->extra_es[i] = e;
3937                 }
3938             }
3939             else
3940             {
3941                 pid->es->id = es_out_Add( p_demux->out, &pid->es->fmt );
3942                 for( int i = 0; i < pid->i_extra_es; i++ )
3943                 {
3944                     pid->extra_es[i]->id =
3945                         es_out_Add( p_demux->out, &pid->extra_es[i]->fmt );
3946                 }
3947                 p_sys->i_pmt_es += 1 + pid->i_extra_es;
3948             }
3949         }
3950
3951         /* Add ES to the list */
3952         if( old_pid )
3953         {
3954             PIDClean( p_demux, old_pid );
3955             TAB_REMOVE( i_clean, pp_clean, old_pid );
3956         }
3957         p_sys->pid[p_es->i_pid] = *pid;
3958
3959         p_dr = PMTEsFindDescriptor( p_es, 0x09 );
3960         if( p_dr && p_dr->i_length >= 2 )
3961         {
3962             msg_Dbg( p_demux, "   * descriptor : CA (0x9) SysID 0x%x",
3963                      (p_dr->p_data[0] << 8) | p_dr->p_data[1] );
3964         }
3965
3966         if( ProgramIsSelected( p_demux, prg->i_number ) &&
3967             ( pid->es->id != NULL || p_sys->b_udp_out ) )
3968             SetPIDFilter( p_demux, p_es->i_pid, true ); /* Set demux filter */
3969     }
3970
3971     /* Set CAM descrambling */
3972     if( !ProgramIsSelected( p_demux, prg->i_number )
3973      || stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
3974                         ACCESS_SET_PRIVATE_ID_CA, p_pmt ) != VLC_SUCCESS )
3975         dvbpsi_DeletePMT( p_pmt );
3976
3977     for( int i = 0; i < i_clean; i++ )
3978     {
3979         if( ProgramIsSelected( p_demux, prg->i_number ) )
3980             SetPIDFilter( p_demux, pp_clean[i]->i_pid, false );
3981
3982         PIDClean( p_demux, pp_clean[i] );
3983     }
3984     if( i_clean )
3985         free( pp_clean );
3986 }
3987
3988 static void PATCallBack( void *data, dvbpsi_pat_t *p_pat )
3989 {
3990     demux_t              *p_demux = data;
3991     demux_sys_t          *p_sys = p_demux->p_sys;
3992     dvbpsi_pat_program_t *p_program;
3993     ts_pid_t             *pat = &p_sys->pid[0];
3994
3995     msg_Dbg( p_demux, "PATCallBack called" );
3996
3997     if( ( pat->psi->i_pat_version != -1 &&
3998             ( !p_pat->b_current_next ||
3999               p_pat->i_version == pat->psi->i_pat_version ) ) ||
4000         p_sys->b_user_pmt )
4001     {
4002         dvbpsi_DeletePAT( p_pat );
4003         return;
4004     }
4005
4006     msg_Dbg( p_demux, "new PAT ts_id=%d version=%d current_next=%d",
4007              p_pat->i_ts_id, p_pat->i_version, p_pat->b_current_next );
4008
4009     /* Clean old */
4010     if( p_sys->i_pmt > 0 )
4011     {
4012         int      i_pmt_rm = 0;
4013         ts_pid_t **pmt_rm = NULL;
4014
4015         /* Search pmt to be deleted */
4016         for( int i = 0; i < p_sys->i_pmt; i++ )
4017         {
4018             ts_pid_t *pmt = p_sys->pmt[i];
4019             bool b_keep = false;
4020
4021             for( p_program = p_pat->p_first_program; !b_keep && p_program;
4022                  p_program = p_program->p_next )
4023             {
4024                 if( p_program->i_pid != pmt->i_pid )
4025                     continue;
4026
4027                 for( int i_prg = 0; !b_keep && i_prg < pmt->psi->i_prg; i_prg++ )
4028                     if( p_program->i_number == pmt->psi->prg[i_prg]->i_number )
4029                         b_keep = true;
4030             }
4031
4032             if( b_keep )
4033                 continue;
4034
4035             TAB_APPEND( i_pmt_rm, pmt_rm, pmt );
4036         }
4037
4038         /* Delete all ES attached to thoses PMT */
4039         for( int i = 2; i < 8192; i++ )
4040         {
4041             ts_pid_t *pid = &p_sys->pid[i];
4042
4043             if( !pid->b_valid || pid->psi )
4044                 continue;
4045
4046             for( int j = 0; j < i_pmt_rm && pid->b_valid; j++ )
4047             {
4048                 for( int i_prg = 0; i_prg < pid->p_owner->i_prg; i_prg++ )
4049                 {
4050                     /* We only remove es that aren't defined by extra pmt */
4051                     if( pid->p_owner->prg[i_prg]->i_pid_pmt != pmt_rm[j]->i_pid )
4052                         continue;
4053
4054                     if( pid->es->id )
4055                         SetPIDFilter( p_demux, i, false );
4056
4057                     PIDClean( p_demux, pid );
4058                     break;
4059                 }
4060             }
4061         }
4062
4063         /* Delete PMT pid */
4064         for( int i = 0; i < i_pmt_rm; i++ )
4065         {
4066             ts_pid_t *pid = pmt_rm[i];
4067             SetPIDFilter( p_demux, pid->i_pid, false );
4068
4069             for( int i_prg = 0; i_prg < pid->psi->i_prg; i_prg++ )
4070             {
4071                 const int i_number = pid->psi->prg[i_prg]->i_number;
4072                 es_out_Control( p_demux->out, ES_OUT_DEL_GROUP, i_number );
4073             }
4074
4075             PIDClean( p_demux, &p_sys->pid[pid->i_pid] );
4076             TAB_REMOVE( p_sys->i_pmt, p_sys->pmt, pid );
4077         }
4078
4079         free( pmt_rm );
4080     }
4081
4082     /* now create programs */
4083     for( p_program = p_pat->p_first_program; p_program != NULL;
4084          p_program = p_program->p_next )
4085     {
4086         msg_Dbg( p_demux, "  * number=%d pid=%d", p_program->i_number,
4087                  p_program->i_pid );
4088         if( p_program->i_number == 0 )
4089             continue;
4090
4091         ts_pid_t *pmt = &p_sys->pid[p_program->i_pid];
4092
4093         ValidateDVBMeta( p_demux, p_program->i_pid );
4094
4095         if( pmt->b_valid )
4096         {
4097             bool b_add = true;
4098             for( int i_prg = 0; b_add && i_prg < pmt->psi->i_prg; i_prg++ )
4099                 if( pmt->psi->prg[i_prg]->i_number == p_program->i_number )
4100                     b_add = false;
4101
4102             if( !b_add )
4103                 continue;
4104         }
4105         else
4106         {
4107             TAB_APPEND( p_sys->i_pmt, p_sys->pmt, pmt );
4108         }
4109
4110         PIDInit( pmt, true, pat->psi );
4111         ts_prg_psi_t *prg = pmt->psi->prg[pmt->psi->i_prg-1];
4112         prg->handle = dvbpsi_AttachPMT(p_program->i_number, PMTCallBack, p_demux);
4113         prg->i_number = p_program->i_number;
4114         prg->i_pid_pmt = p_program->i_pid;
4115
4116         /* Now select PID at access level */
4117         if( ProgramIsSelected( p_demux, p_program->i_number ) )
4118         {
4119             if( p_sys->i_current_program == 0 )
4120                 p_sys->i_current_program = p_program->i_number;
4121
4122             if( SetPIDFilter( p_demux, p_program->i_pid, true ) )
4123                 p_sys->b_access_control = false;
4124         }
4125     }
4126     pat->psi->i_pat_version = p_pat->i_version;
4127
4128     dvbpsi_DeletePAT( p_pat );
4129 }