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