1 /*****************************************************************************
2 * ts.c: Transport Stream input module for VLC.
3 *****************************************************************************
4 * Copyright (C) 2004-2005 VLC authors and VideoLAN
7 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8 * Jean-Paul Saman <jpsaman #_at_# m2x.nl>
10 * This program is free software; you can redistribute it and/or modify it
11 * under the terms of the GNU Lesser General Public License as published by
12 * the Free Software Foundation; either version 2.1 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with this program; if not, write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23 *****************************************************************************/
25 /*****************************************************************************
27 *****************************************************************************/
33 #include <vlc_common.h>
34 #include <vlc_plugin.h>
39 #include <vlc_access.h> /* DVB-specific things */
40 #include <vlc_demux.h>
43 #include <vlc_charset.h> /* FromCharset, for EIT */
46 #include "../mux/mpeg/csa.h"
48 /* Include dvbpsi headers */
49 # include <dvbpsi/dvbpsi.h>
50 # include <dvbpsi/demux.h>
51 # include <dvbpsi/descriptor.h>
52 # include <dvbpsi/pat.h>
53 # include <dvbpsi/pmt.h>
54 # include <dvbpsi/sdt.h>
55 # include <dvbpsi/dr.h>
56 # include <dvbpsi/psi.h>
59 # include <dvbpsi/eit.h>
62 # include <dvbpsi/tot.h>
64 #include "../mux/mpeg/dvbpsi_compat.h"
65 #include "../mux/mpeg/streams.h"
66 #include "../mux/mpeg/tsutil.h"
67 #include "../mux/mpeg/tables.h"
69 #include "../codec/opus_header.h"
74 VLC_FORMAT(1, 2) static void ts_debug(const char *format, ...)
79 vfprintf(stderr, format, ap);
87 #include <aribb24/aribb24.h>
88 #include <aribb24/decoder.h>
91 typedef enum arib_modes_e
94 ARIBMODE_DISABLED = 0,
98 /*****************************************************************************
100 *****************************************************************************/
101 static int Open ( vlc_object_t * );
102 static void Close ( vlc_object_t * );
105 * - Rename "extra pmt" to "user pmt"
106 * - Update extra pmt description
107 * pmt_pid[:pmt_number][=pid_description[,pid_description]]
108 * where pid_description could take 3 forms:
109 * 1. pid:pcr (to force the pcr pid)
111 * 3. pid:type=fourcc where type=(video|audio|spu)
113 #define PMT_TEXT N_("Extra PMT")
114 #define PMT_LONGTEXT N_( \
115 "Allows a user to specify an extra pmt (pmt_pid=pid:stream_type[,...])." )
117 #define PID_TEXT N_("Set id of ES to PID")
118 #define PID_LONGTEXT N_("Set the internal ID of each elementary stream" \
119 " handled by VLC to the same value as the PID in" \
120 " the TS stream, instead of 1, 2, 3, etc. Useful to" \
121 " do \'#duplicate{..., select=\"es=<pid>\"}\'.")
123 #define CSA_TEXT N_("CSA Key")
124 #define CSA_LONGTEXT N_("CSA encryption key. This must be a " \
125 "16 char string (8 hexadecimal bytes).")
127 #define CSA2_TEXT N_("Second CSA Key")
128 #define CSA2_LONGTEXT N_("The even CSA encryption key. This must be a " \
129 "16 char string (8 hexadecimal bytes).")
132 #define CPKT_TEXT N_("Packet size in bytes to decrypt")
133 #define CPKT_LONGTEXT N_("Specify the size of the TS packet to decrypt. " \
134 "The decryption routines subtract the TS-header from the value before " \
137 #define SPLIT_ES_TEXT N_("Separate sub-streams")
138 #define SPLIT_ES_LONGTEXT N_( \
139 "Separate teletex/dvbs pages into independent ES. " \
140 "It can be useful to turn off this option when using stream output." )
142 #define SEEK_PERCENT_TEXT N_("Seek based on percent not time")
143 #define SEEK_PERCENT_LONGTEXT N_( \
144 "Seek and position based on a percent byte position, not a PCR generated " \
145 "time position. If seeking doesn't work property, turn on this option." )
147 #define PCR_TEXT N_("Trust in-stream PCR")
148 #define PCR_LONGTEXT N_("Use the stream PCR as a reference.")
150 static const int const arib_mode_list[] =
151 { ARIBMODE_AUTO, ARIBMODE_ENABLED, ARIBMODE_DISABLED };
152 static const char *const arib_mode_list_text[] =
153 { N_("Auto"), N_("Enabled"), N_("Disabled") };
155 #define SUPPORT_ARIB_TEXT N_("ARIB STD-B24 mode")
156 #define SUPPORT_ARIB_LONGTEXT N_( \
157 "Forces ARIB STD-B24 mode for decoding characters." \
158 "This feature affects EPG information and subtitles." )
161 set_description( N_("MPEG Transport Stream demuxer") )
162 set_shortname ( "MPEG-TS" )
163 set_category( CAT_INPUT )
164 set_subcategory( SUBCAT_INPUT_DEMUX )
166 add_string( "ts-extra-pmt", NULL, PMT_TEXT, PMT_LONGTEXT, true )
167 add_bool( "ts-trust-pcr", true, PCR_TEXT, PCR_LONGTEXT, true )
169 add_bool( "ts-es-id-pid", true, PID_TEXT, PID_LONGTEXT, true )
171 add_obsolete_string( "ts-out" ) /* since 2.2.0 */
172 add_obsolete_integer( "ts-out-mtu" ) /* since 2.2.0 */
173 add_string( "ts-csa-ck", NULL, CSA_TEXT, CSA_LONGTEXT, true )
175 add_string( "ts-csa2-ck", NULL, CSA2_TEXT, CSA2_LONGTEXT, true )
177 add_integer( "ts-csa-pkt", 188, CPKT_TEXT, CPKT_LONGTEXT, true )
180 add_bool( "ts-split-es", true, SPLIT_ES_TEXT, SPLIT_ES_LONGTEXT, false )
181 add_bool( "ts-seek-percent", false, SEEK_PERCENT_TEXT, SEEK_PERCENT_LONGTEXT, true )
183 add_integer( "ts-arib", ARIBMODE_AUTO, SUPPORT_ARIB_TEXT, SUPPORT_ARIB_LONGTEXT, false )
184 change_integer_list( arib_mode_list, arib_mode_list_text )
186 add_obsolete_bool( "ts-silent" );
188 set_capability( "demux", 10 )
189 set_callbacks( Open, Close )
193 /*****************************************************************************
195 *****************************************************************************/
196 static const char *const ppsz_teletext_type[] = {
199 N_("Teletext subtitles"),
200 N_("Teletext: additional information"),
201 N_("Teletext: program schedule"),
202 N_("Teletext subtitles: hearing impaired")
205 typedef struct ts_pid_t ts_pid_t;
209 uint8_t i_objectTypeIndication;
210 uint8_t i_streamType;
215 } decoder_config_descriptor_t;
224 decoder_config_descriptor_t dec_descr;
226 } es_mpeg4_descriptor_t;
228 #define ES_DESCRIPTOR_COUNT 255
234 es_mpeg4_descriptor_t es_descr[ES_DESCRIPTOR_COUNT];
243 DECL_ARRAY(ts_pid_t *) programs;
253 /* IOD stuff (mpeg4) */
254 iod_descriptor_t *iod;
256 DECL_ARRAY(ts_pid_t *) e_streams;
261 mtime_t i_first; // seen <> != -1
262 /* broken PCR handling */
265 bool b_disable; /* ignore PCR field, use dts */
277 const es_mpeg4_descriptor_t *p_mpeg4desc;
283 TS_ES_DATA_TABLE_SECTION
289 /* Some private streams encapsulate several ES (eg. DVB subtitles)*/
290 DECL_ARRAY( ts_pes_es_t * ) extra_es;
292 ts_es_data_type_t data_type;
298 block_t * p_prepcr_outqueue;
305 /* for special PAT/SDT case */
306 dvbpsi_t *handle; /* PAT/SDT/EIT */
313 TS_PMT_REGISTRATION_NONE = 0,
314 TS_PMT_REGISTRATION_HDMV
315 } ts_pmt_registration_type_t;
336 #define SEEN(x) ((x)->i_flags & FLAG_SEEN)
337 #define SCRAMBLED(x) ((x).i_flags & FLAG_SCRAMBLED)
344 uint8_t i_cc; /* countinuity counter */
347 /* PSI owner (ie PMT -> PAT, ES -> PMT */
362 vlc_fourcc_t i_fourcc;
374 #define MIN_ES_PID 4 /* Should be 32.. broken muxers */
375 #define MAX_ES_PID 8190
376 #define MIN_PAT_INTERVAL CLOCK_FREQ // DVB is 500ms
378 #define FROM_SCALE(x) (VLC_TS_0 + ((x) * 100 / 9))
379 #define TO_SCALE(x) (((x) - VLC_TS_0) * 9 / 100)
381 #define PID_ALLOC_CHUNK 16
388 vlc_mutex_t csa_lock;
390 /* TS packet size (188, 192, 204) */
391 unsigned i_packet_size;
393 /* Additional TS packet header size (BluRay TS packets have 4-byte header before sync byte) */
394 unsigned i_packet_header_size;
396 /* how many TS packet we read at once */
399 bool b_force_seek_per_percent;
405 arib_instance_t *p_instance;
415 /* all non commons ones, dynamically allocated */
419 /* last recently used */
426 bool b_es_all; /* If we need to return all es/programs */
430 NO_ES, /* for preparse */
434 #define PREPARSING p_sys->es_creation == NO_ES
438 uint16_t i_next_extraid;
447 bool b_access_control;
454 int64_t i_dvb_length;
455 bool b_broken_charset; /* True if broken encoding is used in EPG/SDT */
457 /* Selected programs */
458 DECL_ARRAY( int ) programs; /* List of selected/access-filtered programs */
459 bool b_default_selection; /* True if set by default to first pmt seen (to get data from filtered access) */
463 mtime_t i_first_dts; /* first dts encountered for the stream */
464 int i_timesourcepid; /* which pid we saved the dts from */
465 bool b_pat_deadline; /* set if we haven't seen PAT within MIN_PAT_INTERVAL */
474 static int Demux ( demux_t *p_demux );
475 static int Control( demux_t *p_demux, int i_query, va_list args );
477 static void PIDFillFormat( es_format_t *fmt, int i_stream_type );
479 static bool PIDSetup( demux_t *p_demux, ts_pid_type_t i_type, ts_pid_t *pid, ts_pid_t *p_parent );
480 static void PIDRelease( demux_t *p_demux, ts_pid_t *pid );
482 static void PATCallBack( void*, dvbpsi_pat_t * );
483 static void PMTCallBack( void *data, dvbpsi_pmt_t *p_pmt );
484 static void PSINewTableCallBack( dvbpsi_t *handle, uint8_t i_table_id,
485 uint16_t i_extension, demux_t * );
487 static int ChangeKeyCallback( vlc_object_t *, char const *, vlc_value_t, vlc_value_t, void * );
490 static ts_pat_t *ts_pat_New( demux_t * );
491 static void ts_pat_Del( demux_t *, ts_pat_t * );
492 static ts_pmt_t *ts_pmt_New( demux_t * );
493 static void ts_pmt_Del( demux_t *, ts_pmt_t * );
494 static ts_pes_t *ts_pes_New( demux_t * );
495 static void ts_pes_Del( demux_t *, ts_pes_t * );
496 static ts_psi_t *ts_psi_New( demux_t * );
497 static void ts_psi_Del( demux_t *, ts_psi_t * );
500 static ts_pid_t *PID( demux_sys_t *, uint16_t i_pid );
501 static ts_pmt_t * GetProgramByID( demux_sys_t *, int i_program );
502 static bool ProgramIsSelected( demux_sys_t *, uint16_t i_pgrm );
503 static void UpdatePESFilters( demux_t *p_demux, bool b_all );
504 static inline void FlushESBuffer( ts_pes_t *p_pes );
505 static void UpdateScrambledState( demux_t *p_demux, ts_pid_t *p_pid, bool );
506 static inline int PIDGet( block_t *p )
508 return ( (p->p_buffer[1]&0x1f)<<8 )|p->p_buffer[2];
511 static bool GatherData( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk );
512 static void AddAndCreateES( demux_t *p_demux, ts_pid_t *pid, bool );
513 static void ProgramSetPCR( demux_t *p_demux, ts_pmt_t *p_prg, mtime_t i_pcr );
515 static block_t* ReadTSPacket( demux_t *p_demux );
516 static int ProbeStart( demux_t *p_demux, int i_program );
517 static int ProbeEnd( demux_t *p_demux, int i_program );
518 static int SeekToTime( demux_t *p_demux, ts_pmt_t *, int64_t time );
519 static void ReadyQueuesPostSeek( demux_t *p_demux );
520 static void PCRHandle( demux_t *p_demux, ts_pid_t *, block_t * );
521 static void PCRFixHandle( demux_t *, ts_pmt_t *, block_t * );
522 static int64_t TimeStampWrapAround( ts_pmt_t *, int64_t );
524 static void IODFree( iod_descriptor_t * );
526 #define TS_USER_PMT_NUMBER (0)
527 static int UserPmt( demux_t *p_demux, const char * );
529 static int SetPIDFilter( demux_sys_t *, ts_pid_t *, bool b_selected );
531 #define TS_PACKET_SIZE_188 188
532 #define TS_PACKET_SIZE_192 192
533 #define TS_PACKET_SIZE_204 204
534 #define TS_PACKET_SIZE_MAX 204
535 #define TS_HEADER_SIZE 4
537 static int DetectPacketSize( demux_t *p_demux, unsigned *pi_header_size, int i_offset )
539 const uint8_t *p_peek;
541 if( stream_Peek( p_demux->s,
542 &p_peek, i_offset + TS_PACKET_SIZE_MAX ) < i_offset + TS_PACKET_SIZE_MAX )
545 for( int i_sync = 0; i_sync < TS_PACKET_SIZE_MAX; i_sync++ )
547 if( p_peek[i_offset + i_sync] != 0x47 )
550 /* Check next 3 sync bytes */
551 int i_peek = i_offset + TS_PACKET_SIZE_MAX * 3 + i_sync + 1;
552 if( ( stream_Peek( p_demux->s, &p_peek, i_peek ) ) < i_peek )
554 msg_Err( p_demux, "cannot peek" );
557 if( p_peek[i_offset + i_sync + 1 * TS_PACKET_SIZE_188] == 0x47 &&
558 p_peek[i_offset + i_sync + 2 * TS_PACKET_SIZE_188] == 0x47 &&
559 p_peek[i_offset + i_sync + 3 * TS_PACKET_SIZE_188] == 0x47 )
561 return TS_PACKET_SIZE_188;
563 else if( p_peek[i_offset + i_sync + 1 * TS_PACKET_SIZE_192] == 0x47 &&
564 p_peek[i_offset + i_sync + 2 * TS_PACKET_SIZE_192] == 0x47 &&
565 p_peek[i_offset + i_sync + 3 * TS_PACKET_SIZE_192] == 0x47 )
569 *pi_header_size = 4; /* BluRay TS packets have 4-byte header */
571 return TS_PACKET_SIZE_192;
573 else if( p_peek[i_offset + i_sync + 1 * TS_PACKET_SIZE_204] == 0x47 &&
574 p_peek[i_offset + i_sync + 2 * TS_PACKET_SIZE_204] == 0x47 &&
575 p_peek[i_offset + i_sync + 3 * TS_PACKET_SIZE_204] == 0x47 )
577 return TS_PACKET_SIZE_204;
581 if( p_demux->b_force )
583 msg_Warn( p_demux, "this does not look like a TS stream, continuing" );
584 return TS_PACKET_SIZE_188;
586 msg_Dbg( p_demux, "TS module discarded (lost sync)" );
590 #define TOPFIELD_HEADER_SIZE 3712
592 static int DetectPVRHeadersAndHeaderSize( demux_t *p_demux, unsigned *pi_header_size, vdr_info_t *p_vdr )
594 const uint8_t *p_peek;
596 int i_packet_size = -1;
598 if( stream_Peek( p_demux->s,
599 &p_peek, TS_PACKET_SIZE_MAX ) < TS_PACKET_SIZE_MAX )
602 if( memcmp( p_peek, "TFrc", 4 ) == 0 &&
603 p_peek[6] == 0 && memcmp( &p_peek[53], "\x80\x00\x00", 4 ) == 0 &&
604 stream_Peek( p_demux->s, &p_peek, TOPFIELD_HEADER_SIZE + TS_PACKET_SIZE_MAX )
605 == TOPFIELD_HEADER_SIZE + TS_PACKET_SIZE_MAX )
607 i_packet_size = DetectPacketSize( p_demux, pi_header_size, TOPFIELD_HEADER_SIZE );
608 if( i_packet_size != -1 )
610 msg_Dbg( p_demux, "this is a topfield file" );
612 /* I used the TF5000PVR 2004 Firmware .doc header documentation,
613 * http://www.i-topfield.com/data/product/firmware/Structure%20of%20Recorded%20File%20in%20TF5000PVR%20(Feb%2021%202004).doc
614 * but after the filename the offsets seem to be incorrect. - DJ */
615 int i_duration, i_name;
616 char *psz_name = xmalloc(25);
617 char *psz_event_name;
618 char *psz_event_text = xmalloc(130);
619 char *psz_ext_text = xmalloc(1025);
621 // 2 bytes version Uimsbf (4,5)
622 // 2 bytes reserved (6,7)
623 // 2 bytes duration in minutes Uimsbf (8,9(
624 i_duration = (int) (p_peek[8] << 8) | p_peek[9];
625 msg_Dbg( p_demux, "Topfield recording length: +/- %d minutes", i_duration);
626 // 2 bytes service number in channel list (10, 11)
627 // 2 bytes service type Bslbf 0=TV 1=Radio Bslb (12, 13)
628 // 4 bytes of reserved + tuner info (14,15,16,17)
629 // 2 bytes of Service ID Bslbf (18,19)
630 // 2 bytes of PMT PID Uimsbf (20,21)
631 // 2 bytes of PCR PID Uimsbf (22,23)
632 // 2 bytes of Video PID Uimsbf (24,25)
633 // 2 bytes of Audio PID Uimsbf (26,27)
634 // 24 bytes filename Bslbf
635 memcpy( psz_name, &p_peek[28], 24 );
637 msg_Dbg( p_demux, "recordingname=%s", psz_name );
638 // 1 byte of sat index Uimsbf (52)
639 // 3 bytes (1 bit of polarity Bslbf +23 bits reserved)
640 // 4 bytes of freq. Uimsbf (56,57,58,59)
641 // 2 bytes of symbol rate Uimsbf (60,61)
642 // 2 bytes of TS stream ID Uimsbf (62,63)
645 // 2 bytes duration Uimsbf (70,71)
646 //i_duration = (int) (p_peek[70] << 8) | p_peek[71];
647 //msg_Dbg( p_demux, "Topfield 2nd duration field: +/- %d minutes", i_duration);
648 // 4 bytes EventID Uimsbf (72-75)
649 // 8 bytes of Start and End time info (76-83)
650 // 1 byte reserved (84)
651 // 1 byte event name length Uimsbf (89)
652 i_name = (int)(p_peek[89]&~0x81);
653 msg_Dbg( p_demux, "event name length = %d", i_name);
654 psz_event_name = xmalloc( i_name+1 );
655 // 1 byte parental rating (90)
656 // 129 bytes of event text
657 memcpy( psz_event_name, &p_peek[91], i_name );
658 psz_event_name[i_name] = '\0';
659 memcpy( psz_event_text, &p_peek[91+i_name], 129-i_name );
660 psz_event_text[129-i_name] = '\0';
661 msg_Dbg( p_demux, "event name=%s", psz_event_name );
662 msg_Dbg( p_demux, "event text=%s", psz_event_text );
663 // 12 bytes reserved (220)
665 // 2 bytes Event Text Length Uimsbf
666 // 4 bytes EventID Uimsbf
667 // FIXME We just have 613 bytes. not enough for this entire text
668 // 1024 bytes Extended Event Text Bslbf
669 memcpy( psz_ext_text, p_peek+372, 1024 );
670 psz_ext_text[1024] = '\0';
671 msg_Dbg( p_demux, "extended event text=%s", psz_ext_text );
672 // 52 bytes reserved Bslbf
674 p_vdr->i_service = GetWBE(&p_peek[18]);
676 return i_packet_size;
677 //return TS_PACKET_SIZE_188;
681 return DetectPacketSize( p_demux, pi_header_size, 0 );
684 static inline mtime_t ExtractPESTimestamp( const uint8_t *p_data )
686 return ((mtime_t)(p_data[ 0]&0x0e ) << 29)|
687 (mtime_t)(p_data[1] << 22)|
688 ((mtime_t)(p_data[2]&0xfe) << 14)|
689 (mtime_t)(p_data[3] << 7)|
690 (mtime_t)(p_data[4] >> 1);
693 static void ProbePES( demux_t *p_demux, ts_pid_t *pid, const uint8_t *p_pesstart, size_t i_data, bool b_adaptfield )
695 demux_sys_t *p_sys = p_demux->p_sys;
696 const uint8_t *p_pes = p_pesstart;
697 pid->probed.i_type = -1;
704 uint8_t len = *p_pes;
709 p_pes++; i_data--;/* stuffing */
715 if( len >= 7 && (p_pes[1] & 0x10) )
716 pid->probed.i_pcr_count++;
725 if( p_pes[0] != 0 || p_pes[1] != 0 || p_pes[2] != 1 )
728 size_t i_pesextoffset = 8;
730 if( p_pes[7] & 0x80 ) // PTS
733 if ( i_data < i_pesextoffset )
735 i_dts = ExtractPESTimestamp( &p_pes[9] );
737 if( p_pes[7] & 0x40 ) // DTS
740 if ( i_data < i_pesextoffset )
742 i_dts = ExtractPESTimestamp( &p_pes[14] );
744 if( p_pes[7] & 0x20 ) // ESCR
746 if( p_pes[7] & 0x10 ) // ESrate
748 if( p_pes[7] & 0x08 ) // DSM
750 if( p_pes[7] & 0x04 ) // CopyInfo
752 if( p_pes[7] & 0x02 ) // PESCRC
755 if ( i_data < i_pesextoffset )
758 /* HeaderdataLength */
759 const size_t i_payloadoffset = 8 + 1 + p_pes[8];
762 if ( i_data < i_pesextoffset || i_data < i_payloadoffset )
765 i_data -= 8 + 1 + p_pes[8];
767 if( p_pes[7] & 0x01 ) // PESExt
769 size_t i_extension2_offset = 1;
770 if ( p_pes[i_pesextoffset] & 0x80 ) // private data
771 i_extension2_offset += 16;
772 if ( p_pes[i_pesextoffset] & 0x40 ) // pack
773 i_extension2_offset += 1;
774 if ( p_pes[i_pesextoffset] & 0x20 ) // seq
775 i_extension2_offset += 2;
776 if ( p_pes[i_pesextoffset] & 0x10 ) // P-STD
777 i_extension2_offset += 2;
778 if ( p_pes[i_pesextoffset] & 0x01 ) // Extension 2
780 uint8_t i_len = p_pes[i_pesextoffset + i_extension2_offset] & 0x7F;
781 i_extension2_offset += i_len;
783 if( i_data < i_extension2_offset )
786 i_data -= i_extension2_offset;
788 /* (i_payloadoffset - i_pesextoffset) 0xFF stuffing */
793 const uint8_t *p_data = &p_pes[i_payloadoffset];
795 if(p_pes[3] >= 0xC0 && p_pes[3] <= 0xDF)
797 if( !memcmp( p_data, "\x7F\xFE\x80\x01", 4 ) )
799 pid->probed.i_type = 0x06;
800 pid->probed.i_fourcc = VLC_CODEC_DTS;
802 else if( !memcmp( p_data, "\x0B\x77", 2 ) )
804 pid->probed.i_type = 0x06;
805 pid->probed.i_fourcc = VLC_CODEC_EAC3;
807 else if( p_data[0] == 0xFF && (p_data[1] & 0xE0) == 0xE0 )
809 switch(p_data[1] & 18)
811 /* 10 - MPEG Version 2 (ISO/IEC 13818-3)
812 11 - MPEG Version 1 (ISO/IEC 11172-3) */
814 pid->probed.i_type = 0x04;
817 pid->probed.i_type = 0x03;
822 switch(p_data[1] & 6)
828 pid->probed.i_type = 0x04;
829 pid->probed.i_fourcc = VLC_CODEC_MPGA;
832 pid->probed.i_type = 0x04;
833 pid->probed.i_fourcc = VLC_CODEC_MP2;
836 pid->probed.i_type = 0x04;
837 pid->probed.i_fourcc = VLC_CODEC_MP3;
844 else if( p_pes[3] >= 0xE0 && p_pes[3] <= 0xEF )
846 if( !memcmp( p_data, "\x00\x00\x00", 4 ) )
848 pid->probed.i_type = 0x1b;
849 pid->probed.i_fourcc = VLC_CODEC_H264;
851 else if( !memcmp( p_data, "\x00\x00\x01", 4 ) )
853 pid->probed.i_type = 0x02;
854 pid->probed.i_fourcc = VLC_CODEC_MPGV;
858 /* Track timestamps and flag missing PAT */
859 if( !p_sys->patfix.i_timesourcepid && i_dts > -1 )
861 p_sys->patfix.i_first_dts = i_dts;
862 p_sys->patfix.i_timesourcepid = pid->i_pid;
864 else if( p_sys->patfix.i_timesourcepid == pid->i_pid && i_dts > -1 &&
865 !p_sys->patfix.b_pat_deadline )
867 if( i_dts - p_sys->patfix.i_first_dts > TO_SCALE(MIN_PAT_INTERVAL) )
868 p_sys->patfix.b_pat_deadline = true;
873 static void BuildPATCallback( void *p_opaque, block_t *p_block )
875 ts_pid_t *pat_pid = (ts_pid_t *) p_opaque;
876 dvbpsi_packet_push( pat_pid->u.p_pat->handle, p_block->p_buffer );
879 static void BuildPMTCallback( void *p_opaque, block_t *p_block )
881 ts_pid_t *program_pid = (ts_pid_t *) p_opaque;
882 assert(program_pid->type == TYPE_PMT);
885 dvbpsi_packet_push( program_pid->u.p_pmt->handle,
887 p_block = p_block->p_next;
891 static void MissingPATPMTFixup( demux_t *p_demux )
893 demux_sys_t *p_sys = p_demux->p_sys;
894 int i_program_number = 1234;
895 int i_program_pid = 1337;
896 int i_pcr_pid = 0x1FFF;
899 ts_pid_t *p_program_pid = PID( p_sys, i_program_pid );
900 if( SEEN(p_program_pid) )
902 /* Find a free one */
903 for( i_program_pid = MIN_ES_PID;
904 i_program_pid <= MAX_ES_PID && SEEN(p_program_pid);
907 p_program_pid = PID( p_sys, i_program_pid );
911 for( int i=0; i<p_sys->pids.i_all; i++ )
913 const ts_pid_t *p_pid = p_sys->pids.pp_all[i];
915 p_pid->probed.i_type == -1 )
918 if( i_pcr_pid == 0x1FFF && ( p_pid->probed.i_type == 0x03 ||
919 p_pid->probed.i_pcr_count ) )
920 i_pcr_pid = p_pid->i_pid;
928 ts_stream_t patstream =
931 .i_continuity_counter = 0x10,
932 .b_discontinuity = false
935 ts_stream_t pmtprogramstream =
937 .i_pid = i_program_pid,
938 .i_continuity_counter = 0x0,
939 .b_discontinuity = false
942 BuildPAT( PID(p_sys, 0)->u.p_pat->handle,
943 &p_sys->pids.pat, BuildPATCallback,
946 1, &pmtprogramstream, &i_program_number );
948 /* PAT callback should have been triggered */
949 if( p_program_pid->type != TYPE_PMT )
951 msg_Err( p_demux, "PAT creation failed" );
960 es_format_t esfmt = {0};
961 struct esstreams_t *esstreams = calloc( i_num_pes, sizeof(struct esstreams_t) );
962 pes_mapped_stream_t *mapped = calloc( i_num_pes, sizeof(pes_mapped_stream_t) );
963 if( esstreams && mapped )
966 for( int i=0; i<p_sys->pids.i_all; i++ )
968 const ts_pid_t *p_pid = p_sys->pids.pp_all[i];
971 p_pid->probed.i_type == -1 )
974 esstreams[j].pes.i_stream_type = p_pid->probed.i_type;
975 esstreams[j].pes.i_stream_type = p_pid->probed.i_type;
976 esstreams[j].ts.i_pid = p_pid->i_pid;
977 mapped[j].pes = &esstreams[j].pes;
978 mapped[j].ts = &esstreams[j].ts;
979 mapped[j].fmt = &esfmt;
983 BuildPMT( PID(p_sys, 0)->u.p_pat->handle, VLC_OBJECT(p_demux),
984 p_program_pid, BuildPMTCallback,
988 1, &pmtprogramstream, &i_program_number,
995 /*****************************************************************************
997 *****************************************************************************/
998 static int Open( vlc_object_t *p_this )
1000 demux_t *p_demux = (demux_t*)p_this;
1004 unsigned i_packet_header_size = 0;
1007 vdr_info_t vdr = {0};
1009 /* Search first sync byte */
1010 i_packet_size = DetectPVRHeadersAndHeaderSize( p_demux, &i_packet_header_size, &vdr );
1011 if( i_packet_size < 0 )
1012 return VLC_EGENERIC;
1014 p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
1017 memset( p_sys, 0, sizeof( demux_sys_t ) );
1018 vlc_mutex_init( &p_sys->csa_lock );
1020 p_demux->pf_demux = Demux;
1021 p_demux->pf_control = Control;
1023 /* Init p_sys field */
1024 p_sys->b_dvb_meta = true;
1025 p_sys->b_access_control = true;
1026 p_sys->b_end_preparse = false;
1027 ARRAY_INIT( p_sys->programs );
1028 p_sys->b_default_selection = false;
1029 p_sys->i_tdt_delta = 0;
1030 p_sys->i_dvb_start = 0;
1031 p_sys->i_dvb_length = 0;
1035 p_sys->arib.b25stream = NULL;
1036 p_sys->stream = p_demux->s;
1038 p_sys->b_broken_charset = false;
1040 p_sys->pids.dummy.i_pid = 8191;
1041 p_sys->pids.dummy.i_flags = FLAG_SEEN;
1043 p_sys->i_packet_size = i_packet_size;
1044 p_sys->i_packet_header_size = i_packet_header_size;
1045 p_sys->i_ts_read = 50;
1047 p_sys->b_start_record = false;
1049 # define VLC_DVBPSI_DEMUX_TABLE_INIT(table,obj) \
1051 if( !dvbpsi_AttachDemux( (table)->u.p_psi->handle, (dvbpsi_demux_new_cb_t)PSINewTableCallBack, (obj) ) ) \
1053 msg_Warn( obj, "Can't dvbpsi_AttachDemux on pid %d", (table)->i_pid );\
1057 /* Init PAT handler */
1058 patpid = PID(p_sys, 0);
1059 if ( !PIDSetup( p_demux, TYPE_PAT, patpid, NULL ) )
1061 vlc_mutex_destroy( &p_sys->csa_lock );
1065 if( !dvbpsi_pat_attach( patpid->u.p_pat->handle, PATCallBack, p_demux ) )
1067 PIDRelease( p_demux, patpid );
1068 vlc_mutex_destroy( &p_sys->csa_lock );
1070 return VLC_EGENERIC;
1073 if( p_sys->b_dvb_meta )
1075 if( !PIDSetup( p_demux, TYPE_SDT, PID(p_sys, 0x11), NULL ) ||
1076 !PIDSetup( p_demux, TYPE_EIT, PID(p_sys, 0x12), NULL ) ||
1077 !PIDSetup( p_demux, TYPE_TDT, PID(p_sys, 0x14), NULL ) )
1079 PIDRelease( p_demux, PID(p_sys, 0x11) );
1080 PIDRelease( p_demux, PID(p_sys, 0x12) );
1081 PIDRelease( p_demux, PID(p_sys, 0x14) );
1082 p_sys->b_dvb_meta = false;
1086 VLC_DVBPSI_DEMUX_TABLE_INIT(PID(p_sys, 0x11), p_demux);
1087 VLC_DVBPSI_DEMUX_TABLE_INIT(PID(p_sys, 0x12), p_demux);
1088 VLC_DVBPSI_DEMUX_TABLE_INIT(PID(p_sys, 0x14), p_demux);
1089 if( p_sys->b_access_control &&
1090 ( SetPIDFilter( p_sys, PID(p_sys, 0x11), true ) ||
1091 SetPIDFilter( p_sys, PID(p_sys, 0x14), true ) ||
1092 SetPIDFilter( p_sys, PID(p_sys, 0x12), true ) )
1094 p_sys->b_access_control = false;
1098 # undef VLC_DVBPSI_DEMUX_TABLE_INIT
1100 p_sys->i_pmt_es = 0;
1101 p_sys->b_es_all = false;
1104 p_sys->b_es_id_pid = var_CreateGetBool( p_demux, "ts-es-id-pid" );
1105 p_sys->i_next_extraid = 1;
1107 p_sys->b_trust_pcr = var_CreateGetBool( p_demux, "ts-trust-pcr" );
1109 /* We handle description of an extra PMT */
1110 char* psz_string = var_CreateGetString( p_demux, "ts-extra-pmt" );
1111 p_sys->b_user_pmt = false;
1112 if( psz_string && *psz_string )
1113 UserPmt( p_demux, psz_string );
1116 psz_string = var_CreateGetStringCommand( p_demux, "ts-csa-ck" );
1117 if( psz_string && *psz_string )
1122 p_sys->csa = csa_New();
1124 psz_csa2 = var_CreateGetStringCommand( p_demux, "ts-csa2-ck" );
1125 i_res = csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_string, true );
1126 if( i_res == VLC_SUCCESS && psz_csa2 && *psz_csa2 )
1128 if( csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_csa2, false ) != VLC_SUCCESS )
1130 csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_string, false );
1133 else if ( i_res == VLC_SUCCESS )
1135 csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_string, false );
1139 csa_Delete( p_sys->csa );
1145 var_AddCallback( p_demux, "ts-csa-ck", ChangeKeyCallback, (void *)1 );
1146 var_AddCallback( p_demux, "ts-csa2-ck", ChangeKeyCallback, NULL );
1148 int i_pkt = var_CreateGetInteger( p_demux, "ts-csa-pkt" );
1149 if( i_pkt < 4 || i_pkt > 188 )
1151 msg_Err( p_demux, "wrong packet size %d specified.", i_pkt );
1152 msg_Warn( p_demux, "using default packet size of 188 bytes" );
1153 p_sys->i_csa_pkt_size = 188;
1156 p_sys->i_csa_pkt_size = i_pkt;
1157 msg_Dbg( p_demux, "decrypting %d bytes of packet", p_sys->i_csa_pkt_size );
1163 p_sys->b_split_es = var_InheritBool( p_demux, "ts-split-es" );
1165 p_sys->b_canseek = false;
1166 p_sys->b_canfastseek = false;
1167 p_sys->b_force_seek_per_percent = var_InheritBool( p_demux, "ts-seek-percent" );
1169 p_sys->arib.e_mode = var_InheritInteger( p_demux, "ts-arib" );
1171 stream_Control( p_sys->stream, STREAM_CAN_SEEK, &p_sys->b_canseek );
1172 stream_Control( p_sys->stream, STREAM_CAN_FASTSEEK, &p_sys->b_canfastseek );
1175 if( p_sys->b_canseek )
1177 p_sys->es_creation = NO_ES;
1178 while( !p_sys->i_pmt_es && !p_sys->b_end_preparse )
1179 if( Demux( p_demux ) != VLC_DEMUXER_SUCCESS )
1181 p_sys->es_creation = DELAY_ES;
1184 p_sys->es_creation = ( p_sys->b_access_control ? CREATE_ES : DELAY_ES );
1189 /*****************************************************************************
1191 *****************************************************************************/
1192 static void Close( vlc_object_t *p_this )
1194 demux_t *p_demux = (demux_t*)p_this;
1195 demux_sys_t *p_sys = p_demux->p_sys;
1197 PIDRelease( p_demux, PID(p_sys, 0) );
1199 if( p_sys->b_dvb_meta )
1201 PIDRelease( p_demux, PID(p_sys, 0x11) );
1202 PIDRelease( p_demux, PID(p_sys, 0x12) );
1203 PIDRelease( p_demux, PID(p_sys, 0x14) );
1206 vlc_mutex_lock( &p_sys->csa_lock );
1209 var_DelCallback( p_demux, "ts-csa-ck", ChangeKeyCallback, NULL );
1210 var_DelCallback( p_demux, "ts-csa2-ck", ChangeKeyCallback, NULL );
1211 csa_Delete( p_sys->csa );
1213 vlc_mutex_unlock( &p_sys->csa_lock );
1215 ARRAY_RESET( p_sys->programs );
1218 if ( p_sys->arib.p_instance )
1219 arib_instance_destroy( p_sys->arib.p_instance );
1222 if ( p_sys->arib.b25stream )
1224 p_sys->arib.b25stream->p_source = NULL; /* don't chain kill demuxer's source */
1225 stream_Delete( p_sys->arib.b25stream );
1228 vlc_mutex_destroy( &p_sys->csa_lock );
1230 /* Release all non default pids */
1231 for( int i = 0; i < p_sys->pids.i_all; i++ )
1233 ts_pid_t *pid = p_sys->pids.pp_all[i];
1235 if( pid->type != TYPE_FREE )
1236 msg_Err( p_demux, "PID %d type %d not freed", pid->i_pid, pid->type );
1240 free( p_sys->pids.pp_all );
1245 /*****************************************************************************
1246 * ChangeKeyCallback: called when changing the odd encryption key on the fly.
1247 *****************************************************************************/
1248 static int ChangeKeyCallback( vlc_object_t *p_this, char const *psz_cmd,
1249 vlc_value_t oldval, vlc_value_t newval,
1252 VLC_UNUSED(psz_cmd); VLC_UNUSED(oldval);
1253 demux_t *p_demux = (demux_t*)p_this;
1254 demux_sys_t *p_sys = p_demux->p_sys;
1255 int i_tmp = (intptr_t)p_data;
1257 vlc_mutex_lock( &p_sys->csa_lock );
1259 i_tmp = csa_SetCW( p_this, p_sys->csa, newval.psz_string, true );
1261 i_tmp = csa_SetCW( p_this, p_sys->csa, newval.psz_string, false );
1263 vlc_mutex_unlock( &p_sys->csa_lock );
1267 /*****************************************************************************
1269 *****************************************************************************/
1270 static int Demux( demux_t *p_demux )
1272 demux_sys_t *p_sys = p_demux->p_sys;
1273 bool b_wait_es = p_sys->i_pmt_es <= 0;
1275 /* If we had no PAT within MIN_PAT_INTERVAL, create PAT/PMT from probed streams */
1276 if( p_sys->i_pmt_es == 0 && !SEEN(PID(p_sys, 0)) && p_sys->patfix.b_pat_deadline )
1277 MissingPATPMTFixup( p_demux );
1279 /* We read at most 100 TS packet or until a frame is completed */
1280 for( unsigned i_pkt = 0; i_pkt < p_sys->i_ts_read; i_pkt++ )
1282 bool b_frame = false;
1284 if( !(p_pkt = ReadTSPacket( p_demux )) )
1286 return VLC_DEMUXER_EOF;
1289 if( p_sys->b_start_record )
1291 /* Enable recording once synchronized */
1292 stream_Control( p_sys->stream, STREAM_SET_RECORD_STATE, true, "ts" );
1293 p_sys->b_start_record = false;
1296 /* Parse the TS packet */
1297 ts_pid_t *p_pid = PID( p_sys, PIDGet( p_pkt ) );
1299 if( SCRAMBLED(*p_pid) != !!(p_pkt->p_buffer[3] & 0x80) )
1300 UpdateScrambledState( p_demux, p_pid, p_pkt->p_buffer[3] & 0x80 );
1304 if( p_pid->type == TYPE_FREE )
1305 msg_Dbg( p_demux, "pid[%d] unknown", p_pid->i_pid );
1306 p_pid->i_flags |= FLAG_SEEN;
1309 if ( SCRAMBLED(*p_pid) && !p_demux->p_sys->csa )
1311 block_Release( p_pkt );
1315 /* Probe streams to build PAT/PMT after MIN_PAT_INTERVAL in case we don't see any PAT */
1316 if( !SEEN( PID( p_sys, 0 ) ) &&
1317 (p_pid->probed.i_type == 0 || p_pid->i_pid == p_sys->patfix.i_timesourcepid) &&
1318 (p_pkt->p_buffer[1] & 0xC0) == 0x40 && /* Payload start but not corrupt */
1319 (p_pkt->p_buffer[3] & 0xD0) == 0x10 ) /* Has payload but is not encrypted */
1321 ProbePES( p_demux, p_pid, p_pkt->p_buffer + TS_HEADER_SIZE,
1322 p_pkt->i_buffer - TS_HEADER_SIZE, p_pkt->p_buffer[3] & 0x20 /* Adaptation field */);
1325 switch( p_pid->type )
1328 dvbpsi_packet_push( p_pid->u.p_pat->handle, p_pkt->p_buffer );
1329 block_Release( p_pkt );
1333 dvbpsi_packet_push( p_pid->u.p_pmt->handle, p_pkt->p_buffer );
1334 block_Release( p_pkt );
1338 p_sys->b_end_preparse = true;
1340 if( p_sys->es_creation == DELAY_ES ) /* No longer delay ES since that pid's program sends data */
1342 msg_Dbg( p_demux, "Creating delayed ES" );
1343 AddAndCreateES( p_demux, p_pid, true );
1346 if( !p_sys->b_access_control && !(p_pid->i_flags & FLAG_FILTERED) )
1348 /* That packet is for an unselected ES, don't waste time/memory gathering its data */
1349 block_Release( p_pkt );
1353 b_frame = GatherData( p_demux, p_pid, p_pkt );
1359 if( p_sys->b_dvb_meta )
1360 dvbpsi_packet_push( p_pid->u.p_psi->handle, p_pkt->p_buffer );
1361 block_Release( p_pkt );
1365 /* We have to handle PCR if present */
1366 PCRHandle( p_demux, p_pid, p_pkt );
1367 block_Release( p_pkt );
1371 if( b_frame || ( b_wait_es && p_sys->i_pmt_es > 0 ) )
1375 demux_UpdateTitleFromStream( p_demux );
1376 return VLC_DEMUXER_SUCCESS;
1379 /*****************************************************************************
1381 *****************************************************************************/
1382 static int DVBEventInformation( demux_t *p_demux, int64_t *pi_time, int64_t *pi_length )
1384 demux_sys_t *p_sys = p_demux->p_sys;
1390 if( p_sys->i_dvb_length > 0 )
1392 const int64_t t = mdate() + p_sys->i_tdt_delta;
1394 if( p_sys->i_dvb_start <= t && t < p_sys->i_dvb_start + p_sys->i_dvb_length )
1397 *pi_length = p_sys->i_dvb_length;
1399 *pi_time = t - p_sys->i_dvb_start;
1403 return VLC_EGENERIC;
1406 static void UpdatePESFilters( demux_t *p_demux, bool b_all )
1408 demux_sys_t *p_sys = p_demux->p_sys;
1409 ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
1410 for( int i=0; i< p_pat->programs.i_size; i++ )
1412 ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
1413 bool b_program_selected;
1414 if( (p_sys->b_default_selection && !p_sys->b_access_control) || b_all )
1415 b_program_selected = true;
1417 b_program_selected = ProgramIsSelected( p_sys, p_pmt->i_number );
1419 SetPIDFilter( p_sys, p_pat->programs.p_elems[i], b_program_selected );
1421 for( int j=0; j<p_pmt->e_streams.i_size; j++ )
1423 ts_pid_t *espid = p_pmt->e_streams.p_elems[j];
1424 bool b_stream_selected = b_program_selected;
1425 if( b_program_selected && !b_all && espid->u.p_pes->es.id )
1426 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
1427 espid->u.p_pes->es.id, &b_stream_selected );
1429 if( !p_sys->b_es_all && espid->u.p_pes->es.fmt.i_cat == UNKNOWN_ES )
1430 b_stream_selected = false;
1432 if( b_stream_selected )
1433 msg_Dbg( p_demux, "enabling pid %d from program %d", espid->i_pid, p_pmt->i_number );
1435 SetPIDFilter( p_sys, espid, b_stream_selected );
1436 if( !b_stream_selected )
1437 FlushESBuffer( espid->u.p_pes );
1440 /* Select pcr last in case it is handled by unselected ES */
1441 if( p_pmt->i_pid_pcr > 0 )
1443 SetPIDFilter( p_sys, PID(p_sys, p_pmt->i_pid_pcr), b_program_selected );
1444 if( b_program_selected )
1445 msg_Dbg( p_demux, "enabling pcr pid %d from program %d", p_pmt->i_pid_pcr, p_pmt->i_number );
1450 static int Control( demux_t *p_demux, int i_query, va_list args )
1452 demux_sys_t *p_sys = p_demux->p_sys;
1454 bool b_bool, *pb_bool;
1459 int i_first_program = ( p_sys->programs.i_size ) ? p_sys->programs.p_elems[0] : 0;
1461 if( PREPARSING || !i_first_program || p_sys->b_default_selection )
1463 if( likely(PID(p_sys, 0)->type == TYPE_PAT) )
1465 ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
1466 /* Set default program for preparse time (no program has been selected) */
1467 for( int i = 0; i < p_pat->programs.i_size; i++ )
1469 assert(p_pat->programs.p_elems[i]->type == TYPE_PMT);
1470 p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
1471 if( ( p_pmt->pcr.i_first > -1 || p_pmt->pcr.i_first_dts > VLC_TS_INVALID ) && p_pmt->i_last_dts > 0 )
1473 i_first_program = p_pmt->i_number;
1482 case DEMUX_GET_POSITION:
1483 pf = (double*) va_arg( args, double* );
1485 /* Access control test is because EPG for recordings is not relevant */
1486 if( p_sys->b_dvb_meta && p_sys->b_access_control )
1488 int64_t i_time, i_length;
1489 if( !DVBEventInformation( p_demux, &i_time, &i_length ) && i_length > 0 )
1491 *pf = (double)i_time/(double)i_length;
1496 if( (p_pmt = GetProgramByID( p_sys, i_first_program )) &&
1497 p_pmt->pcr.i_first > -1 && p_pmt->i_last_dts > VLC_TS_INVALID &&
1498 p_pmt->pcr.i_current > -1 )
1500 double i_length = TimeStampWrapAround( p_pmt,
1501 p_pmt->i_last_dts ) - p_pmt->pcr.i_first;
1502 i_length += p_pmt->pcr.i_pcroffset;
1503 double i_pos = TimeStampWrapAround( p_pmt,
1504 p_pmt->pcr.i_current ) - p_pmt->pcr.i_first;
1505 *pf = i_pos / i_length;
1509 if( (i64 = stream_Size( p_sys->stream) ) > 0 )
1511 int64_t offset = stream_Tell( p_sys->stream );
1512 *pf = (double)offset / (double)i64;
1517 case DEMUX_SET_POSITION:
1518 f = (double) va_arg( args, double );
1520 if(!p_sys->b_canseek)
1523 if( p_sys->b_dvb_meta && p_sys->b_access_control &&
1524 !p_sys->b_force_seek_per_percent &&
1525 (p_pmt = GetProgramByID( p_sys, i_first_program )) )
1527 int64_t i_time, i_length;
1528 if( !DVBEventInformation( p_demux, &i_time, &i_length ) &&
1529 i_length > 0 && !SeekToTime( p_demux, p_pmt, TO_SCALE(i_length) * f ) )
1531 ReadyQueuesPostSeek( p_demux );
1532 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME,
1533 TO_SCALE(i_length) * f );
1538 if( !p_sys->b_force_seek_per_percent &&
1539 (p_pmt = GetProgramByID( p_sys, i_first_program )) &&
1540 p_pmt->pcr.i_first > -1 && p_pmt->i_last_dts > VLC_TS_INVALID &&
1541 p_pmt->pcr.i_current > -1 )
1543 double i_length = TimeStampWrapAround( p_pmt,
1544 p_pmt->i_last_dts ) - p_pmt->pcr.i_first;
1545 if( !SeekToTime( p_demux, p_pmt, p_pmt->pcr.i_first + i_length * f ) )
1547 ReadyQueuesPostSeek( p_demux );
1548 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME,
1549 FROM_SCALE(p_pmt->pcr.i_first + i_length * f) );
1554 i64 = stream_Size( p_sys->stream );
1556 stream_Seek( p_sys->stream, (int64_t)(i64 * f) ) == VLC_SUCCESS )
1558 ReadyQueuesPostSeek( p_demux );
1563 case DEMUX_SET_TIME:
1564 i64 = (int64_t)va_arg( args, int64_t );
1566 if( p_sys->b_canseek &&
1567 (p_pmt = GetProgramByID( p_sys, i_first_program )) &&
1568 p_pmt->pcr.i_first > -1 &&
1569 !SeekToTime( p_demux, p_pmt, p_pmt->pcr.i_first + TO_SCALE(i64) ) )
1571 ReadyQueuesPostSeek( p_demux );
1572 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME,
1573 FROM_SCALE(p_pmt->pcr.i_first) + i64 - VLC_TS_0 );
1578 case DEMUX_GET_TIME:
1579 pi64 = (int64_t*)va_arg( args, int64_t * );
1581 if( p_sys->b_dvb_meta && p_sys->b_access_control )
1583 if( !DVBEventInformation( p_demux, pi64, NULL ) )
1587 if( (p_pmt = GetProgramByID( p_sys, i_first_program )) &&
1588 p_pmt->pcr.i_current > -1 && p_pmt->pcr.i_first > -1 )
1590 int64_t i_pcr = TimeStampWrapAround( p_pmt, p_pmt->pcr.i_current );
1591 *pi64 = FROM_SCALE(i_pcr - p_pmt->pcr.i_first);
1596 case DEMUX_GET_LENGTH:
1597 pi64 = (int64_t*)va_arg( args, int64_t * );
1599 if( p_sys->b_dvb_meta && p_sys->b_access_control )
1601 if( !DVBEventInformation( p_demux, NULL, pi64 ) )
1605 if( (p_pmt = GetProgramByID( p_sys, i_first_program )) &&
1606 ( p_pmt->pcr.i_first > -1 || p_pmt->pcr.i_first_dts > VLC_TS_INVALID ) &&
1607 p_pmt->i_last_dts > 0 )
1609 int64_t i_start = (p_pmt->pcr.i_first > -1) ? p_pmt->pcr.i_first :
1610 TO_SCALE(p_pmt->pcr.i_first_dts);
1611 int64_t i_last = TimeStampWrapAround( p_pmt, p_pmt->i_last_dts );
1612 i_last += p_pmt->pcr.i_pcroffset;
1613 *pi64 = FROM_SCALE(i_last - i_start);
1618 case DEMUX_SET_GROUP:
1622 i_int = (int)va_arg( args, int );
1623 p_list = (vlc_list_t *)va_arg( args, vlc_list_t * );
1624 msg_Dbg( p_demux, "DEMUX_SET_GROUP %d %p", i_int, p_list );
1626 if( i_int != 0 ) /* If not default program */
1628 /* Deselect/filter current ones */
1632 p_sys->b_es_all = false;
1633 ARRAY_APPEND( p_sys->programs, i_int );
1634 UpdatePESFilters( p_demux, false );
1636 else if( likely( p_list != NULL ) )
1638 p_sys->b_es_all = false;
1639 for( int i = 0; i < p_list->i_count; i++ )
1640 ARRAY_APPEND( p_sys->programs, p_list->p_values[i].i_int );
1641 UpdatePESFilters( p_demux, false );
1645 p_sys->b_es_all = true;
1646 ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
1647 for( int i = 0; i < p_pat->programs.i_size; i++ )
1648 ARRAY_APPEND( p_sys->programs, p_pat->programs.p_elems[i]->i_pid );
1649 UpdatePESFilters( p_demux, true );
1652 p_sys->b_default_selection = false;
1660 i_int = (int)va_arg( args, int );
1661 msg_Dbg( p_demux, "DEMUX_SET_ES %d", i_int );
1663 if( !p_sys->b_es_all ) /* Won't change anything */
1664 UpdatePESFilters( p_demux, false );
1669 case DEMUX_GET_TITLE_INFO:
1671 struct input_title_t ***v = va_arg( args, struct input_title_t*** );
1672 int *c = va_arg( args, int * );
1674 *va_arg( args, int* ) = 0; /* Title offset */
1675 *va_arg( args, int* ) = 0; /* Chapter offset */
1676 return stream_Control( p_sys->stream, STREAM_GET_TITLE_INFO, v, c );
1679 case DEMUX_SET_TITLE:
1680 return stream_vaControl( p_sys->stream, STREAM_SET_TITLE, args );
1682 case DEMUX_SET_SEEKPOINT:
1683 return stream_vaControl( p_sys->stream, STREAM_SET_SEEKPOINT, args );
1685 case DEMUX_GET_META:
1686 return stream_vaControl( p_sys->stream, STREAM_GET_META, args );
1688 case DEMUX_CAN_RECORD:
1689 pb_bool = (bool*)va_arg( args, bool * );
1693 case DEMUX_SET_RECORD_STATE:
1694 b_bool = (bool)va_arg( args, int );
1697 stream_Control( p_sys->stream, STREAM_SET_RECORD_STATE, false );
1698 p_sys->b_start_record = b_bool;
1701 case DEMUX_GET_SIGNAL:
1702 return stream_vaControl( p_sys->stream, STREAM_GET_SIGNAL, args );
1708 return VLC_EGENERIC;
1711 /*****************************************************************************
1713 *****************************************************************************/
1714 static int UserPmt( demux_t *p_demux, const char *psz_fmt )
1716 demux_sys_t *p_sys = p_demux->p_sys;
1717 char *psz_dup = strdup( psz_fmt );
1718 char *psz = psz_dup;
1726 i_pid = strtol( psz, &psz, 0 );
1727 if( i_pid < 2 || i_pid >= 8192 )
1730 /* Parse optional program number */
1733 i_number = strtol( &psz[1], &psz, 0 );
1736 ts_pid_t *pmtpid = PID(p_sys, i_pid);
1738 msg_Dbg( p_demux, "user pmt specified (pid=%d,number=%d)", i_pid, i_number );
1739 if ( !PIDSetup( p_demux, TYPE_PMT, pmtpid, PID(p_sys, 0) ) )
1743 ts_pmt_t *p_pmt = pmtpid->u.p_pmt;
1744 p_pmt->i_number = i_number != 0 ? i_number : TS_USER_PMT_NUMBER;
1745 if( !dvbpsi_pmt_attach( p_pmt->handle,
1746 ((i_number != TS_USER_PMT_NUMBER ? i_number : 1)),
1747 PMTCallBack, p_demux ) )
1749 PIDRelease( p_demux, pmtpid );
1753 ARRAY_APPEND( PID(p_sys, 0)->u.p_pat->programs, pmtpid );
1755 psz = strchr( psz, '=' );
1758 while( psz && *psz )
1760 char *psz_next = strchr( psz, ',' );
1766 i_pid = strtol( psz, &psz, 0 );
1767 if( *psz != ':' || i_pid < 2 || i_pid >= 8192 )
1770 char *psz_opt = &psz[1];
1771 if( !strcmp( psz_opt, "pcr" ) )
1773 p_pmt->i_pid_pcr = i_pid;
1775 else if( PID(p_sys, i_pid)->type == TYPE_FREE )
1777 ts_pid_t *pid = PID(p_sys, i_pid);
1779 char *psz_arg = strchr( psz_opt, '=' );
1783 if ( !PIDSetup( p_demux, TYPE_PES, pid, pmtpid ) )
1786 ARRAY_APPEND( p_pmt->e_streams, pid );
1788 if( p_pmt->i_pid_pcr <= 0 )
1789 p_pmt->i_pid_pcr = i_pid;
1791 es_format_t *fmt = &pid->u.p_pes->es.fmt;
1793 if( psz_arg && strlen( psz_arg ) == 4 )
1795 const vlc_fourcc_t i_codec = VLC_FOURCC( psz_arg[0], psz_arg[1],
1796 psz_arg[2], psz_arg[3] );
1797 int i_cat = UNKNOWN_ES;
1799 if( !strcmp( psz_opt, "video" ) )
1801 else if( !strcmp( psz_opt, "audio" ) )
1803 else if( !strcmp( psz_opt, "spu" ) )
1806 es_format_Init( fmt, i_cat, i_codec );
1807 fmt->b_packetized = false;
1811 const int i_stream_type = strtol( psz_opt, NULL, 0 );
1812 PIDFillFormat( fmt, i_stream_type );
1815 fmt->i_group = i_number;
1816 if( p_sys->b_es_id_pid )
1819 if( fmt->i_cat != UNKNOWN_ES )
1821 msg_Dbg( p_demux, " * es pid=%d fcc=%4.4s", i_pid,
1822 (char*)&fmt->i_codec );
1823 pid->u.p_pes->es.id = es_out_Add( p_demux->out, fmt );
1832 p_sys->b_user_pmt = true;
1838 return VLC_EGENERIC;
1841 static int SetPIDFilter( demux_sys_t *p_sys, ts_pid_t *p_pid, bool b_selected )
1844 p_pid->i_flags |= FLAG_FILTERED;
1846 p_pid->i_flags &= ~FLAG_FILTERED;
1848 if( !p_sys->b_access_control )
1849 return VLC_EGENERIC;
1851 return stream_Control( p_sys->stream, STREAM_SET_PRIVATE_ID_STATE,
1852 p_pid->i_pid, b_selected );
1855 static void PIDReset( ts_pid_t *pid )
1857 assert(pid->i_refcount == 0);
1859 pid->i_flags &= ~FLAG_SCRAMBLED;
1860 pid->p_parent = NULL;
1861 pid->type = TYPE_FREE;
1864 static bool PIDSetup( demux_t *p_demux, ts_pid_type_t i_type, ts_pid_t *pid, ts_pid_t *p_parent )
1866 if( pid == p_parent || pid->i_pid == 0x1FFF )
1869 if( pid->i_refcount == 0 )
1871 assert( pid->type == TYPE_FREE );
1874 case TYPE_FREE: /* nonsense ?*/
1880 pid->u.p_pat = ts_pat_New( p_demux );
1887 pid->u.p_pmt = ts_pmt_New( p_demux );
1894 pid->u.p_pes = ts_pes_New( p_demux );
1903 pid->u.p_psi = ts_psi_New( p_demux );
1915 pid->p_parent = p_parent;
1917 else if( pid->type == i_type && pid->i_refcount < UINT8_MAX )
1923 if( pid->type != TYPE_FREE )
1924 msg_Warn( p_demux, "Tried to redeclare pid %d with another type", pid->i_pid );
1931 static void PIDRelease( demux_t *p_demux, ts_pid_t *pid )
1933 if( pid->i_refcount == 0 )
1935 assert( pid->type == TYPE_FREE );
1938 else if( pid->i_refcount == 1 )
1942 else if( pid->i_refcount > 1 )
1944 assert( pid->type != TYPE_FREE && pid->type != TYPE_PAT );
1948 if( pid->i_refcount == 0 )
1953 case TYPE_FREE: /* nonsense ?*/
1954 assert( pid->type != TYPE_FREE );
1958 ts_pat_Del( p_demux, pid->u.p_pat );
1959 pid->u.p_pat = NULL;
1963 ts_pmt_Del( p_demux, pid->u.p_pmt );
1964 pid->u.p_pmt = NULL;
1968 ts_pes_Del( p_demux, pid->u.p_pes );
1969 pid->u.p_pes = NULL;
1975 ts_psi_Del( p_demux, pid->u.p_psi );
1976 pid->u.p_psi = NULL;
1981 SetPIDFilter( p_demux->p_sys, pid, false );
1986 static int16_t read_opus_flag(uint8_t **buf, size_t *len)
1991 int16_t ret = ((*buf)[0] << 8) | (*buf)[1];
2002 static block_t *Opus_Parse(demux_t *demux, block_t *block)
2004 block_t *out = NULL;
2005 block_t **last = NULL;
2007 uint8_t *buf = block->p_buffer;
2008 size_t len = block->i_buffer;
2010 while (len > 3 && ((buf[0] << 3) | (buf[1] >> 5)) == 0x3ff) {
2011 int16_t start_trim = 0, end_trim = 0;
2012 int start_trim_flag = (buf[1] >> 4) & 1;
2013 int end_trim_flag = (buf[1] >> 3) & 1;
2014 int control_extension_flag = (buf[1] >> 2) & 1;
2019 unsigned au_size = 0;
2027 if (start_trim_flag) {
2028 start_trim = read_opus_flag(&buf, &len);
2029 if (start_trim < 0) {
2030 msg_Err(demux, "Invalid start trimming flag");
2033 if (end_trim_flag) {
2034 end_trim = read_opus_flag(&buf, &len);
2036 msg_Err(demux, "Invalid end trimming flag");
2039 if (control_extension_flag && len) {
2040 unsigned l = *buf++; len--;
2042 msg_Err(demux, "Invalid control extension length %d > %zu", l, len);
2049 if (!au_size || au_size > len) {
2050 msg_Err(demux, "Invalid Opus AU size %d (PES %zu)", au_size, len);
2054 block_t *au = block_Alloc(au_size);
2057 memcpy(au->p_buffer, buf, au_size);
2058 block_CopyProperties(au, block);
2067 au->i_nb_samples = opus_frame_duration(buf, au_size);
2068 if (end_trim && (uint16_t) end_trim <= au->i_nb_samples)
2069 au->i_length = end_trim; /* Blatant abuse of the i_length field. */
2073 if (start_trim && start_trim < (au->i_nb_samples - au->i_length)) {
2074 au->i_nb_samples -= start_trim;
2075 if (au->i_nb_samples == 0)
2076 au->i_flags |= BLOCK_FLAG_PREROLL;
2083 block_Release(block);
2087 /****************************************************************************
2089 ****************************************************************************/
2090 static int ParsePESHeader( demux_t *p_demux, const uint8_t *p_header, size_t i_header,
2091 unsigned *pi_skip, mtime_t *pi_dts, mtime_t *pi_pts )
2096 return VLC_EGENERIC;
2098 switch( p_header[3] )
2100 case 0xBC: /* Program stream map */
2101 case 0xBE: /* Padding */
2102 case 0xBF: /* Private stream 2 */
2103 case 0xF0: /* ECM */
2104 case 0xF1: /* EMM */
2105 case 0xFF: /* Program stream directory */
2106 case 0xF2: /* DSMCC stream */
2107 case 0xF8: /* ITU-T H.222.1 type E stream */
2111 if( ( p_header[6]&0xC0 ) == 0x80 )
2114 i_skip = p_header[8] + 9;
2116 if( p_header[7]&0x80 ) /* has pts */
2118 if( i_header < 9 + 5 )
2119 return VLC_EGENERIC;
2120 *pi_pts = ExtractPESTimestamp( &p_header[9] );
2122 if( p_header[7]&0x40 ) /* has dts */
2124 if( i_header < 14 + 5 )
2125 return VLC_EGENERIC;
2126 *pi_dts = ExtractPESTimestamp( &p_header[14] );
2133 if( i_header < i_skip + 1 )
2134 return VLC_EGENERIC;
2135 while( i_skip < 23 && p_header[i_skip] == 0xff )
2138 if( i_header < i_skip + 1 )
2139 return VLC_EGENERIC;
2143 msg_Err( p_demux, "too much MPEG-1 stuffing" );
2144 return VLC_EGENERIC;
2146 if( ( p_header[i_skip] & 0xC0 ) == 0x40 )
2151 if( i_header < i_skip + 1 )
2152 return VLC_EGENERIC;
2154 if( p_header[i_skip]&0x20 )
2156 if( i_header < i_skip + 5 )
2157 return VLC_EGENERIC;
2158 *pi_pts = ExtractPESTimestamp( &p_header[i_skip] );
2160 if( p_header[i_skip]&0x10 ) /* has dts */
2162 if( i_header < i_skip + 10 )
2163 return VLC_EGENERIC;
2164 *pi_dts = ExtractPESTimestamp( &p_header[i_skip+5] );
2184 static void ParsePES( demux_t *p_demux, ts_pid_t *pid, block_t *p_pes )
2187 unsigned i_pes_size = 0;
2188 unsigned i_skip = 0;
2191 mtime_t i_length = 0;
2193 assert(pid->type == TYPE_PES);
2194 assert(pid->p_parent && pid->p_parent->type == TYPE_PMT);
2196 const int i_max = block_ChainExtract( p_pes, header, 34 );
2199 block_ChainRelease( p_pes );
2203 if( SCRAMBLED(*pid) || header[0] != 0 || header[1] != 0 || header[2] != 1 )
2205 if ( !SCRAMBLED(*pid) )
2206 msg_Warn( p_demux, "invalid header [0x%02x:%02x:%02x:%02x] (pid: %d)",
2207 header[0], header[1],header[2],header[3], pid->i_pid );
2208 block_ChainRelease( p_pes );
2212 if( ParsePESHeader( p_demux, (uint8_t*)&header, i_max, &i_skip, &i_dts, &i_pts ) == VLC_EGENERIC )
2214 block_ChainRelease( p_pes );
2220 i_pts = TimeStampWrapAround( pid->p_parent->u.p_pmt, i_pts );
2222 i_dts = TimeStampWrapAround( pid->p_parent->u.p_pmt, i_dts );
2225 if( pid->u.p_pes->es.fmt.i_codec == VLC_FOURCC( 'a', '5', '2', 'b' ) ||
2226 pid->u.p_pes->es.fmt.i_codec == VLC_FOURCC( 'd', 't', 's', 'b' ) )
2230 else if( pid->u.p_pes->es.fmt.i_codec == VLC_FOURCC( 'l', 'p', 'c', 'b' ) ||
2231 pid->u.p_pes->es.fmt.i_codec == VLC_FOURCC( 's', 'p', 'u', 'b' ) ||
2232 pid->u.p_pes->es.fmt.i_codec == VLC_FOURCC( 's', 'd', 'd', 'b' ) )
2236 else if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_SUBT &&
2237 pid->u.p_pes->es.p_mpeg4desc )
2239 const decoder_config_descriptor_t *dcd = &pid->u.p_pes->es.p_mpeg4desc->dec_descr;
2241 if( dcd->i_extra > 2 &&
2242 dcd->p_extra[0] == 0x10 &&
2243 ( dcd->p_extra[1]&0x10 ) )
2245 /* display length */
2246 if( p_pes->i_buffer + 2 <= i_skip )
2247 i_length = GetWBE( &p_pes->p_buffer[i_skip] );
2251 if( p_pes->i_buffer + 2 <= i_skip )
2252 i_pes_size = GetWBE( &p_pes->p_buffer[i_skip] );
2258 while( p_pes && i_skip > 0 )
2260 if( p_pes->i_buffer <= i_skip )
2262 block_t *p_next = p_pes->p_next;
2264 i_skip -= p_pes->i_buffer;
2265 block_Release( p_pes );
2270 p_pes->i_buffer -= i_skip;
2271 p_pes->p_buffer += i_skip;
2276 /* ISO/IEC 13818-1 2.7.5: if no pts and no dts, then dts == pts */
2277 if( i_pts >= 0 && i_dts < 0 )
2285 p_pes->i_dts = VLC_TS_0 + i_dts * 100 / 9;
2288 p_pes->i_pts = VLC_TS_0 + i_pts * 100 / 9;
2290 p_pes->i_length = i_length * 100 / 9;
2292 p_block = block_ChainGather( p_pes );
2293 if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_SUBT )
2295 if( i_pes_size > 0 && p_block->i_buffer > i_pes_size )
2297 p_block->i_buffer = i_pes_size;
2300 p_block = block_Realloc( p_block, 0, p_block->i_buffer + 1 );
2303 p_block->p_buffer[p_block->i_buffer -1] = '\0';
2305 else if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_TELETEXT )
2307 if( p_block->i_pts <= VLC_TS_INVALID && pid->p_parent )
2309 /* Teletext may have missing PTS (ETSI EN 300 472 Annexe A)
2310 * In this case use the last PCR + 40ms */
2311 assert( pid->p_parent->type == TYPE_PMT );
2312 if( likely(pid->p_parent->type == TYPE_PMT) )
2314 mtime_t i_pcr = pid->p_parent->u.p_pmt->pcr.i_current;
2315 if( i_pcr > VLC_TS_INVALID )
2316 p_block->i_pts = VLC_TS_0 + i_pcr * 100 / 9 + 40000;
2320 else if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_ARIB_A ||
2321 pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_ARIB_C )
2323 if( p_block->i_pts <= VLC_TS_INVALID )
2325 if( i_pes_size > 0 && p_block->i_buffer > i_pes_size )
2327 p_block->i_buffer = i_pes_size;
2330 p_block = block_Realloc( p_block, 0, p_block->i_buffer + 1 );
2333 p_block->p_buffer[p_block->i_buffer -1] = '\0';
2336 else if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_OPUS)
2338 p_block = Opus_Parse(p_demux, p_block);
2341 if( !pid->p_parent || pid->p_parent->type != TYPE_PMT )
2343 block_Release( p_block );
2347 ts_pmt_t *p_pmt = pid->p_parent->u.p_pmt;
2350 block_t *p_next = p_block->p_next;
2351 p_block->p_next = NULL;
2353 if( !p_pmt->pcr.b_fix_done ) /* Not seen yet */
2354 PCRFixHandle( p_demux, p_pmt, p_block );
2356 if( pid->u.p_pes->es.id && (p_pmt->pcr.i_current > -1 || p_pmt->pcr.b_disable) )
2358 if( pid->u.p_pes->p_prepcr_outqueue )
2360 block_ChainAppend( &pid->u.p_pes->p_prepcr_outqueue, p_block );
2361 p_block = pid->u.p_pes->p_prepcr_outqueue;
2362 p_next = p_block->p_next;
2363 p_block->p_next = NULL;
2364 pid->u.p_pes->p_prepcr_outqueue = NULL;
2367 if ( p_pmt->pcr.b_disable && p_block->i_dts > VLC_TS_INVALID &&
2368 ( p_pmt->i_pid_pcr == pid->i_pid || p_pmt->i_pid_pcr == 0x1FFF ) )
2370 ProgramSetPCR( p_demux, p_pmt, (p_block->i_dts - VLC_TS_0) * 9 / 100 - 120000 );
2373 /* Compute PCR/DTS offset if any */
2374 if( p_pmt->pcr.i_pcroffset == -1 && p_block->i_dts > VLC_TS_INVALID &&
2375 p_pmt->pcr.i_current > VLC_TS_INVALID )
2377 int64_t i_dts27 = (p_block->i_dts - VLC_TS_0) * 9 / 100;
2378 int64_t i_pcr = TimeStampWrapAround( p_pmt, p_pmt->pcr.i_current );
2379 if( i_dts27 < i_pcr )
2381 p_pmt->pcr.i_pcroffset = i_pcr - i_dts27 + 80000;
2382 msg_Warn( p_demux, "Broken stream: pid %d sends packets with dts %"PRId64
2383 "us later than pcr, applying delay",
2384 pid->i_pid, p_pmt->pcr.i_pcroffset * 100 / 9 );
2386 else p_pmt->pcr.i_pcroffset = 0;
2389 if( p_pmt->pcr.i_pcroffset != -1 )
2391 if( p_block->i_dts > VLC_TS_INVALID )
2392 p_block->i_dts += (p_pmt->pcr.i_pcroffset * 100 / 9);
2393 if( p_block->i_pts > VLC_TS_INVALID )
2394 p_block->i_pts += (p_pmt->pcr.i_pcroffset * 100 / 9);
2397 for( int i = 0; i < pid->u.p_pes->extra_es.i_size; i++ )
2399 es_out_Send( p_demux->out, pid->u.p_pes->extra_es.p_elems[i]->id,
2400 block_Duplicate( p_block ) );
2403 es_out_Send( p_demux->out, pid->u.p_pes->es.id, p_block );
2407 if( !p_pmt->pcr.b_fix_done ) /* Not seen yet */
2408 PCRFixHandle( p_demux, p_pmt, p_block );
2410 block_ChainAppend( &pid->u.p_pes->p_prepcr_outqueue, p_block );
2418 msg_Warn( p_demux, "empty pes" );
2422 static void ParseTableSection( demux_t *p_demux, ts_pid_t *pid, block_t *p_data )
2424 block_t *p_content = block_ChainGather( p_data );
2426 if ( pid->p_parent && pid->p_parent->type == TYPE_PMT )
2428 ts_pmt_t *p_pmt = pid->p_parent->u.p_pmt;
2429 mtime_t i_date = p_pmt->pcr.i_current;
2431 if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_SCTE_27 )
2433 /* We need to extract the truncated pts stored inside the payload */
2434 if( p_content->i_buffer > 9 && p_content->p_buffer[0] == 0xc6 )
2437 size_t i_offset = 4;
2438 if( p_content->p_buffer[3] & 0x40 )
2440 i_index = ((p_content->p_buffer[7] & 0x0f) << 8) |
2441 p_content->p_buffer[8];
2444 if( i_index == 0 && p_content->i_buffer > i_offset + 8 )
2446 bool is_immediate = p_content->p_buffer[i_offset + 3] & 0x40;
2449 mtime_t i_display_in = GetDWBE( &p_content->p_buffer[i_offset + 4] );
2450 if( i_display_in < i_date )
2451 i_date = i_display_in + (1ll << 32);
2453 i_date = i_display_in;
2460 p_content->i_dts = p_content->i_pts = VLC_TS_0 + i_date * 100 / 9;
2461 PCRFixHandle( p_demux, p_pmt, p_content );
2464 es_out_Send( p_demux->out, pid->u.p_pes->es.id, p_content );
2467 static void ParseData( demux_t *p_demux, ts_pid_t *pid )
2469 block_t *p_data = pid->u.p_pes->p_data;
2474 /* remove the pes from pid */
2475 pid->u.p_pes->p_data = NULL;
2476 pid->u.p_pes->i_data_size = 0;
2477 pid->u.p_pes->i_data_gathered = 0;
2478 pid->u.p_pes->pp_last = &pid->u.p_pes->p_data;
2480 if( pid->u.p_pes->data_type == TS_ES_DATA_PES )
2482 ParsePES( p_demux, pid, p_data );
2484 else if( pid->u.p_pes->data_type == TS_ES_DATA_TABLE_SECTION )
2486 ParseTableSection( p_demux, pid, p_data );
2490 block_ChainRelease( p_data );
2494 static block_t* ReadTSPacket( demux_t *p_demux )
2496 demux_sys_t *p_sys = p_demux->p_sys;
2500 /* Get a new TS packet */
2501 if( !( p_pkt = stream_Block( p_sys->stream, p_sys->i_packet_size ) ) )
2503 if( stream_Tell( p_sys->stream ) == stream_Size( p_sys->stream ) )
2504 msg_Dbg( p_demux, "EOF at %"PRId64, stream_Tell( p_sys->stream ) );
2506 msg_Dbg( p_demux, "Can't read TS packet at %"PRId64, stream_Tell(p_sys->stream) );
2510 if( p_pkt->i_buffer < TS_HEADER_SIZE + p_sys->i_packet_header_size )
2512 block_Release( p_pkt );
2516 /* Skip header (BluRay streams).
2517 * re-sync logic would do this (by adjusting packet start), but this would result in losing first and last ts packets.
2518 * First packet is usually PAT, and losing it means losing whole first GOP. This is fatal with still-image based menus.
2520 p_pkt->p_buffer += p_sys->i_packet_header_size;
2521 p_pkt->i_buffer -= p_sys->i_packet_header_size;
2523 /* Check sync byte and re-sync if needed */
2524 if( p_pkt->p_buffer[0] != 0x47 )
2526 msg_Warn( p_demux, "lost synchro" );
2527 block_Release( p_pkt );
2530 const uint8_t *p_peek;
2532 unsigned i_skip = 0;
2534 i_peek = stream_Peek( p_sys->stream, &p_peek,
2535 p_sys->i_packet_size * 10 );
2536 if( i_peek < 0 || (unsigned)i_peek < p_sys->i_packet_size + 1 )
2538 msg_Dbg( p_demux, "eof ?" );
2542 while( i_skip < i_peek - p_sys->i_packet_size )
2544 if( p_peek[i_skip + p_sys->i_packet_header_size] == 0x47 &&
2545 p_peek[i_skip + p_sys->i_packet_header_size + p_sys->i_packet_size] == 0x47 )
2551 msg_Dbg( p_demux, "skipping %d bytes of garbage", i_skip );
2552 stream_Read( p_sys->stream, NULL, i_skip );
2554 if( i_skip < i_peek - p_sys->i_packet_size )
2559 if( !( p_pkt = stream_Block( p_sys->stream, p_sys->i_packet_size ) ) )
2561 msg_Dbg( p_demux, "eof ?" );
2568 static int64_t TimeStampWrapAround( ts_pmt_t *p_pmt, int64_t i_time )
2570 int64_t i_adjust = 0;
2571 if( p_pmt && p_pmt->pcr.i_first > 0x0FFFFFFFF && i_time < 0x0FFFFFFFF )
2572 i_adjust = 0x1FFFFFFFF;
2574 return i_time + i_adjust;
2577 static mtime_t GetPCR( block_t *p_pkt )
2579 const uint8_t *p = p_pkt->p_buffer;
2583 if( ( p[3]&0x20 ) && /* adaptation */
2587 /* PCR is 33 bits */
2588 i_pcr = ( (mtime_t)p[6] << 25 ) |
2589 ( (mtime_t)p[7] << 17 ) |
2590 ( (mtime_t)p[8] << 9 ) |
2591 ( (mtime_t)p[9] << 1 ) |
2592 ( (mtime_t)p[10] >> 7 );
2597 static void UpdateScrambledState( demux_t *p_demux, ts_pid_t *p_pid, bool b_scrambled )
2599 if( !SCRAMBLED(*p_pid) == !b_scrambled )
2602 msg_Warn( p_demux, "scrambled state changed on pid %d (%d->%d)",
2603 p_pid->i_pid, SCRAMBLED(*p_pid), b_scrambled );
2605 p_pid->i_flags |= (b_scrambled) ? FLAG_SCRAMBLED : FLAGS_NONE;
2607 if( p_pid->type == TYPE_PES && p_pid->u.p_pes->es.id )
2609 for( int i = 0; i < p_pid->u.p_pes->extra_es.i_size; i++ )
2611 if( p_pid->u.p_pes->extra_es.p_elems[i]->id )
2612 es_out_Control( p_demux->out, ES_OUT_SET_ES_SCRAMBLED_STATE,
2613 p_pid->u.p_pes->extra_es.p_elems[i]->id, b_scrambled );
2615 es_out_Control( p_demux->out, ES_OUT_SET_ES_SCRAMBLED_STATE,
2616 p_pid->u.p_pes->es.id, b_scrambled );
2620 static inline void FlushESBuffer( ts_pes_t *p_pes )
2624 p_pes->i_data_gathered = p_pes->i_data_size = 0;
2625 block_ChainRelease( p_pes->p_data );
2626 p_pes->p_data = NULL;
2627 p_pes->pp_last = &p_pes->p_data;
2631 static void ReadyQueuesPostSeek( demux_t *p_demux )
2633 demux_sys_t *p_sys = p_demux->p_sys;
2635 ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
2636 for( int i=0; i< p_pat->programs.i_size; i++ )
2638 ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
2639 for( int j=0; j<p_pmt->e_streams.i_size; j++ )
2641 ts_pid_t *pid = p_pmt->e_streams.p_elems[j];
2643 if( pid->type != TYPE_PES )
2646 if( pid->u.p_pes->es.id )
2648 block_t *p_block = block_Alloc(1);
2651 p_block->i_buffer = 0;
2652 p_block->i_flags = BLOCK_FLAG_DISCONTINUITY | BLOCK_FLAG_CORRUPTED;
2653 es_out_Send( p_demux->out, pid->u.p_pes->es.id, p_block );
2659 if( pid->u.p_pes->p_prepcr_outqueue )
2661 block_ChainRelease( pid->u.p_pes->p_prepcr_outqueue );
2662 pid->u.p_pes->p_prepcr_outqueue = NULL;
2665 FlushESBuffer( pid->u.p_pes );
2667 p_pmt->pcr.i_current = -1;
2671 static int SeekToTime( demux_t *p_demux, ts_pmt_t *p_pmt, int64_t i_scaledtime )
2673 demux_sys_t *p_sys = p_demux->p_sys;
2675 /* Deal with common but worst binary search case */
2676 if( p_pmt->pcr.i_first == i_scaledtime && p_sys->b_canseek )
2677 return stream_Seek( p_sys->stream, 0 );
2679 if( !p_sys->b_canfastseek )
2680 return VLC_EGENERIC;
2682 int64_t i_initial_pos = stream_Tell( p_sys->stream );
2684 /* Find the time position by using binary search algorithm. */
2685 int64_t i_head_pos = 0;
2686 int64_t i_tail_pos = stream_Size( p_sys->stream ) - p_sys->i_packet_size;
2687 if( i_head_pos >= i_tail_pos )
2688 return VLC_EGENERIC;
2690 bool b_found = false;
2691 while( (i_head_pos + p_sys->i_packet_size) <= i_tail_pos && !b_found )
2693 /* Round i_pos to a multiple of p_sys->i_packet_size */
2694 int64_t i_splitpos = i_head_pos + (i_tail_pos - i_head_pos) / 2;
2695 int64_t i_div = i_splitpos % p_sys->i_packet_size;
2696 i_splitpos -= i_div;
2698 if ( stream_Seek( p_sys->stream, i_splitpos ) != VLC_SUCCESS )
2701 int64_t i_pos = i_splitpos;
2702 while( i_pos > -1 && i_pos < i_tail_pos )
2705 block_t *p_pkt = ReadTSPacket( p_demux );
2708 i_head_pos = i_tail_pos;
2712 i_pos = stream_Tell( p_sys->stream );
2714 int i_pid = PIDGet( p_pkt );
2715 if( i_pid != 0x1FFF && PID(p_sys, i_pid)->type == TYPE_PES &&
2716 PID(p_sys, i_pid)->p_parent->u.p_pmt == p_pmt &&
2717 (p_pkt->p_buffer[1] & 0xC0) == 0x40 && /* Payload start but not corrupt */
2718 (p_pkt->p_buffer[3] & 0xD0) == 0x10 /* Has payload but is not encrypted */
2721 unsigned i_skip = 4;
2722 if ( p_pkt->p_buffer[3] & 0x20 ) // adaptation field
2724 if( p_pkt->i_buffer >= 4 + 2 + 5 )
2726 i_pcr = GetPCR( p_pkt );
2727 i_skip += 1 + p_pkt->p_buffer[4];
2734 if ( VLC_SUCCESS == ParsePESHeader( p_demux, &p_pkt->p_buffer[i_skip],
2735 p_pkt->i_buffer - i_skip, &i_skip, &i_dts, &i_pts ) )
2742 block_Release( p_pkt );
2746 int64_t i_diff = i_scaledtime - TimeStampWrapAround( p_pmt, i_pcr );
2748 i_tail_pos = i_splitpos - p_sys->i_packet_size;
2749 else if( i_diff < TO_SCALE(VLC_TS_0 + CLOCK_FREQ / 2) ) // 500ms
2757 if ( !b_found && i_pos > i_tail_pos - p_sys->i_packet_size )
2758 i_tail_pos = i_splitpos - p_sys->i_packet_size;
2763 msg_Dbg( p_demux, "Seek():cannot find a time position." );
2764 stream_Seek( p_sys->stream, i_initial_pos );
2765 return VLC_EGENERIC;
2770 static ts_pid_t *PID( demux_sys_t *p_sys, uint16_t i_pid )
2775 return &p_sys->pids.pat;
2777 return &p_sys->pids.dummy;
2779 if( p_sys->pids.i_last_pid == i_pid )
2780 return p_sys->pids.p_last;
2784 for( int i=0; i < p_sys->pids.i_all; i++ )
2786 if( p_sys->pids.pp_all[i]->i_pid == i_pid )
2788 p_sys->pids.p_last = p_sys->pids.pp_all[i];
2789 p_sys->pids.i_last_pid = i_pid;
2790 return p_sys->pids.p_last;
2794 if( p_sys->pids.i_all >= p_sys->pids.i_all_alloc )
2796 ts_pid_t **p_realloc = realloc( p_sys->pids.pp_all,
2797 (p_sys->pids.i_all_alloc + PID_ALLOC_CHUNK) * sizeof(ts_pid_t *) );
2800 p_sys->pids.pp_all = p_realloc;
2801 p_sys->pids.i_all_alloc += PID_ALLOC_CHUNK;
2804 ts_pid_t *p_pid = calloc( 1, sizeof(*p_pid) );
2811 p_pid->i_pid = i_pid;
2812 p_sys->pids.pp_all[p_sys->pids.i_all++] = p_pid;
2814 p_sys->pids.p_last = p_pid;
2815 p_sys->pids.i_last_pid = i_pid;
2820 static ts_pmt_t * GetProgramByID( demux_sys_t *p_sys, int i_program )
2822 if(unlikely(PID(p_sys, 0)->type != TYPE_PAT))
2825 ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
2826 for( int i = 0; i < p_pat->programs.i_size; i++ )
2828 assert(p_pat->programs.p_elems[i]->type == TYPE_PMT);
2829 ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
2830 if( p_pmt->i_number == i_program )
2836 #define PROBE_CHUNK_COUNT 250
2838 static int ProbeChunk( demux_t *p_demux, int i_program, bool b_end, int64_t *pi_pcr, bool *pb_found )
2840 demux_sys_t *p_sys = p_demux->p_sys;
2842 block_t *p_pkt = NULL;
2848 if( i_count++ > PROBE_CHUNK_COUNT || !( p_pkt = ReadTSPacket( p_demux ) ) )
2853 const int i_pid = PIDGet( p_pkt );
2854 ts_pid_t *p_pid = PID(p_sys, i_pid);
2856 p_pid->i_flags |= FLAG_SEEN;
2858 if( i_pid != 0x1FFF && (p_pkt->p_buffer[1] & 0x80) == 0 ) /* not corrupt */
2860 bool b_pcrresult = true;
2861 bool b_adaptfield = p_pkt->p_buffer[3] & 0x20;
2863 if( b_adaptfield && p_pkt->i_buffer >= 4 + 2 + 5 )
2864 *pi_pcr = GetPCR( p_pkt );
2866 if( *pi_pcr == -1 &&
2867 (p_pkt->p_buffer[1] & 0xC0) == 0x40 && /* payload start */
2868 (p_pkt->p_buffer[3] & 0xD0) == 0x10 && /* Has payload but is not encrypted */
2869 p_pid->type == TYPE_PES &&
2870 p_pid->u.p_pes->es.fmt.i_cat != UNKNOWN_ES
2873 b_pcrresult = false;
2876 unsigned i_skip = 4;
2877 if ( b_adaptfield ) // adaptation field
2878 i_skip += 1 + p_pkt->p_buffer[4];
2880 if ( VLC_SUCCESS == ParsePESHeader( p_demux, &p_pkt->p_buffer[i_skip],
2881 p_pkt->i_buffer - i_skip,
2882 &i_skip, &i_dts, &i_pts ) )
2886 else if( i_pts != -1 )
2893 ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
2894 for( int i=0; i<p_pat->programs.i_size; i++ )
2896 ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
2897 if( ( p_pmt->i_pid_pcr == p_pid->i_pid ||
2898 ( p_pmt->i_pid_pcr == 0x1FFF && p_pid->p_parent == p_pat->programs.p_elems[i] ) ) )
2902 p_pmt->i_last_dts = *pi_pcr;
2904 /* Start, only keep first */
2905 else if( b_pcrresult && p_pmt->pcr.i_first == -1 )
2907 p_pmt->pcr.i_first = *pi_pcr;
2909 else if( p_pmt->pcr.i_first_dts < VLC_TS_0 )
2911 p_pmt->pcr.i_first_dts = FROM_SCALE(*pi_pcr);
2914 if( i_program == 0 || i_program == p_pmt->i_number )
2921 block_Release( p_pkt );
2927 static int ProbeStart( demux_t *p_demux, int i_program )
2929 demux_sys_t *p_sys = p_demux->p_sys;
2930 const int64_t i_initial_pos = stream_Tell( p_sys->stream );
2931 int64_t i_stream_size = stream_Size( p_sys->stream );
2933 int i_probe_count = 0;
2936 bool b_found = false;
2940 i_pos = p_sys->i_packet_size * i_probe_count;
2941 i_pos = __MIN( i_pos, i_stream_size );
2943 if( stream_Seek( p_sys->stream, i_pos ) )
2944 return VLC_EGENERIC;
2946 ProbeChunk( p_demux, i_program, false, &i_pcr, &b_found );
2948 /* Go ahead one more chunk if end of file contained only stuffing packets */
2949 i_probe_count += PROBE_CHUNK_COUNT;
2950 } while( i_pos > 0 && (i_pcr == -1 || !b_found) && i_probe_count < (2 * PROBE_CHUNK_COUNT) );
2952 stream_Seek( p_sys->stream, i_initial_pos );
2954 return (b_found) ? VLC_SUCCESS : VLC_EGENERIC;
2957 static int ProbeEnd( demux_t *p_demux, int i_program )
2959 demux_sys_t *p_sys = p_demux->p_sys;
2960 const int64_t i_initial_pos = stream_Tell( p_sys->stream );
2961 int64_t i_stream_size = stream_Size( p_sys->stream );
2963 int i_probe_count = PROBE_CHUNK_COUNT;
2966 bool b_found = false;
2970 i_pos = i_stream_size - (p_sys->i_packet_size * i_probe_count);
2971 i_pos = __MAX( i_pos, 0 );
2973 if( stream_Seek( p_sys->stream, i_pos ) )
2974 return VLC_EGENERIC;
2976 ProbeChunk( p_demux, i_program, true, &i_pcr, &b_found );
2978 /* Go ahead one more chunk if end of file contained only stuffing packets */
2979 i_probe_count += PROBE_CHUNK_COUNT;
2980 } while( i_pos > 0 && (i_pcr == -1 || !b_found) && i_probe_count < (6 * PROBE_CHUNK_COUNT) );
2982 stream_Seek( p_sys->stream, i_initial_pos );
2984 return (b_found) ? VLC_SUCCESS : VLC_EGENERIC;
2987 static void ProgramSetPCR( demux_t *p_demux, ts_pmt_t *p_pmt, mtime_t i_pcr )
2989 demux_sys_t *p_sys = p_demux->p_sys;
2991 /* Check if we have enqueued blocks waiting the/before the
2992 PCR barrier, and then adapt pcr so they have valid PCR when dequeuing */
2993 if( p_pmt->pcr.i_current == -1 && p_pmt->pcr.b_fix_done )
2995 mtime_t i_mindts = -1;
2997 ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
2998 for( int i=0; i< p_pat->programs.i_size; i++ )
3000 ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
3001 for( int j=0; j<p_pmt->e_streams.i_size; j++ )
3003 ts_pid_t *p_pid = p_pmt->e_streams.p_elems[j];
3004 block_t *p_block = p_pid->u.p_pes->p_prepcr_outqueue;
3005 while( p_block && p_block->i_dts == VLC_TS_INVALID )
3006 p_block = p_block->p_next;
3008 if( p_block && ( i_mindts == -1 || p_block->i_dts < i_mindts ) )
3009 i_mindts = p_block->i_dts;
3013 if( i_mindts > VLC_TS_INVALID )
3015 msg_Dbg( p_demux, "Program %d PCR prequeue fixup %"PRId64"->%"PRId64,
3016 p_pmt->i_number, TO_SCALE(i_mindts), i_pcr );
3017 i_pcr = TO_SCALE(i_mindts);
3021 p_pmt->pcr.i_current = i_pcr;
3022 if( p_pmt->pcr.i_first == -1 )
3024 p_pmt->pcr.i_first = i_pcr; // now seen
3027 if ( p_sys->i_pmt_es )
3029 es_out_Control( p_demux->out, ES_OUT_SET_GROUP_PCR,
3030 p_pmt->i_number, VLC_TS_0 + i_pcr * 100 / 9 );
3034 static void PCRHandle( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
3036 demux_sys_t *p_sys = p_demux->p_sys;
3038 if( p_sys->i_pmt_es <= 0 )
3041 mtime_t i_pcr = GetPCR( p_bk );
3045 pid->probed.i_pcr_count++;
3047 if(unlikely(PID(p_sys, 0)->type != TYPE_PAT))
3050 /* Search program and set the PCR */
3051 ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
3052 for( int i = 0; i < p_pat->programs.i_size; i++ )
3054 ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
3055 mtime_t i_program_pcr = TimeStampWrapAround( p_pmt, i_pcr );
3057 if( p_pmt->i_pid_pcr == 0x1FFF ) /* That program has no dedicated PCR pid ISO/IEC 13818-1 2.4.4.9 */
3059 if( pid->p_parent == p_pat->programs.p_elems[i] ) /* PCR shall be on pid itself */
3061 /* ? update PCR for the whole group program ? */
3062 ProgramSetPCR( p_demux, p_pmt, i_program_pcr );
3065 else /* set PCR provided by current pid to program(s) referencing it */
3067 /* Can be dedicated PCR pid (no owned then) or another pid (owner == pmt) */
3068 if( p_pmt->i_pid_pcr == pid->i_pid ) /* If that program references current pid as PCR */
3070 /* We've found a target group for update */
3071 ProgramSetPCR( p_demux, p_pmt, i_program_pcr );
3078 static int FindPCRCandidate( ts_pmt_t *p_pmt )
3080 ts_pid_t *p_cand = NULL;
3081 int i_previous = p_pmt->i_pid_pcr;
3083 for( int i=0; i<p_pmt->e_streams.i_size; i++ )
3085 ts_pid_t *p_pid = p_pmt->e_streams.p_elems[i];
3087 (!p_cand || p_cand->i_pid != i_previous) )
3089 if( p_pid->probed.i_pcr_count ) /* check PCR frequency first */
3091 if( !p_cand || p_pid->probed.i_pcr_count > p_cand->probed.i_pcr_count )
3098 if( p_pid->u.p_pes->es.fmt.i_cat == AUDIO_ES )
3103 else if ( p_pid->u.p_pes->es.fmt.i_cat == VIDEO_ES ) /* Otherwise prioritize video dts */
3105 if( !p_cand || p_cand->u.p_pes->es.fmt.i_cat == AUDIO_ES )
3112 return p_cand->i_pid;
3117 /* Tries to reselect a new PCR when none has been received */
3118 static void PCRFixHandle( demux_t *p_demux, ts_pmt_t *p_pmt, block_t *p_block )
3120 if ( p_pmt->pcr.b_disable || p_pmt->pcr.b_fix_done )
3124 /* Record the first data packet timestamp in case there wont be any PCR */
3125 else if( !p_pmt->pcr.i_first_dts )
3127 p_pmt->pcr.i_first_dts = p_block->i_dts;
3129 else if( p_block->i_dts - p_pmt->pcr.i_first_dts > CLOCK_FREQ / 2 ) /* "PCR repeat rate shall not exceed 100ms" */
3131 if( p_pmt->pcr.i_current < 0 )
3133 int i_cand = FindPCRCandidate( p_pmt );
3134 p_pmt->i_pid_pcr = i_cand;
3135 msg_Warn( p_demux, "No PCR received for program %d, set up workaround using pid %d",
3136 p_pmt->i_number, i_cand );
3137 UpdatePESFilters( p_demux, p_demux->p_sys->b_es_all );
3138 p_pmt->pcr.b_fix_done = true;
3143 static bool GatherData( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
3145 const uint8_t *p = p_bk->p_buffer;
3146 const bool b_unit_start = p[1]&0x40;
3147 const bool b_adaptation = p[3]&0x20;
3148 const bool b_payload = p[3]&0x10;
3149 const int i_cc = p[3]&0x0f; /* continuity counter */
3150 bool b_discontinuity = false; /* discontinuity */
3152 /* transport_scrambling_control is ignored */
3157 msg_Dbg( p_demux, "pid=%d unit_start=%d adaptation=%d payload=%d "
3158 "cc=0x%x", pid->i_pid, b_unit_start, b_adaptation,
3162 /* For now, ignore additional error correction
3163 * TODO: handle Reed-Solomon 204,188 error correction */
3164 p_bk->i_buffer = TS_PACKET_SIZE_188;
3168 msg_Dbg( p_demux, "transport_error_indicator set (pid=%d)",
3170 if( pid->u.p_pes->p_data ) //&& pid->es->fmt.i_cat == VIDEO_ES )
3171 pid->u.p_pes->p_data->i_flags |= BLOCK_FLAG_CORRUPTED;
3174 if( p_demux->p_sys->csa )
3176 vlc_mutex_lock( &p_demux->p_sys->csa_lock );
3177 csa_Decrypt( p_demux->p_sys->csa, p_bk->p_buffer, p_demux->p_sys->i_csa_pkt_size );
3178 vlc_mutex_unlock( &p_demux->p_sys->csa_lock );
3183 /* We don't have any adaptation_field, so payload starts
3184 * immediately after the 4 byte TS header */
3189 /* p[4] is adaptation_field_length minus one */
3193 /* discontinuity indicator found in stream */
3194 b_discontinuity = (p[5]&0x80) ? true : false;
3195 if( b_discontinuity && pid->u.p_pes->p_data )
3197 msg_Warn( p_demux, "discontinuity indicator (pid=%d) ",
3199 /* pid->es->p_data->i_flags |= BLOCK_FLAG_DISCONTINUITY; */
3203 msg_Dbg( p_demux, "random access indicator (pid=%d) ", pid->i_pid );
3208 /* Test continuity counter */
3209 /* continuous when (one of this):
3211 * diff == 0 and payload == 0
3212 * diff == 0 and duplicate packet (playload != 0) <- should we
3213 * test the content ?
3215 const int i_diff = ( i_cc - pid->i_cc )&0x0f;
3216 if( b_payload && i_diff == 1 )
3218 pid->i_cc = ( pid->i_cc + 1 ) & 0xf;
3222 if( pid->i_cc == 0xff )
3224 msg_Warn( p_demux, "first packet for pid=%d cc=0x%x",
3228 else if( i_diff != 0 && !b_discontinuity )
3230 msg_Warn( p_demux, "discontinuity received 0x%x instead of 0x%x (pid=%d)",
3231 i_cc, ( pid->i_cc + 1 )&0x0f, pid->i_pid );
3234 if( pid->u.p_pes->p_data && pid->u.p_pes->es.fmt.i_cat != VIDEO_ES &&
3235 pid->u.p_pes->es.fmt.i_cat != AUDIO_ES )
3237 /* Small audio/video artifacts are usually better than
3238 * dropping full frames */
3239 pid->u.p_pes->p_data->i_flags |= BLOCK_FLAG_CORRUPTED;
3244 PCRHandle( p_demux, pid, p_bk );
3248 block_Release( p_bk );
3252 /* We have to gather it */
3253 p_bk->p_buffer += i_skip;
3254 p_bk->i_buffer -= i_skip;
3258 if( pid->u.p_pes->data_type == TS_ES_DATA_TABLE_SECTION && p_bk->i_buffer > 0 )
3260 int i_pointer_field = __MIN( p_bk->p_buffer[0], p_bk->i_buffer - 1 );
3261 block_t *p = block_Duplicate( p_bk );
3264 p->i_buffer = i_pointer_field;
3266 block_ChainLastAppend( &pid->u.p_pes->pp_last, p );
3268 p_bk->i_buffer -= 1 + i_pointer_field;
3269 p_bk->p_buffer += 1 + i_pointer_field;
3271 if( pid->u.p_pes->p_data )
3273 ParseData( p_demux, pid );
3277 block_ChainLastAppend( &pid->u.p_pes->pp_last, p_bk );
3278 if( pid->u.p_pes->data_type == TS_ES_DATA_PES )
3280 if( p_bk->i_buffer > 6 )
3282 pid->u.p_pes->i_data_size = GetWBE( &p_bk->p_buffer[4] );
3283 if( pid->u.p_pes->i_data_size > 0 )
3285 pid->u.p_pes->i_data_size += 6;
3289 else if( pid->u.p_pes->data_type == TS_ES_DATA_TABLE_SECTION )
3291 if( p_bk->i_buffer > 3 && p_bk->p_buffer[0] != 0xff )
3293 pid->u.p_pes->i_data_size = 3 + (((p_bk->p_buffer[1] & 0xf) << 8) | p_bk->p_buffer[2]);
3296 pid->u.p_pes->i_data_gathered += p_bk->i_buffer;
3297 if( pid->u.p_pes->i_data_size > 0 &&
3298 pid->u.p_pes->i_data_gathered >= pid->u.p_pes->i_data_size )
3300 ParseData( p_demux, pid );
3306 if( pid->u.p_pes->p_data == NULL )
3308 /* msg_Dbg( p_demux, "broken packet" ); */
3309 block_Release( p_bk );
3313 block_ChainLastAppend( &pid->u.p_pes->pp_last, p_bk );
3314 pid->u.p_pes->i_data_gathered += p_bk->i_buffer;
3316 if( pid->u.p_pes->i_data_size > 0 &&
3317 pid->u.p_pes->i_data_gathered >= pid->u.p_pes->i_data_size )
3319 ParseData( p_demux, pid );
3328 static void PIDFillFormat( es_format_t *fmt, int i_stream_type )
3330 switch( i_stream_type )
3332 case 0x01: /* MPEG-1 video */
3333 case 0x02: /* MPEG-2 video */
3334 case 0x80: /* MPEG-2 MOTO video */
3335 es_format_Init( fmt, VIDEO_ES, VLC_CODEC_MPGV );
3337 case 0x03: /* MPEG-1 audio */
3338 case 0x04: /* MPEG-2 audio */
3339 es_format_Init( fmt, AUDIO_ES, VLC_CODEC_MPGA );
3341 case 0x11: /* MPEG4 (audio) LATM */
3342 case 0x0f: /* ISO/IEC 13818-7 Audio with ADTS transport syntax */
3343 case 0x1c: /* ISO/IEC 14496-3 Audio, without using any additional
3344 transport syntax, such as DST, ALS and SLS */
3345 es_format_Init( fmt, AUDIO_ES, VLC_CODEC_MP4A );
3347 case 0x10: /* MPEG4 (video) */
3348 es_format_Init( fmt, VIDEO_ES, VLC_CODEC_MP4V );
3350 case 0x1B: /* H264 <- check transport syntax/needed descriptor */
3351 es_format_Init( fmt, VIDEO_ES, VLC_CODEC_H264 );
3353 case 0x24: /* HEVC */
3354 es_format_Init( fmt, VIDEO_ES, VLC_CODEC_HEVC );
3356 case 0x42: /* CAVS (Chinese AVS) */
3357 es_format_Init( fmt, VIDEO_ES, VLC_CODEC_CAVS );
3360 case 0x81: /* A52 (audio) */
3361 es_format_Init( fmt, AUDIO_ES, VLC_CODEC_A52 );
3363 case 0x82: /* SCTE-27 (sub) */
3364 es_format_Init( fmt, SPU_ES, VLC_CODEC_SCTE_27 );
3366 case 0x84: /* SDDS (audio) */
3367 es_format_Init( fmt, AUDIO_ES, VLC_CODEC_SDDS );
3369 case 0x85: /* DTS (audio) */
3370 es_format_Init( fmt, AUDIO_ES, VLC_CODEC_DTS );
3372 case 0x87: /* E-AC3 */
3373 es_format_Init( fmt, AUDIO_ES, VLC_CODEC_EAC3 );
3376 case 0x91: /* A52 vls (audio) */
3377 es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'a', '5', '2', 'b' ) );
3379 case 0x92: /* DVD_SPU vls (sub) */
3380 es_format_Init( fmt, SPU_ES, VLC_FOURCC( 's', 'p', 'u', 'b' ) );
3383 case 0x94: /* SDDS (audio) */
3384 es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 's', 'd', 'd', 'b' ) );
3387 case 0xa0: /* MSCODEC vlc (video) (fixed later) */
3388 es_format_Init( fmt, UNKNOWN_ES, 0 );
3391 case 0x06: /* PES_PRIVATE (fixed later) */
3392 case 0x12: /* MPEG-4 generic (sub/scene/...) (fixed later) */
3393 case 0xEA: /* Privately managed ES (VC-1) (fixed later */
3395 es_format_Init( fmt, UNKNOWN_ES, 0 );
3399 /* PES packets usually contain truncated frames */
3400 fmt->b_packetized = false;
3403 /*****************************************************************************
3404 * MP4 specific functions (IOD parser)
3405 *****************************************************************************/
3406 static unsigned IODDescriptorLength( unsigned *pi_data, uint8_t **pp_data )
3409 unsigned int i_len = 0;
3415 i_len = ( i_len << 7 ) + ( i_b&0x7f );
3417 } while( i_b&0x80 && *pi_data > 0 );
3419 if (i_len > *pi_data)
3425 static unsigned IODGetBytes( unsigned *pi_data, uint8_t **pp_data, size_t bytes )
3428 while( *pi_data > 0 && bytes-- )
3439 static char* IODGetURL( unsigned *pi_data, uint8_t **pp_data )
3441 unsigned len = IODGetBytes( pi_data, pp_data, 1 );
3444 char *url = strndup( (char*)*pp_data, len );
3450 static iod_descriptor_t *IODNew( unsigned i_data, uint8_t *p_data )
3452 uint8_t i_iod_tag, i_iod_label, byte1, byte2, byte3;
3454 iod_descriptor_t *p_iod = calloc( 1, sizeof( iod_descriptor_t ) );
3463 byte1 = IODGetBytes( &i_data, &p_data, 1 );
3464 byte2 = IODGetBytes( &i_data, &p_data, 1 );
3465 byte3 = IODGetBytes( &i_data, &p_data, 1 );
3466 if( byte2 == 0x02 ) //old vlc's buggy implementation of the IOD_descriptor
3468 i_iod_label = byte1;
3471 else //correct implementation of the IOD_descriptor
3473 i_iod_label = byte2;
3477 ts_debug( "\n* iod label:%d tag:0x%x", i_iod_label, i_iod_tag );
3479 if( i_iod_tag != 0x02 )
3481 ts_debug( "\n ERR: tag %02x != 0x02", i_iod_tag );
3485 IODDescriptorLength( &i_data, &p_data );
3487 uint16_t i_od_id = ( IODGetBytes( &i_data, &p_data, 1 ) << 2 );
3488 uint8_t i_flags = IODGetBytes( &i_data, &p_data, 1 );
3489 i_od_id |= i_flags >> 6;
3490 ts_debug( "\n* od_id:%d", i_od_id );
3491 ts_debug( "\n* includeInlineProfileLevel flag:%d", ( i_flags >> 4 )&0x01 );
3492 if ((i_flags >> 5) & 0x01)
3494 p_iod->psz_url = IODGetURL( &i_data, &p_data );
3495 ts_debug( "\n* url string:%s", p_iod->psz_url );
3496 ts_debug( "\n*****************************\n" );
3501 p_iod->psz_url = NULL;
3504 /* Profile Level Indication */
3505 IODGetBytes( &i_data, &p_data, 1 ); /* OD */
3506 IODGetBytes( &i_data, &p_data, 1 ); /* scene */
3507 IODGetBytes( &i_data, &p_data, 1 ); /* audio */
3508 IODGetBytes( &i_data, &p_data, 1 ); /* visual */
3509 IODGetBytes( &i_data, &p_data, 1 ); /* graphics */
3511 unsigned i_length = 0;
3512 unsigned i_data_sav = i_data;
3513 uint8_t *p_data_sav = p_data;
3514 for (unsigned i = 0; i_data > 0 && i < ES_DESCRIPTOR_COUNT; i++)
3516 es_mpeg4_descriptor_t *es_descr = &p_iod->es_descr[i];
3518 p_data = p_data_sav + i_length;
3519 i_data = i_data_sav - i_length;
3521 uint8_t i_tag = IODGetBytes( &i_data, &p_data, 1 );
3522 i_length = IODDescriptorLength( &i_data, &p_data );
3524 i_data_sav = i_data;
3525 p_data_sav = p_data;
3529 if ( i_tag != 0x03 )
3531 ts_debug( "\n* - OD tag:0x%x Unsupported", i_tag );
3535 es_descr->i_es_id = IODGetBytes( &i_data, &p_data, 2 );
3536 uint8_t i_flags = IODGetBytes( &i_data, &p_data, 1 );
3537 bool b_streamDependenceFlag = ( i_flags >> 7 )&0x01;
3538 if( b_streamDependenceFlag )
3539 IODGetBytes( &i_data, &p_data, 2 ); /* dependOn_es_id */
3541 if( (i_flags >> 6) & 0x01 )
3542 es_descr->psz_url = IODGetURL( &i_data, &p_data );
3544 bool b_OCRStreamFlag = ( i_flags >> 5 )&0x01;
3545 if( b_OCRStreamFlag )
3546 IODGetBytes( &i_data, &p_data, 2 ); /* OCR_es_id */
3548 if( IODGetBytes( &i_data, &p_data, 1 ) != 0x04 )
3550 ts_debug( "\n* ERR missing DecoderConfigDescr" );
3553 unsigned i_config_desc_length = IODDescriptorLength( &i_data, &p_data ); /* DecoderConfigDescr_length */
3554 decoder_config_descriptor_t *dec_descr = &es_descr->dec_descr;
3555 dec_descr->i_objectTypeIndication = IODGetBytes( &i_data, &p_data, 1 );
3556 i_flags = IODGetBytes( &i_data, &p_data, 1 );
3557 dec_descr->i_streamType = i_flags >> 2;
3559 IODGetBytes( &i_data, &p_data, 3); /* bufferSizeDB */
3560 IODGetBytes( &i_data, &p_data, 4); /* maxBitrate */
3561 IODGetBytes( &i_data, &p_data, 4 ); /* avgBitrate */
3563 if( i_config_desc_length > 13 && IODGetBytes( &i_data, &p_data, 1 ) == 0x05 )
3565 dec_descr->i_extra = IODDescriptorLength( &i_data, &p_data );
3566 if( dec_descr->i_extra > 0 )
3568 dec_descr->p_extra = xmalloc( dec_descr->i_extra );
3569 memcpy(dec_descr->p_extra, p_data, dec_descr->i_extra);
3570 p_data += dec_descr->i_extra;
3571 i_data -= dec_descr->i_extra;
3576 dec_descr->i_extra = 0;
3577 dec_descr->p_extra = NULL;
3580 if( IODGetBytes( &i_data, &p_data, 1 ) != 0x06 )
3582 ts_debug( "\n* ERR missing SLConfigDescr" );
3585 IODDescriptorLength( &i_data, &p_data ); /* SLConfigDescr_length */
3586 switch( IODGetBytes( &i_data, &p_data, 1 ) /* predefined */ )
3589 ts_debug( "\n* ERR unsupported SLConfigDescr predefined" );
3594 es_descr->b_ok = true;
3600 static void IODFree( iod_descriptor_t *p_iod )
3602 if( p_iod->psz_url )
3604 free( p_iod->psz_url );
3609 for( int i = 0; i < 255; i++ )
3611 #define es_descr p_iod->es_descr[i]
3614 if( es_descr.psz_url )
3615 free( es_descr.psz_url );
3617 free( es_descr.dec_descr.p_extra );
3624 /****************************************************************************
3625 ****************************************************************************
3626 ** libdvbpsi callbacks
3627 ****************************************************************************
3628 ****************************************************************************/
3629 static bool ProgramIsSelected( demux_sys_t *p_sys, uint16_t i_pgrm )
3631 for(int i=0; i<p_sys->programs.i_size; i++)
3632 if( p_sys->programs.p_elems[i] == i_pgrm )
3638 static void ValidateDVBMeta( demux_t *p_demux, int i_pid )
3640 demux_sys_t *p_sys = p_demux->p_sys;
3642 if( !p_sys->b_dvb_meta || ( i_pid != 0x11 && i_pid != 0x12 && i_pid != 0x14 ) )
3645 msg_Warn( p_demux, "Switching to non DVB mode" );
3647 /* This doesn't look like a DVB stream so don't try
3648 * parsing the SDT/EDT/TDT */
3650 PIDRelease( p_demux, PID(p_sys, 0x11) );
3651 PIDRelease( p_demux, PID(p_sys, 0x12) );
3652 PIDRelease( p_demux, PID(p_sys, 0x14) );
3653 p_sys->b_dvb_meta = false;
3656 #include "dvb-text.h"
3658 static char *EITConvertToUTF8( demux_t *p_demux,
3659 const unsigned char *psz_instring,
3663 demux_sys_t *p_sys = p_demux->p_sys;
3665 if( p_sys->arib.e_mode == ARIBMODE_ENABLED )
3667 if ( !p_sys->arib.p_instance )
3668 p_sys->arib.p_instance = arib_instance_new( p_demux );
3669 if ( !p_sys->arib.p_instance )
3671 arib_decoder_t *p_decoder = arib_get_decoder( p_sys->arib.p_instance );
3675 char *psz_outstring = NULL;
3678 i_out = i_length * 4;
3679 psz_outstring = (char*) calloc( i_out + 1, sizeof(char) );
3680 if( !psz_outstring )
3683 arib_initialize_decoder( p_decoder );
3684 i_out = arib_decode_buffer( p_decoder, psz_instring, i_length,
3685 psz_outstring, i_out );
3686 arib_finalize_decoder( p_decoder );
3688 return psz_outstring;
3693 /* Deal with no longer broken providers (no switch byte
3694 but sending ISO_8859-1 instead of ISO_6937) without
3695 removing them from the broken providers table
3696 (keep the entry for correctly handling recorded TS).
3698 b_broken = b_broken && i_length && *psz_instring > 0x20;
3701 return FromCharset( "ISO_8859-1", psz_instring, i_length );
3702 return vlc_from_EIT( psz_instring, i_length );
3705 static void SDTCallBack( demux_t *p_demux, dvbpsi_sdt_t *p_sdt )
3707 demux_sys_t *p_sys = p_demux->p_sys;
3708 ts_pid_t *sdt = PID(p_sys, 0x11);
3709 dvbpsi_sdt_service_t *p_srv;
3711 msg_Dbg( p_demux, "SDTCallBack called" );
3713 if( p_sys->es_creation != CREATE_ES ||
3714 !p_sdt->b_current_next ||
3715 p_sdt->i_version == sdt->u.p_psi->i_version )
3717 dvbpsi_sdt_delete( p_sdt );
3721 msg_Dbg( p_demux, "new SDT ts_id=%d version=%d current_next=%d "
3724 p_sdt->i_version, p_sdt->b_current_next,
3725 p_sdt->i_network_id );
3727 p_sys->b_broken_charset = false;
3729 for( p_srv = p_sdt->p_first_service; p_srv; p_srv = p_srv->p_next )
3732 dvbpsi_descriptor_t *p_dr;
3734 const char *psz_type = NULL;
3735 const char *psz_status = NULL;
3737 msg_Dbg( p_demux, " * service id=%d eit schedule=%d present=%d "
3738 "running=%d free_ca=%d",
3739 p_srv->i_service_id, p_srv->b_eit_schedule,
3740 p_srv->b_eit_present, p_srv->i_running_status,
3743 if( p_sys->vdr.i_service && p_srv->i_service_id != p_sys->vdr.i_service )
3745 msg_Dbg( p_demux, " * service id=%d skipped (not declared in vdr header)",
3746 p_sys->vdr.i_service );
3750 p_meta = vlc_meta_New();
3751 for( p_dr = p_srv->p_first_descriptor; p_dr; p_dr = p_dr->p_next )
3753 if( p_dr->i_tag == 0x48 )
3755 static const char *ppsz_type[17] = {
3757 "Digital television service",
3758 "Digital radio sound service",
3760 "NVOD reference service",
3761 "NVOD time-shifted service",
3764 "SECAM coded signal",
3767 "NTSC coded signal",
3768 "Data broadcast service",
3769 "Reserved for Common Interface Usage",
3770 "RCS Map (see EN 301 790 [35])",
3771 "RCS FLS (see EN 301 790 [35])",
3774 dvbpsi_service_dr_t *pD = dvbpsi_DecodeServiceDr( p_dr );
3778 /* Workarounds for broadcasters with broken EPG */
3780 if( p_sdt->i_network_id == 133 )
3781 p_sys->b_broken_charset = true; /* SKY DE & BetaDigital use ISO8859-1 */
3783 /* List of providers using ISO8859-1 */
3784 static const char ppsz_broken_providers[][8] = {
3785 "CSAT", /* CanalSat FR */
3786 "GR1", /* France televisions */
3788 "MR5", /* France 2/M6 HD */
3791 for( int i = 0; *ppsz_broken_providers[i]; i++ )
3793 const size_t i_length = strlen(ppsz_broken_providers[i]);
3794 if( pD->i_service_provider_name_length == i_length &&
3795 !strncmp( (char *)pD->i_service_provider_name, ppsz_broken_providers[i], i_length ) )
3796 p_sys->b_broken_charset = true;
3799 /* FIXME: Digital+ ES also uses ISO8859-1 */
3801 str1 = EITConvertToUTF8(p_demux,
3802 pD->i_service_provider_name,
3803 pD->i_service_provider_name_length,
3804 p_sys->b_broken_charset );
3805 str2 = EITConvertToUTF8(p_demux,
3807 pD->i_service_name_length,
3808 p_sys->b_broken_charset );
3810 msg_Dbg( p_demux, " - type=%d provider=%s name=%s",
3811 pD->i_service_type, str1, str2 );
3813 vlc_meta_SetTitle( p_meta, str2 );
3814 vlc_meta_SetPublisher( p_meta, str1 );
3815 if( pD->i_service_type >= 0x01 && pD->i_service_type <= 0x10 )
3816 psz_type = ppsz_type[pD->i_service_type];
3822 if( p_srv->i_running_status >= 0x01 && p_srv->i_running_status <= 0x04 )
3824 static const char *ppsz_status[5] = {
3827 "Starts in a few seconds",
3831 psz_status = ppsz_status[p_srv->i_running_status];
3835 vlc_meta_AddExtra( p_meta, "Type", psz_type );
3837 vlc_meta_AddExtra( p_meta, "Status", psz_status );
3839 es_out_Control( p_demux->out, ES_OUT_SET_GROUP_META,
3840 p_srv->i_service_id, p_meta );
3841 vlc_meta_Delete( p_meta );
3844 sdt->u.p_psi->i_version = p_sdt->i_version;
3845 dvbpsi_sdt_delete( p_sdt );
3848 /* i_year: year - 1900 i_month: 0-11 i_mday: 1-31 i_hour: 0-23 i_minute: 0-59 i_second: 0-59 */
3849 static int64_t vlc_timegm( int i_year, int i_month, int i_mday, int i_hour, int i_minute, int i_second )
3851 static const int pn_day[12+1] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
3855 i_month < 0 || i_month > 11 || i_mday < 1 || i_mday > 31 ||
3856 i_hour < 0 || i_hour > 23 || i_minute < 0 || i_minute > 59 || i_second < 0 || i_second > 59 )
3859 /* Count the number of days */
3860 i_day = 365 * (i_year-70) + pn_day[i_month] + i_mday - 1;
3861 #define LEAP(y) ( ((y)%4) == 0 && (((y)%100) != 0 || ((y)%400) == 0) ? 1 : 0)
3862 for( int i = 70; i < i_year; i++ )
3863 i_day += LEAP(1900+i);
3865 i_day += LEAP(1900+i_year);
3868 return ((24*i_day + i_hour)*60 + i_minute)*60 + i_second;
3871 static void EITDecodeMjd( int i_mjd, int *p_y, int *p_m, int *p_d )
3873 const int yp = (int)( ( (double)i_mjd - 15078.2)/365.25 );
3874 const int mp = (int)( ((double)i_mjd - 14956.1 - (int)(yp * 365.25)) / 30.6001 );
3875 const int c = ( mp == 14 || mp == 15 ) ? 1 : 0;
3877 *p_y = 1900 + yp + c*1;
3878 *p_m = mp - 1 - c*12;
3879 *p_d = i_mjd - 14956 - (int)(yp*365.25) - (int)(mp*30.6001);
3881 #define CVT_FROM_BCD(v) ((((v) >> 4)&0xf)*10 + ((v)&0xf))
3882 static int64_t EITConvertStartTime( uint64_t i_date )
3884 const int i_mjd = i_date >> 24;
3885 const int i_hour = CVT_FROM_BCD(i_date >> 16);
3886 const int i_minute = CVT_FROM_BCD(i_date >> 8);
3887 const int i_second = CVT_FROM_BCD(i_date );
3892 /* if all 40 bits are 1, the start is unknown */
3893 if( i_date == UINT64_C(0xffffffffff) )
3896 EITDecodeMjd( i_mjd, &i_year, &i_month, &i_day );
3897 return vlc_timegm( i_year - 1900, i_month - 1, i_day, i_hour, i_minute, i_second );
3899 static int EITConvertDuration( uint32_t i_duration )
3901 return CVT_FROM_BCD(i_duration >> 16) * 3600 +
3902 CVT_FROM_BCD(i_duration >> 8 ) * 60 +
3903 CVT_FROM_BCD(i_duration );
3907 static void TDTCallBack( demux_t *p_demux, dvbpsi_tot_t *p_tdt )
3909 demux_sys_t *p_sys = p_demux->p_sys;
3911 p_sys->i_tdt_delta = CLOCK_FREQ * EITConvertStartTime( p_tdt->i_utc_time )
3913 dvbpsi_tot_delete(p_tdt);
3917 static void EITCallBack( demux_t *p_demux,
3918 dvbpsi_eit_t *p_eit, bool b_current_following )
3920 demux_sys_t *p_sys = p_demux->p_sys;
3921 dvbpsi_eit_event_t *p_evt;
3924 msg_Dbg( p_demux, "EITCallBack called" );
3925 if( !p_eit->b_current_next )
3927 dvbpsi_eit_delete( p_eit );
3931 msg_Dbg( p_demux, "new EIT service_id=%d version=%d current_next=%d "
3932 "ts_id=%d network_id=%d segment_last_section_number=%d "
3935 p_eit->i_version, p_eit->b_current_next,
3936 p_eit->i_ts_id, p_eit->i_network_id,
3937 p_eit->i_segment_last_section_number, p_eit->i_last_table_id );
3939 p_epg = vlc_epg_New( NULL );
3940 for( p_evt = p_eit->p_first_event; p_evt; p_evt = p_evt->p_next )
3942 dvbpsi_descriptor_t *p_dr;
3943 char *psz_name = NULL;
3944 char *psz_text = NULL;
3945 char *psz_extra = strdup("");
3949 int64_t i_tot_time = 0;
3951 i_start = EITConvertStartTime( p_evt->i_start_time );
3952 i_duration = EITConvertDuration( p_evt->i_duration );
3954 if( p_sys->arib.e_mode == ARIBMODE_ENABLED )
3956 if( p_sys->i_tdt_delta == 0 )
3957 p_sys->i_tdt_delta = CLOCK_FREQ * (i_start + i_duration - 5) - mdate();
3959 i_tot_time = (mdate() + p_sys->i_tdt_delta) / CLOCK_FREQ;
3961 tzset(); // JST -> UTC
3962 i_start += timezone; // FIXME: what about DST?
3963 i_tot_time += timezone;
3965 if( p_evt->i_running_status == 0x00 &&
3966 (i_start - 5 < i_tot_time &&
3967 i_tot_time < i_start + i_duration + 5) )
3969 p_evt->i_running_status = 0x04;
3970 msg_Dbg( p_demux, " EIT running status 0x00 -> 0x04" );
3974 msg_Dbg( p_demux, " * event id=%d start_time:%d duration=%d "
3975 "running=%d free_ca=%d",
3976 p_evt->i_event_id, (int)i_start, (int)i_duration,
3977 p_evt->i_running_status, p_evt->b_free_ca );
3979 for( p_dr = p_evt->p_first_descriptor; p_dr; p_dr = p_dr->p_next )
3985 dvbpsi_short_event_dr_t *pE = dvbpsi_DecodeShortEventDr( p_dr );
3987 /* Only take first description, as we don't handle language-info
3989 if( pE && psz_name == NULL )
3991 psz_name = EITConvertToUTF8( p_demux,
3992 pE->i_event_name, pE->i_event_name_length,
3993 p_sys->b_broken_charset );
3995 psz_text = EITConvertToUTF8( p_demux,
3996 pE->i_text, pE->i_text_length,
3997 p_sys->b_broken_charset );
3998 msg_Dbg( p_demux, " - short event lang=%3.3s '%s' : '%s'",
3999 pE->i_iso_639_code, psz_name, psz_text );
4006 dvbpsi_extended_event_dr_t *pE = dvbpsi_DecodeExtendedEventDr( p_dr );
4009 msg_Dbg( p_demux, " - extended event lang=%3.3s [%d/%d]",
4011 pE->i_descriptor_number, pE->i_last_descriptor_number );
4013 if( pE->i_text_length > 0 )
4015 char *psz_text = EITConvertToUTF8( p_demux,
4016 pE->i_text, pE->i_text_length,
4017 p_sys->b_broken_charset );
4020 msg_Dbg( p_demux, " - text='%s'", psz_text );
4022 psz_extra = xrealloc( psz_extra,
4023 strlen(psz_extra) + strlen(psz_text) + 1 );
4024 strcat( psz_extra, psz_text );
4029 for( int i = 0; i < pE->i_entry_count; i++ )
4031 char *psz_dsc = EITConvertToUTF8( p_demux,
4032 pE->i_item_description[i],
4033 pE->i_item_description_length[i],
4034 p_sys->b_broken_charset );
4035 char *psz_itm = EITConvertToUTF8( p_demux,
4036 pE->i_item[i], pE->i_item_length[i],
4037 p_sys->b_broken_charset );
4039 if( psz_dsc && psz_itm )
4041 msg_Dbg( p_demux, " - desc='%s' item='%s'", psz_dsc, psz_itm );
4043 psz_extra = xrealloc( psz_extra,
4044 strlen(psz_extra) + strlen(psz_dsc) +
4045 strlen(psz_itm) + 3 + 1 );
4046 strcat( psz_extra, "(" );
4047 strcat( psz_extra, psz_dsc );
4048 strcat( psz_extra, " " );
4049 strcat( psz_extra, psz_itm );
4050 strcat( psz_extra, ")" );
4062 dvbpsi_parental_rating_dr_t *pR = dvbpsi_DecodeParentalRatingDr( p_dr );
4065 for ( int i = 0; i < pR->i_ratings_number; i++ )
4067 const dvbpsi_parental_rating_t *p_rating = & pR->p_parental_rating[ i ];
4068 if ( p_rating->i_rating > 0x00 && p_rating->i_rating <= 0x0F )
4070 if ( p_rating->i_rating + 3 > i_min_age )
4071 i_min_age = p_rating->i_rating + 3;
4072 msg_Dbg( p_demux, " - parental control set to %d years",
4081 msg_Dbg( p_demux, " - event unknown dr 0x%x(%d)", p_dr->i_tag, p_dr->i_tag );
4087 if( i_start > 0 && psz_name && psz_text)
4088 vlc_epg_AddEvent( p_epg, i_start, i_duration, psz_name, psz_text,
4089 *psz_extra ? psz_extra : NULL, i_min_age );
4091 /* Update "now playing" field */
4092 if( p_evt->i_running_status == 0x04 && i_start > 0 && psz_name && psz_text )
4093 vlc_epg_SetCurrent( p_epg, i_start );
4100 if( p_epg->i_event > 0 )
4102 if( b_current_following &&
4103 ( p_sys->programs.i_size == 0 ||
4104 p_sys->programs.p_elems[0] ==
4108 p_sys->i_dvb_length = 0;
4109 p_sys->i_dvb_start = 0;
4111 if( p_epg->p_current )
4113 p_sys->i_dvb_start = CLOCK_FREQ * p_epg->p_current->i_start;
4114 p_sys->i_dvb_length = CLOCK_FREQ * p_epg->p_current->i_duration;
4117 es_out_Control( p_demux->out, ES_OUT_SET_GROUP_EPG,
4121 vlc_epg_Delete( p_epg );
4123 dvbpsi_eit_delete( p_eit );
4125 static void EITCallBackCurrentFollowing( demux_t *p_demux, dvbpsi_eit_t *p_eit )
4127 EITCallBack( p_demux, p_eit, true );
4129 static void EITCallBackSchedule( demux_t *p_demux, dvbpsi_eit_t *p_eit )
4131 EITCallBack( p_demux, p_eit, false );
4134 static void PSINewTableCallBack( dvbpsi_t *h, uint8_t i_table_id,
4135 uint16_t i_extension, demux_t *p_demux )
4137 demux_sys_t *p_sys = p_demux->p_sys;
4140 msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
4141 i_table_id, i_table_id, i_extension, i_extension );
4143 if( PID(p_sys, 0)->u.p_pat->i_version != -1 && i_table_id == 0x42 )
4145 msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
4146 i_table_id, i_table_id, i_extension, i_extension );
4148 if( !dvbpsi_sdt_attach( h, i_table_id, i_extension, (dvbpsi_sdt_callback)SDTCallBack, p_demux ) )
4149 msg_Err( p_demux, "PSINewTableCallback: failed attaching SDTCallback" );
4151 else if( PID(p_sys, 0x11)->u.p_psi->i_version != -1 &&
4152 ( i_table_id == 0x4e || /* Current/Following */
4153 (i_table_id >= 0x50 && i_table_id <= 0x5f) ) ) /* Schedule */
4155 msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
4156 i_table_id, i_table_id, i_extension, i_extension );
4158 dvbpsi_eit_callback cb = i_table_id == 0x4e ?
4159 (dvbpsi_eit_callback)EITCallBackCurrentFollowing :
4160 (dvbpsi_eit_callback)EITCallBackSchedule;
4162 if( !dvbpsi_eit_attach( h, i_table_id, i_extension, cb, p_demux ) )
4163 msg_Err( p_demux, "PSINewTableCallback: failed attaching EITCallback" );
4165 else if( PID(p_sys, 0x11)->u.p_psi->i_version != -1 &&
4166 (i_table_id == 0x70 /* TDT */ || i_table_id == 0x73 /* TOT */) )
4168 msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
4169 i_table_id, i_table_id, i_extension, i_extension );
4171 if( !dvbpsi_tot_attach( h, i_table_id, i_extension, (dvbpsi_tot_callback)TDTCallBack, p_demux ) )
4172 msg_Err( p_demux, "PSINewTableCallback: failed attaching TDTCallback" );
4176 /*****************************************************************************
4177 * PMT callback and helpers
4178 *****************************************************************************/
4179 static dvbpsi_descriptor_t *PMTEsFindDescriptor( const dvbpsi_pmt_es_t *p_es,
4182 dvbpsi_descriptor_t *p_dr = p_es->p_first_descriptor;;
4183 while( p_dr && ( p_dr->i_tag != i_tag ) )
4184 p_dr = p_dr->p_next;
4187 static bool PMTEsHasRegistration( demux_t *p_demux,
4188 const dvbpsi_pmt_es_t *p_es,
4189 const char *psz_tag )
4191 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x05 );
4195 if( p_dr->i_length < 4 )
4197 msg_Warn( p_demux, "invalid Registration Descriptor" );
4201 assert( strlen(psz_tag) == 4 );
4202 return !memcmp( p_dr->p_data, psz_tag, 4 );
4205 static bool PMTEsHasComponentTag( const dvbpsi_pmt_es_t *p_es,
4206 int i_component_tag )
4208 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x52 );
4211 dvbpsi_stream_identifier_dr_t *p_si = dvbpsi_DecodeStreamIdentifierDr( p_dr );
4215 return p_si->i_component_tag == i_component_tag;
4218 static const es_mpeg4_descriptor_t * GetMPEG4DescByEsId( const iod_descriptor_t *iod,
4222 for( int i = 0; i < ES_DESCRIPTOR_COUNT; i++ )
4224 if( iod->es_descr[i].i_es_id == i_es_id )
4226 if ( iod->es_descr[i].b_ok )
4227 return &iod->es_descr[i];
4233 static void PMTSetupEsISO14496( demux_t *p_demux, ts_pes_es_t *p_es,
4234 const ts_pmt_t *p_pmt, const dvbpsi_pmt_es_t *p_dvbpsies )
4236 es_format_t *p_fmt = &p_es->fmt;
4238 const dvbpsi_descriptor_t *p_dr = p_dvbpsies->p_first_descriptor;
4241 const es_mpeg4_descriptor_t *p_esdescr = NULL;
4243 uint8_t i_length = p_dr->i_length;
4245 switch( p_dr->i_tag )
4247 case 0x1f: /* FMC Descriptor */
4248 while( i_length >= 3 && !p_esdescr )
4250 i_es_id = ( p_dr->p_data[0] << 8 ) | p_dr->p_data[1];
4251 p_esdescr = GetMPEG4DescByEsId( p_pmt->iod, i_es_id );
4252 /* FIXME: add flexmux channel */
4255 msg_Dbg( p_demux, "found FMC_descriptor declaring sl packetization on es_id=%"PRIu16, i_es_id );
4258 case 0x1e: /* SL Descriptor */
4261 i_es_id = ( p_dr->p_data[0] << 8 ) | p_dr->p_data[1];
4262 p_esdescr = GetMPEG4DescByEsId( p_pmt->iod, i_es_id );
4264 msg_Dbg( p_demux, "found SL_descriptor declaring sl packetization on es_id=%"PRIu16, i_es_id );
4273 if( !p_esdescr->b_ok )
4275 msg_Dbg( p_demux, "MPEG-4 descriptor not yet available on es_id=%"PRIu16, i_es_id );
4279 p_es->p_mpeg4desc = p_esdescr;
4284 p_dr = p_dr->p_next;
4287 if( !p_es->p_mpeg4desc )
4289 switch( p_dvbpsies->i_type )
4291 /* non fatal, set by packetizer */
4292 case 0x0f: /* ADTS */
4293 case 0x11: /* LOAS */
4294 msg_Info( p_demux, "MPEG-4 descriptor not found for pid 0x%x type 0x%x",
4295 p_dvbpsies->i_pid, p_dvbpsies->i_type );
4298 msg_Err( p_demux, "MPEG-4 descriptor not found for pid 0x%x type 0x%x",
4299 p_dvbpsies->i_pid, p_dvbpsies->i_type );
4305 const decoder_config_descriptor_t *dcd = &p_es->p_mpeg4desc->dec_descr;
4306 if( dcd->i_streamType == 0x04 ) /* VisualStream */
4308 p_fmt->i_cat = VIDEO_ES;
4309 switch( dcd->i_objectTypeIndication )
4311 case 0x0B: /* mpeg4 sub */
4312 p_fmt->i_cat = SPU_ES;
4313 p_fmt->i_codec = VLC_CODEC_SUBT;
4316 case 0x20: /* mpeg4 */
4317 p_fmt->i_codec = VLC_CODEC_MP4V;
4319 case 0x21: /* h264 */
4320 p_fmt->i_codec = VLC_CODEC_H264;
4327 case 0x65: /* mpeg2 */
4328 p_fmt->i_codec = VLC_CODEC_MPGV;
4330 case 0x6a: /* mpeg1 */
4331 p_fmt->i_codec = VLC_CODEC_MPGV;
4333 case 0x6c: /* mpeg1 */
4334 p_fmt->i_codec = VLC_CODEC_JPEG;
4337 p_fmt->i_cat = UNKNOWN_ES;
4341 else if( dcd->i_streamType == 0x05 ) /* AudioStream */
4343 p_fmt->i_cat = AUDIO_ES;
4344 switch( dcd->i_objectTypeIndication )
4346 case 0x40: /* mpeg4 */
4347 p_fmt->i_codec = VLC_CODEC_MP4A;
4351 case 0x68: /* mpeg2 aac */
4352 p_fmt->i_codec = VLC_CODEC_MP4A;
4354 case 0x69: /* mpeg2 */
4355 p_fmt->i_codec = VLC_CODEC_MPGA;
4357 case 0x6b: /* mpeg1 */
4358 p_fmt->i_codec = VLC_CODEC_MPGA;
4361 p_fmt->i_cat = UNKNOWN_ES;
4367 p_fmt->i_cat = UNKNOWN_ES;
4370 if( p_fmt->i_cat != UNKNOWN_ES )
4372 p_fmt->i_extra = __MIN(dcd->i_extra, INT32_MAX);
4373 if( p_fmt->i_extra > 0 )
4375 p_fmt->p_extra = malloc( p_fmt->i_extra );
4376 if( p_fmt->p_extra )
4377 memcpy( p_fmt->p_extra, dcd->p_extra, p_fmt->i_extra );
4390 } ts_teletext_page_t;
4392 static void PMTSetupEsTeletext( demux_t *p_demux, ts_pes_t *p_pes,
4393 const dvbpsi_pmt_es_t *p_dvbpsies )
4395 es_format_t *p_fmt = &p_pes->es.fmt;
4397 ts_teletext_page_t p_page[2 * 64 + 20];
4398 unsigned i_page = 0;
4400 /* Gather pages information */
4401 for( unsigned i_tag_idx = 0; i_tag_idx < 2; i_tag_idx++ )
4403 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, i_tag_idx == 0 ? 0x46 : 0x56 );
4407 dvbpsi_teletext_dr_t *p_sub = dvbpsi_DecodeTeletextDr( p_dr );
4411 for( int i = 0; i < p_sub->i_pages_number; i++ )
4413 const dvbpsi_teletextpage_t *p_src = &p_sub->p_pages[i];
4415 if( p_src->i_teletext_type >= 0x06 )
4418 assert( i_page < sizeof(p_page)/sizeof(*p_page) );
4420 ts_teletext_page_t *p_dst = &p_page[i_page++];
4422 p_dst->i_type = p_src->i_teletext_type;
4423 p_dst->i_magazine = p_src->i_teletext_magazine_number
4424 ? p_src->i_teletext_magazine_number : 8;
4425 p_dst->i_page = p_src->i_teletext_page_number;
4426 memcpy( p_dst->p_iso639, p_src->i_iso6392_language_code, 3 );
4430 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x59 );
4433 dvbpsi_subtitling_dr_t *p_sub = dvbpsi_DecodeSubtitlingDr( p_dr );
4434 for( int i = 0; p_sub && i < p_sub->i_subtitles_number; i++ )
4436 dvbpsi_subtitle_t *p_src = &p_sub->p_subtitle[i];
4438 if( p_src->i_subtitling_type < 0x01 || p_src->i_subtitling_type > 0x03 )
4441 assert( i_page < sizeof(p_page)/sizeof(*p_page) );
4443 ts_teletext_page_t *p_dst = &p_page[i_page++];
4445 switch( p_src->i_subtitling_type )
4448 p_dst->i_type = 0x02;
4451 p_dst->i_type = 0x03;
4454 /* FIXME check if it is the right split */
4455 p_dst->i_magazine = (p_src->i_composition_page_id >> 8)
4456 ? (p_src->i_composition_page_id >> 8) : 8;
4457 p_dst->i_page = p_src->i_composition_page_id & 0xff;
4458 memcpy( p_dst->p_iso639, p_src->i_iso6392_language_code, 3 );
4463 es_format_Init( p_fmt, SPU_ES, VLC_CODEC_TELETEXT );
4465 if( !p_demux->p_sys->b_split_es || i_page <= 0 )
4467 p_fmt->subs.teletext.i_magazine = -1;
4468 p_fmt->subs.teletext.i_page = 0;
4469 p_fmt->psz_description = strdup( vlc_gettext(ppsz_teletext_type[1]) );
4471 dvbpsi_descriptor_t *p_dr;
4472 p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x46 );
4474 p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x56 );
4476 if( !p_demux->p_sys->b_split_es && p_dr && p_dr->i_length > 0 )
4478 /* Descriptor pass-through */
4479 p_fmt->p_extra = malloc( p_dr->i_length );
4480 if( p_fmt->p_extra )
4482 p_fmt->i_extra = p_dr->i_length;
4483 memcpy( p_fmt->p_extra, p_dr->p_data, p_dr->i_length );
4489 for( unsigned i = 0; i < i_page; i++ )
4491 ts_pes_es_t *p_page_es;
4496 p_page_es = &p_pes->es;
4500 p_page_es = calloc( 1, sizeof(*p_page_es) );
4504 es_format_Copy( &p_page_es->fmt, p_fmt );
4505 free( p_page_es->fmt.psz_language );
4506 free( p_page_es->fmt.psz_description );
4507 p_page_es->fmt.psz_language = NULL;
4508 p_page_es->fmt.psz_description = NULL;
4510 ARRAY_APPEND( p_pes->extra_es, p_page_es );
4514 const ts_teletext_page_t *p = &p_page[i];
4515 p_page_es->fmt.i_priority = (p->i_type == 0x02 || p->i_type == 0x05) ?
4516 ES_PRIORITY_SELECTABLE_MIN : ES_PRIORITY_NOT_DEFAULTABLE;
4517 p_page_es->fmt.psz_language = strndup( p->p_iso639, 3 );
4518 p_page_es->fmt.psz_description = strdup(vlc_gettext(ppsz_teletext_type[p->i_type]));
4519 p_page_es->fmt.subs.teletext.i_magazine = p->i_magazine;
4520 p_page_es->fmt.subs.teletext.i_page = p->i_page;
4523 " * ttxt type=%s lan=%s page=%d%02x",
4524 p_page_es->fmt.psz_description,
4525 p_page_es->fmt.psz_language,
4526 p->i_magazine, p->i_page );
4530 static void PMTSetupEsDvbSubtitle( demux_t *p_demux, ts_pes_t *p_pes,
4531 const dvbpsi_pmt_es_t *p_dvbpsies )
4533 es_format_t *p_fmt = &p_pes->es.fmt;
4535 es_format_Init( p_fmt, SPU_ES, VLC_CODEC_DVBS );
4537 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x59 );
4539 dvbpsi_subtitling_dr_t *p_sub = dvbpsi_DecodeSubtitlingDr( p_dr );
4540 for( int i = 0; p_sub && i < p_sub->i_subtitles_number; i++ )
4542 const int i_type = p_sub->p_subtitle[i].i_subtitling_type;
4543 if( ( i_type >= 0x10 && i_type <= 0x14 ) ||
4544 ( i_type >= 0x20 && i_type <= 0x24 ) )
4548 if( !p_demux->p_sys->b_split_es || i_page <= 0 )
4550 p_fmt->subs.dvb.i_id = -1;
4551 p_fmt->psz_description = strdup( _("DVB subtitles") );
4553 if( !p_demux->p_sys->b_split_es && p_dr && p_dr->i_length > 0 )
4555 /* Descriptor pass-through */
4556 p_fmt->p_extra = malloc( p_dr->i_length );
4557 if( p_fmt->p_extra )
4559 p_fmt->i_extra = p_dr->i_length;
4560 memcpy( p_fmt->p_extra, p_dr->p_data, p_dr->i_length );
4566 for( int i = 0; i < p_sub->i_subtitles_number; i++ )
4568 ts_pes_es_t *p_subs_es;
4573 p_subs_es = &p_pes->es;
4577 p_subs_es = malloc( sizeof(*p_subs_es) );
4581 es_format_Copy( &p_subs_es->fmt, p_fmt );
4582 free( p_subs_es->fmt.psz_language );
4583 free( p_subs_es->fmt.psz_description );
4584 p_subs_es->fmt.psz_language = NULL;
4585 p_subs_es->fmt.psz_description = NULL;
4587 ARRAY_APPEND( p_pes->extra_es, p_subs_es );
4591 const dvbpsi_subtitle_t *p = &p_sub->p_subtitle[i];
4592 p_subs_es->fmt.psz_language = strndup( (char *)p->i_iso6392_language_code, 3 );
4593 switch( p->i_subtitling_type )
4595 case 0x10: /* unspec. */
4596 case 0x11: /* 4:3 */
4597 case 0x12: /* 16:9 */
4598 case 0x13: /* 2.21:1 */
4599 case 0x14: /* HD monitor */
4600 p_subs_es->fmt.psz_description = strdup( _("DVB subtitles") );
4602 case 0x20: /* Hearing impaired unspec. */
4603 case 0x21: /* h.i. 4:3 */
4604 case 0x22: /* h.i. 16:9 */
4605 case 0x23: /* h.i. 2.21:1 */
4606 case 0x24: /* h.i. HD monitor */
4607 p_subs_es->fmt.psz_description = strdup( _("DVB subtitles: hearing impaired") );
4614 p_subs_es->fmt.subs.dvb.i_id = ( p->i_composition_page_id << 0 ) |
4615 ( p->i_ancillary_page_id << 16 );
4620 static int vlc_ceil_log2( const unsigned int val )
4622 int n = 31 - clz(val);
4623 if ((1U << n) != val)
4629 static void OpusSetup(demux_t *demux, uint8_t *p, size_t len, es_format_t *p_fmt)
4633 /* default mapping */
4634 static const unsigned char map[8] = { 0, 1, 2, 3, 4, 5, 6, 7 };
4635 memcpy(h.stream_map, map, sizeof(map));
4639 int stream_count = 0;
4640 int ccc = p[1]; // channel_config_code
4644 mapping = channels > 2;
4647 channels = 2; // dual mono
4649 static const uint8_t p_csc[8] = { 0, 1, 1, 2, 2, 2, 3, 3 };
4650 csc = p_csc[channels - 1];
4651 stream_count = channels - csc;
4653 static const uint8_t map[6][7] = {
4662 memcpy(&h.stream_map[1], map[channels-3], channels - 1);
4663 } else if (ccc == 0x81) {
4665 goto explicit_config_too_short;
4672 bs_init(&s, &p[4], len - 4);
4675 int bits = vlc_ceil_log2(channels);
4676 if (s.i_left < bits)
4677 goto explicit_config_too_short;
4678 stream_count = bs_read(&s, bits) + 1;
4679 bits = vlc_ceil_log2(stream_count + 1);
4680 if (s.i_left < bits)
4681 goto explicit_config_too_short;
4682 csc = bs_read(&s, bits);
4684 int channel_bits = vlc_ceil_log2(stream_count + csc + 1);
4685 if (s.i_left < channels * channel_bits)
4686 goto explicit_config_too_short;
4688 unsigned char silence = (1U << (stream_count + csc + 1)) - 1;
4689 for (int i = 0; i < channels; i++) {
4690 unsigned char m = bs_read(&s, channel_bits);
4693 h.stream_map[i] = m;
4696 } else if (ccc >= 0x80 && ccc <= 0x88) {
4697 channels = ccc - 0x80;
4702 channels = 2; // dual mono
4705 stream_count = channels;
4707 msg_Err(demux, "Opus channel configuration 0x%.2x is reserved", ccc);
4711 msg_Err(demux, "Opus channel configuration 0x%.2x not supported yet", p[1]);
4715 opus_prepare_header(channels, 0, &h);
4717 h.input_sample_rate = 48000;
4719 h.nb_streams = channels - csc;
4720 h.channel_mapping = mapping;
4723 opus_write_header((uint8_t**)&p_fmt->p_extra, &p_fmt->i_extra, &h, NULL /* FIXME */);
4724 if (p_fmt->p_extra) {
4725 p_fmt->i_cat = AUDIO_ES;
4726 p_fmt->i_codec = VLC_CODEC_OPUS;
4727 p_fmt->audio.i_channels = h.channels;
4728 p_fmt->audio.i_rate = 48000;
4734 explicit_config_too_short:
4735 msg_Err(demux, "Opus descriptor too short");
4738 static void PMTSetupEs0x06( demux_t *p_demux, ts_pes_t *p_pes,
4739 const dvbpsi_pmt_es_t *p_dvbpsies )
4741 es_format_t *p_fmt = &p_pes->es.fmt;
4742 dvbpsi_descriptor_t *p_subs_dr = PMTEsFindDescriptor( p_dvbpsies, 0x59 );
4743 dvbpsi_descriptor_t *desc;
4745 if( PMTEsHasRegistration( p_demux, p_dvbpsies, "AC-3" ) ||
4746 PMTEsFindDescriptor( p_dvbpsies, 0x6a ) ||
4747 PMTEsFindDescriptor( p_dvbpsies, 0x81 ) )
4749 p_fmt->i_cat = AUDIO_ES;
4750 p_fmt->i_codec = VLC_CODEC_A52;
4752 else if( (desc = PMTEsFindDescriptor( p_dvbpsies, 0x7f ) ) && desc->i_length >= 2 &&
4753 PMTEsHasRegistration(p_demux, p_dvbpsies, "Opus"))
4755 OpusSetup(p_demux, desc->p_data, desc->i_length, p_fmt);
4757 else if( PMTEsFindDescriptor( p_dvbpsies, 0x7a ) )
4759 /* DVB with stream_type 0x06 (ETS EN 300 468) */
4760 p_fmt->i_cat = AUDIO_ES;
4761 p_fmt->i_codec = VLC_CODEC_EAC3;
4763 else if( PMTEsHasRegistration( p_demux, p_dvbpsies, "DTS1" ) ||
4764 PMTEsHasRegistration( p_demux, p_dvbpsies, "DTS2" ) ||
4765 PMTEsHasRegistration( p_demux, p_dvbpsies, "DTS3" ) ||
4766 PMTEsFindDescriptor( p_dvbpsies, 0x73 ) )
4768 /*registration descriptor(ETSI TS 101 154 Annex F)*/
4769 p_fmt->i_cat = AUDIO_ES;
4770 p_fmt->i_codec = VLC_CODEC_DTS;
4772 else if( PMTEsHasRegistration( p_demux, p_dvbpsies, "BSSD" ) && !p_subs_dr )
4774 /* BSSD is AES3 DATA, but could also be subtitles
4775 * we need to check for secondary descriptor then s*/
4776 p_fmt->i_cat = AUDIO_ES;
4777 p_fmt->b_packetized = true;
4778 p_fmt->i_codec = VLC_CODEC_302M;
4780 else if( PMTEsHasRegistration( p_demux, p_dvbpsies, "HEVC" ) )
4782 p_fmt->i_cat = VIDEO_ES;
4783 p_fmt->i_codec = VLC_CODEC_HEVC;
4785 else if ( p_demux->p_sys->arib.e_mode == ARIBMODE_ENABLED )
4787 /* Lookup our data component descriptor first ARIB STD B10 6.4 */
4788 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0xFD );
4789 /* and check that it maps to something ARIB STD B14 Table 5.1/5.2 */
4790 if ( p_dr && p_dr->i_length >= 2 )
4792 if( !memcmp( p_dr->p_data, "\x00\x08", 2 ) && (
4793 PMTEsHasComponentTag( p_dvbpsies, 0x30 ) ||
4794 PMTEsHasComponentTag( p_dvbpsies, 0x31 ) ||
4795 PMTEsHasComponentTag( p_dvbpsies, 0x32 ) ||
4796 PMTEsHasComponentTag( p_dvbpsies, 0x33 ) ||
4797 PMTEsHasComponentTag( p_dvbpsies, 0x34 ) ||
4798 PMTEsHasComponentTag( p_dvbpsies, 0x35 ) ||
4799 PMTEsHasComponentTag( p_dvbpsies, 0x36 ) ||
4800 PMTEsHasComponentTag( p_dvbpsies, 0x37 ) ) )
4802 es_format_Init( p_fmt, SPU_ES, VLC_CODEC_ARIB_A );
4803 p_fmt->psz_language = strndup ( "jpn", 3 );
4804 p_fmt->psz_description = strdup( _("ARIB subtitles") );
4806 else if( !memcmp( p_dr->p_data, "\x00\x12", 2 ) && (
4807 PMTEsHasComponentTag( p_dvbpsies, 0x87 ) ||
4808 PMTEsHasComponentTag( p_dvbpsies, 0x88 ) ) )
4810 es_format_Init( p_fmt, SPU_ES, VLC_CODEC_ARIB_C );
4811 p_fmt->psz_language = strndup ( "jpn", 3 );
4812 p_fmt->psz_description = strdup( _("ARIB subtitles") );
4818 /* Subtitle/Teletext/VBI fallbacks */
4819 dvbpsi_subtitling_dr_t *p_sub;
4820 if( p_subs_dr && ( p_sub = dvbpsi_DecodeSubtitlingDr( p_subs_dr ) ) )
4822 for( int i = 0; i < p_sub->i_subtitles_number; i++ )
4824 if( p_fmt->i_cat != UNKNOWN_ES )
4827 switch( p_sub->p_subtitle[i].i_subtitling_type )
4829 case 0x01: /* EBU Teletext subtitles */
4830 case 0x02: /* Associated EBU Teletext */
4831 case 0x03: /* VBI data */
4832 PMTSetupEsTeletext( p_demux, p_pes, p_dvbpsies );
4834 case 0x10: /* DVB Subtitle (normal) with no monitor AR critical */
4835 case 0x11: /* ... on 4:3 AR monitor */
4836 case 0x12: /* ... on 16:9 AR monitor */
4837 case 0x13: /* ... on 2.21:1 AR monitor */
4838 case 0x14: /* ... for display on a high definition monitor */
4839 case 0x20: /* DVB Subtitle (impaired) with no monitor AR critical */
4840 case 0x21: /* ... on 4:3 AR monitor */
4841 case 0x22: /* ... on 16:9 AR monitor */
4842 case 0x23: /* ... on 2.21:1 AR monitor */
4843 case 0x24: /* ... for display on a high definition monitor */
4844 PMTSetupEsDvbSubtitle( p_demux, p_pes, p_dvbpsies );
4847 msg_Err( p_demux, "Unrecognized DVB subtitle type (0x%x)",
4848 p_sub->p_subtitle[i].i_subtitling_type );
4854 if( p_fmt->i_cat == UNKNOWN_ES &&
4855 ( PMTEsFindDescriptor( p_dvbpsies, 0x45 ) || /* VBI Data descriptor */
4856 PMTEsFindDescriptor( p_dvbpsies, 0x46 ) || /* VBI Teletext descriptor */
4857 PMTEsFindDescriptor( p_dvbpsies, 0x56 ) ) ) /* EBU Teletext descriptor */
4860 PMTSetupEsTeletext( p_demux, p_pes, p_dvbpsies );
4864 /* FIXME is it useful ? */
4865 if( PMTEsFindDescriptor( p_dvbpsies, 0x52 ) )
4867 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x52 );
4868 dvbpsi_stream_identifier_dr_t *p_si = dvbpsi_DecodeStreamIdentifierDr( p_dr );
4870 msg_Dbg( p_demux, " * Stream Component Identifier: %d", p_si->i_component_tag );
4874 static void PMTSetupEs0xEA( demux_t *p_demux, ts_pes_es_t *p_es,
4875 const dvbpsi_pmt_es_t *p_dvbpsies )
4877 /* Registration Descriptor */
4878 if( !PMTEsHasRegistration( p_demux, p_dvbpsies, "VC-1" ) )
4880 msg_Err( p_demux, "Registration descriptor not found or invalid" );
4884 es_format_t *p_fmt = &p_es->fmt;
4886 /* registration descriptor for VC-1 (SMPTE rp227) */
4887 p_fmt->i_cat = VIDEO_ES;
4888 p_fmt->i_codec = VLC_CODEC_VC1;
4890 /* XXX With Simple and Main profile the SEQUENCE
4891 * header is modified: video width and height are
4892 * inserted just after the start code as 2 int16_t
4893 * The packetizer will take care of that. */
4896 static void PMTSetupEs0xD1( demux_t *p_demux, ts_pes_es_t *p_es,
4897 const dvbpsi_pmt_es_t *p_dvbpsies )
4899 /* Registration Descriptor */
4900 if( !PMTEsHasRegistration( p_demux, p_dvbpsies, "drac" ) )
4902 msg_Err( p_demux, "Registration descriptor not found or invalid" );
4906 es_format_t *p_fmt = &p_es->fmt;
4908 /* registration descriptor for Dirac
4909 * (backwards compatable with VC-2 (SMPTE Sxxxx:2008)) */
4910 p_fmt->i_cat = VIDEO_ES;
4911 p_fmt->i_codec = VLC_CODEC_DIRAC;
4914 static void PMTSetupEs0xA0( demux_t *p_demux, ts_pes_es_t *p_es,
4915 const dvbpsi_pmt_es_t *p_dvbpsies )
4917 /* MSCODEC sent by vlc */
4918 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0xa0 );
4919 if( !p_dr || p_dr->i_length < 10 )
4922 "private MSCODEC (vlc) without bih private descriptor" );
4926 es_format_t *p_fmt = &p_es->fmt;
4927 p_fmt->i_cat = VIDEO_ES;
4928 p_fmt->i_codec = VLC_FOURCC( p_dr->p_data[0], p_dr->p_data[1],
4929 p_dr->p_data[2], p_dr->p_data[3] );
4930 p_fmt->video.i_width = GetWBE( &p_dr->p_data[4] );
4931 p_fmt->video.i_height = GetWBE( &p_dr->p_data[6] );
4932 p_fmt->i_extra = GetWBE( &p_dr->p_data[8] );
4934 if( p_fmt->i_extra > 0 )
4936 p_fmt->p_extra = malloc( p_fmt->i_extra );
4937 if( p_fmt->p_extra )
4938 memcpy( p_fmt->p_extra, &p_dr->p_data[10],
4939 __MIN( p_fmt->i_extra, p_dr->i_length - 10 ) );
4943 /* For such stream we will gather them ourself and don't launch a
4945 * Yes it's ugly but it's the only way to have DIV3 working */
4946 p_fmt->b_packetized = true;
4949 static void PMTSetupEs0x83( const dvbpsi_pmt_t *p_pmt, ts_pes_es_t *p_es, int i_pid )
4951 /* WiDi broadcasts without registration on PMT 0x1, PCR 0x1000 and
4952 * with audio track pid being 0x1100..0x11FF */
4953 if ( p_pmt->i_program_number == 0x1 &&
4954 p_pmt->i_pcr_pid == 0x1000 &&
4955 ( i_pid >> 8 ) == 0x11 )
4957 /* Not enough ? might contain 0x83 private descriptor, 2 bytes 0x473F */
4958 es_format_Init( &p_es->fmt, AUDIO_ES, VLC_CODEC_WIDI_LPCM );
4961 es_format_Init( &p_es->fmt, AUDIO_ES, VLC_CODEC_DVD_LPCM );
4964 static bool PMTSetupEsHDMV( demux_t *p_demux, ts_pes_es_t *p_es,
4965 const dvbpsi_pmt_es_t *p_dvbpsies )
4967 es_format_t *p_fmt = &p_es->fmt;
4969 /* Blu-Ray mapping */
4970 switch( p_dvbpsies->i_type )
4973 p_fmt->i_cat = AUDIO_ES;
4974 p_fmt->i_codec = VLC_CODEC_BD_LPCM;
4977 p_fmt->i_cat = AUDIO_ES;
4978 p_fmt->i_codec = VLC_CODEC_A52;
4981 case 0x85: /* DTS-HD High resolution audio */
4982 case 0x86: /* DTS-HD Master audio */
4983 case 0xA2: /* Secondary DTS audio */
4984 p_fmt->i_cat = AUDIO_ES;
4985 p_fmt->i_codec = VLC_CODEC_DTS;
4988 case 0x83: /* TrueHD AC3 */
4989 p_fmt->i_cat = AUDIO_ES;
4990 p_fmt->i_codec = VLC_CODEC_TRUEHD;
4993 case 0x84: /* E-AC3 */
4994 case 0xA1: /* Secondary E-AC3 */
4995 p_fmt->i_cat = AUDIO_ES;
4996 p_fmt->i_codec = VLC_CODEC_EAC3;
4998 case 0x90: /* Presentation graphics */
4999 p_fmt->i_cat = SPU_ES;
5000 p_fmt->i_codec = VLC_CODEC_BD_PG;
5002 case 0x91: /* Interactive graphics */
5003 case 0x92: /* Subtitle */
5006 p_fmt->i_cat = VIDEO_ES;
5007 p_fmt->i_codec = VLC_CODEC_VC1;
5010 msg_Info( p_demux, "HDMV registration not implemented for pid 0x%x type 0x%x",
5011 p_dvbpsies->i_pid, p_dvbpsies->i_type );
5018 static bool PMTSetupEsRegistration( demux_t *p_demux, ts_pes_es_t *p_es,
5019 const dvbpsi_pmt_es_t *p_dvbpsies )
5025 vlc_fourcc_t i_codec;
5027 { "AC-3", AUDIO_ES, VLC_CODEC_A52 },
5028 { "DTS1", AUDIO_ES, VLC_CODEC_DTS },
5029 { "DTS2", AUDIO_ES, VLC_CODEC_DTS },
5030 { "DTS3", AUDIO_ES, VLC_CODEC_DTS },
5031 { "BSSD", AUDIO_ES, VLC_CODEC_302M },
5032 { "VC-1", VIDEO_ES, VLC_CODEC_VC1 },
5033 { "drac", VIDEO_ES, VLC_CODEC_DIRAC },
5034 { "", UNKNOWN_ES, 0 }
5036 es_format_t *p_fmt = &p_es->fmt;
5038 for( int i = 0; p_regs[i].i_cat != UNKNOWN_ES; i++ )
5040 if( PMTEsHasRegistration( p_demux, p_dvbpsies, p_regs[i].psz_tag ) )
5042 p_fmt->i_cat = p_regs[i].i_cat;
5043 p_fmt->i_codec = p_regs[i].i_codec;
5044 if (p_dvbpsies->i_type == 0x87)
5045 p_fmt->i_codec = VLC_CODEC_EAC3;
5052 static char *GetAudioTypeDesc(demux_t *p_demux, int type)
5054 static const char *audio_type[] = {
5056 N_("clean effects"),
5057 N_("hearing impaired"),
5058 N_("visual impaired commentary"),
5061 if (type < 0 || type > 3)
5062 msg_Dbg( p_demux, "unknown audio type: %d", type);
5064 return strdup(audio_type[type]);
5068 static void PMTParseEsIso639( demux_t *p_demux, ts_pes_es_t *p_es,
5069 const dvbpsi_pmt_es_t *p_dvbpsies )
5071 /* get language descriptor */
5072 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x0a );
5077 dvbpsi_iso639_dr_t *p_decoded = dvbpsi_DecodeISO639Dr( p_dr );
5080 msg_Err( p_demux, "Failed to decode a ISO 639 descriptor" );
5084 #if defined(DR_0A_API_VER) && (DR_0A_API_VER >= 2)
5085 p_es->fmt.psz_language = malloc( 4 );
5086 if( p_es->fmt.psz_language )
5088 memcpy( p_es->fmt.psz_language, p_decoded->code[0].iso_639_code, 3 );
5089 p_es->fmt.psz_language[3] = 0;
5090 msg_Dbg( p_demux, "found language: %s", p_es->fmt.psz_language);
5092 int type = p_decoded->code[0].i_audio_type;
5093 p_es->fmt.psz_description = GetAudioTypeDesc(p_demux, type);
5095 p_es->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN + 1; // prioritize normal audio tracks
5097 p_es->fmt.i_extra_languages = p_decoded->i_code_count-1;
5098 if( p_es->fmt.i_extra_languages > 0 )
5099 p_es->fmt.p_extra_languages =
5100 malloc( sizeof(*p_es->fmt.p_extra_languages) *
5101 p_es->fmt.i_extra_languages );
5102 if( p_es->fmt.p_extra_languages )
5104 for( unsigned i = 0; i < p_es->fmt.i_extra_languages; i++ )
5106 p_es->fmt.p_extra_languages[i].psz_language = malloc(4);
5107 if( p_es->fmt.p_extra_languages[i].psz_language )
5109 memcpy( p_es->fmt.p_extra_languages[i].psz_language,
5110 p_decoded->code[i+1].iso_639_code, 3 );
5111 p_es->fmt.p_extra_languages[i].psz_language[3] = '\0';
5113 int type = p_decoded->code[i].i_audio_type;
5114 p_es->fmt.p_extra_languages[i].psz_description = GetAudioTypeDesc(p_demux, type);
5118 p_es->fmt.psz_language = malloc( 4 );
5119 if( p_es->fmt.psz_language )
5121 memcpy( p_es->fmt.psz_language,
5122 p_decoded->i_iso_639_code, 3 );
5123 p_es->fmt.psz_language[3] = 0;
5128 static inline void SetExtraESGroupAndID( demux_sys_t *p_sys, es_format_t *p_fmt,
5129 const es_format_t *p_parent_fmt )
5131 if ( p_sys->b_es_id_pid ) /* pid is 13 bits */
5132 p_fmt->i_id = (p_sys->i_next_extraid++ << 13) | p_parent_fmt->i_id;
5133 p_fmt->i_group = p_parent_fmt->i_group;
5136 static void AddAndCreateES( demux_t *p_demux, ts_pid_t *pid, bool b_create_delayed )
5138 demux_sys_t *p_sys = p_demux->p_sys;
5140 if( b_create_delayed )
5141 p_sys->es_creation = CREATE_ES;
5143 if( pid && p_sys->es_creation == CREATE_ES )
5145 /* FIXME: other owners / shared pid */
5146 pid->u.p_pes->es.id = es_out_Add( p_demux->out, &pid->u.p_pes->es.fmt );
5147 for( int i = 0; i < pid->u.p_pes->extra_es.i_size; i++ )
5149 es_format_t *p_fmt = &pid->u.p_pes->extra_es.p_elems[i]->fmt;
5150 SetExtraESGroupAndID( p_sys, p_fmt, &pid->u.p_pes->es.fmt );
5151 pid->u.p_pes->extra_es.p_elems[i]->id = es_out_Add( p_demux->out, p_fmt );
5153 p_sys->i_pmt_es += 1 + pid->u.p_pes->extra_es.i_size;
5155 /* Update the default program == first created ES group */
5156 if( p_sys->b_default_selection )
5158 p_sys->b_default_selection = false;
5159 assert(p_sys->programs.i_size == 1);
5160 if( p_sys->programs.p_elems[0] != pid->p_parent->u.p_pmt->i_number )
5161 p_sys->programs.p_elems[0] = pid->p_parent->u.p_pmt->i_number;
5162 msg_Dbg( p_demux, "Default program is %d", pid->p_parent->u.p_pmt->i_number );
5166 if( b_create_delayed )
5168 ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
5169 for( int i=0; i< p_pat->programs.i_size; i++ )
5171 ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
5172 for( int j=0; j<p_pmt->e_streams.i_size; j++ )
5174 ts_pid_t *pid = p_pmt->e_streams.p_elems[j];
5175 if( pid->u.p_pes->es.id )
5178 pid->u.p_pes->es.id = es_out_Add( p_demux->out, &pid->u.p_pes->es.fmt );
5179 for( int k = 0; k < pid->u.p_pes->extra_es.i_size; k++ )
5181 es_format_t *p_fmt = &pid->u.p_pes->extra_es.p_elems[k]->fmt;
5182 SetExtraESGroupAndID( p_sys, p_fmt, &pid->u.p_pes->es.fmt );
5183 pid->u.p_pes->extra_es.p_elems[k]->id = es_out_Add( p_demux->out, p_fmt );
5185 p_sys->i_pmt_es += 1 + pid->u.p_pes->extra_es.i_size;
5190 UpdatePESFilters( p_demux, p_sys->b_es_all );
5193 static void PMTCallBack( void *data, dvbpsi_pmt_t *p_dvbpsipmt )
5195 demux_t *p_demux = data;
5196 demux_sys_t *p_sys = p_demux->p_sys;
5198 ts_pid_t *pmtpid = NULL;
5199 ts_pmt_t *p_pmt = NULL;
5201 msg_Dbg( p_demux, "PMTCallBack called" );
5203 if (unlikely(PID(p_sys, 0)->type != TYPE_PAT))
5205 assert(PID(p_sys, 0)->type == TYPE_PAT);
5206 dvbpsi_pmt_delete(p_dvbpsipmt);
5209 const ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
5211 /* First find this PMT declared in PAT */
5212 for( int i = 0; !pmtpid && i < p_pat->programs.i_size; i++ )
5214 const int i_pmt_prgnumber = p_pat->programs.p_elems[i]->u.p_pmt->i_number;
5215 if( i_pmt_prgnumber != TS_USER_PMT_NUMBER &&
5216 i_pmt_prgnumber == p_dvbpsipmt->i_program_number )
5218 pmtpid = p_pat->programs.p_elems[i];
5219 assert(pmtpid->type == TYPE_PMT);
5220 p_pmt = pmtpid->u.p_pmt;
5224 if( pmtpid == NULL )
5226 msg_Warn( p_demux, "unreferenced program (broken stream)" );
5227 dvbpsi_pmt_delete(p_dvbpsipmt);
5231 pmtpid->i_flags |= FLAG_SEEN;
5233 if( p_pmt->i_version != -1 &&
5234 ( !p_dvbpsipmt->b_current_next || p_pmt->i_version == p_dvbpsipmt->i_version ) )
5236 dvbpsi_pmt_delete( p_dvbpsipmt );
5240 /* Save old es array */
5241 DECL_ARRAY(ts_pid_t *) old_es_rm;
5242 old_es_rm.i_alloc = p_pmt->e_streams.i_alloc;
5243 old_es_rm.i_size = p_pmt->e_streams.i_size;
5244 old_es_rm.p_elems = p_pmt->e_streams.p_elems;
5245 ARRAY_INIT(p_pmt->e_streams);
5249 IODFree( p_pmt->iod );
5251 for( int i=0; i<old_es_rm.i_size; i++ )
5252 old_es_rm.p_elems[i]->u.p_pes->es.p_mpeg4desc = NULL;
5255 msg_Dbg( p_demux, "new PMT program number=%d version=%d pid_pcr=%d",
5256 p_dvbpsipmt->i_program_number, p_dvbpsipmt->i_version, p_dvbpsipmt->i_pcr_pid );
5257 p_pmt->i_pid_pcr = p_dvbpsipmt->i_pcr_pid;
5258 p_pmt->i_version = p_dvbpsipmt->i_version;
5260 ValidateDVBMeta( p_demux, p_pmt->i_pid_pcr );
5262 if( ProgramIsSelected( p_sys, p_pmt->i_number ) )
5263 SetPIDFilter( p_sys, PID(p_sys, p_pmt->i_pid_pcr), true ); /* Set demux filter */
5265 /* Parse PMT descriptors */
5266 ts_pmt_registration_type_t registration_type = TS_PMT_REGISTRATION_NONE;
5267 dvbpsi_descriptor_t *p_dr;
5269 /* First pass for standard detection */
5270 if ( p_sys->arib.e_mode == ARIBMODE_AUTO )
5272 int i_arib_flags = 0; /* Descriptors can be repeated */
5273 for( p_dr = p_dvbpsipmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
5279 dvbpsi_ca_dr_t *p_cadr = dvbpsi_DecodeCADr( p_dr );
5280 i_arib_flags |= (p_cadr->i_ca_system_id == 0x05);
5284 i_arib_flags |= 1 << 1;
5287 i_arib_flags |= 1 << 2;
5293 if ( i_arib_flags == 0x07 ) //0b111
5294 p_sys->arib.e_mode = ARIBMODE_ENABLED;
5297 for( p_dr = p_dvbpsipmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
5299 /* special descriptors handling */
5302 case 0x1d: /* We have found an IOD descriptor */
5303 msg_Dbg( p_demux, " * PMT descriptor : IOD (0x1d)" );
5304 p_pmt->iod = IODNew( p_dr->i_length, p_dr->p_data );
5308 msg_Dbg( p_demux, " * PMT descriptor : CA (0x9) SysID 0x%x",
5309 (p_dr->p_data[0] << 8) | p_dr->p_data[1] );
5312 case 0x5: /* Registration Descriptor */
5313 if( p_dr->i_length != 4 )
5315 msg_Warn( p_demux, " * PMT invalid Registration Descriptor" );
5319 msg_Dbg( p_demux, " * PMT descriptor : registration %4.4s", p_dr->p_data );
5320 if( !memcmp( p_dr->p_data, "HDMV", 4 ) || !memcmp( p_dr->p_data, "HDPR", 4 ) )
5321 registration_type = TS_PMT_REGISTRATION_HDMV; /* Blu-Ray */
5326 msg_Dbg( p_demux, " * PMT descriptor : Private Data (0x0f)" );
5330 msg_Dbg( p_demux, " * PMT descriptor : Digital copy control (0xC1)" );
5333 case 0x88: /* EACEM Simulcast HD Logical channels ordering */
5334 msg_Dbg( p_demux, " * descriptor : EACEM Simulcast HD" );
5335 /* TODO: apply visibility flags */
5339 msg_Dbg( p_demux, " * PMT descriptor : unknown (0x%x)", p_dr->i_tag );
5343 dvbpsi_pmt_es_t *p_dvbpsies;
5344 for( p_dvbpsies = p_dvbpsipmt->p_first_es; p_dvbpsies != NULL; p_dvbpsies = p_dvbpsies->p_next )
5346 bool b_reusing_pid = false;
5349 ts_pid_t *pespid = PID(p_sys, p_dvbpsies->i_pid);
5350 if ( pespid->type == TYPE_PES && pespid->p_parent->u.p_pmt->i_number != p_pmt->i_number )
5352 msg_Warn( p_demux, " * PMT wants to get a share or pid %d (unsupported)", pespid->i_pid );
5356 /* Find out if the PID was already declared */
5357 for( int i = 0; i < old_es_rm.i_size; i++ )
5359 if( old_es_rm.p_elems[i]->i_pid == p_dvbpsies->i_pid )
5361 b_reusing_pid = true;
5365 ValidateDVBMeta( p_demux, p_dvbpsies->i_pid );
5367 char const * psz_typedesc = "";
5368 switch(p_dvbpsies->i_type)
5371 psz_typedesc = "ISO/IEC Reserved";
5374 psz_typedesc = "ISO/IEC 11172 Video";
5377 psz_typedesc = "ISO/IEC 13818-2 Video or ISO/IEC 11172-2 constrained parameter video stream";
5380 psz_typedesc = "ISO/IEC 11172 Audio";
5383 psz_typedesc = "ISO/IEC 13818-3 Audio";
5386 psz_typedesc = "ISO/IEC 13818-1 private_sections";
5389 psz_typedesc = "ISO/IEC 13818-1 PES packets containing private data";
5392 psz_typedesc = "ISO/IEC 13522 MHEG";
5395 psz_typedesc = "ISO/IEC 13818-1 Annex A DSM CC";
5398 psz_typedesc = "ITU-T Rec. H.222.1";
5401 psz_typedesc = "ISO/IEC 13818-6 type A";
5404 psz_typedesc = "ISO/IEC 13818-6 type B";
5407 psz_typedesc = "ISO/IEC 13818-6 type C";
5410 psz_typedesc = "ISO/IEC 13818-6 type D";
5413 psz_typedesc = "ISO/IEC 13818-1 auxiliary";
5416 if (p_dvbpsies->i_type >= 0x0F && p_dvbpsies->i_type <=0x7F)
5417 psz_typedesc = "ISO/IEC 13818-1 Reserved";
5419 psz_typedesc = "User Private";
5422 msg_Dbg( p_demux, " * pid=%d type=0x%x %s",
5423 p_dvbpsies->i_pid, p_dvbpsies->i_type, psz_typedesc );
5425 for( p_dr = p_dvbpsies->p_first_descriptor; p_dr != NULL;
5426 p_dr = p_dr->p_next )
5428 msg_Dbg( p_demux, " - descriptor tag 0x%x",
5432 if ( !PIDSetup( p_demux, TYPE_PES, pespid, pmtpid ) )
5434 msg_Warn( p_demux, " * pid=%d type=0x%x %s (skipped)",
5435 p_dvbpsies->i_pid, p_dvbpsies->i_type, psz_typedesc );
5442 p_pes = ts_pes_New( p_demux );
5448 p_pes = pespid->u.p_pes;
5452 ARRAY_APPEND( p_pmt->e_streams, pespid );
5454 PIDFillFormat( &p_pes->es.fmt, p_dvbpsies->i_type );
5456 pespid->i_flags |= SEEN(PID(p_sys, p_dvbpsies->i_pid));
5458 bool b_registration_applied = false;
5459 if ( p_dvbpsies->i_type >= 0x80 ) /* non standard, extensions */
5461 if ( registration_type == TS_PMT_REGISTRATION_HDMV )
5463 if (( b_registration_applied = PMTSetupEsHDMV( p_demux, &p_pes->es, p_dvbpsies ) ))
5464 msg_Dbg( p_demux, " + HDMV registration applied to pid %d type 0x%x",
5465 p_dvbpsies->i_pid, p_dvbpsies->i_type );
5469 if (( b_registration_applied = PMTSetupEsRegistration( p_demux, &p_pes->es, p_dvbpsies ) ))
5470 msg_Dbg( p_demux, " + registration applied to pid %d type 0x%x",
5471 p_dvbpsies->i_pid, p_dvbpsies->i_type );
5475 if ( !b_registration_applied )
5477 switch( p_dvbpsies->i_type )
5480 /* Handle PES private data */
5481 PMTSetupEs0x06( p_demux, p_pes, p_dvbpsies );
5483 /* All other private or reserved types */
5488 PMTSetupEsISO14496( p_demux, &p_pes->es, p_pmt, p_dvbpsies );
5492 PMTSetupEs0x83( p_dvbpsipmt, &p_pes->es, p_dvbpsies->i_pid );
5495 PMTSetupEs0xA0( p_demux, &p_pes->es, p_dvbpsies );
5498 PMTSetupEs0xD1( p_demux, &p_pes->es, p_dvbpsies );
5501 PMTSetupEs0xEA( p_demux, &p_pes->es, p_dvbpsies );
5507 if( p_pes->es.fmt.i_cat == AUDIO_ES ||
5508 ( p_pes->es.fmt.i_cat == SPU_ES &&
5509 p_pes->es.fmt.i_codec != VLC_CODEC_DVBS &&
5510 p_pes->es.fmt.i_codec != VLC_CODEC_TELETEXT ) )
5512 PMTParseEsIso639( p_demux, &p_pes->es, p_dvbpsies );
5515 switch( p_pes->es.fmt.i_codec )
5517 case VLC_CODEC_SCTE_27:
5518 p_pes->data_type = TS_ES_DATA_TABLE_SECTION;
5521 //pid->es->data_type = TS_ES_DATA_PES;
5525 /* Set Groups / ID */
5526 p_pes->es.fmt.i_group = p_dvbpsipmt->i_program_number;
5527 if( p_sys->b_es_id_pid )
5528 p_pes->es.fmt.i_id = p_dvbpsies->i_pid;
5530 if( p_pes->es.fmt.i_cat == UNKNOWN_ES )
5532 msg_Dbg( p_demux, " => pid %d content is *unknown*",
5533 p_dvbpsies->i_pid );
5534 p_pes->es.fmt.psz_description = strdup( psz_typedesc );
5538 msg_Dbg( p_demux, " => pid %d has now es fcc=%4.4s",
5539 p_dvbpsies->i_pid, (char*)&p_pes->es.fmt.i_codec );
5541 /* Check if we can avoid restarting the ES */
5544 /* p_pes points to a tmp pes */
5545 if( pespid->u.p_pes->es.fmt.i_codec != p_pes->es.fmt.i_codec ||
5546 pespid->u.p_pes->es.fmt.i_extra != p_pes->es.fmt.i_extra ||
5547 pespid->u.p_pes->es.fmt.i_extra != 0 ||
5548 pespid->u.p_pes->extra_es.i_size != p_pes->extra_es.i_size ||
5549 !( ( !pespid->u.p_pes->es.fmt.psz_language &&
5550 !p_pes->es.fmt.psz_language ) ||
5551 ( pespid->u.p_pes->es.fmt.psz_language &&
5552 p_pes->es.fmt.psz_language &&
5553 !strcmp( pespid->u.p_pes->es.fmt.psz_language,
5554 p_pes->es.fmt.psz_language ) ) ) )
5556 /* Differs, swap then */
5557 ts_pes_t *e = pespid->u.p_pes;
5558 pespid->u.p_pes = p_pes;
5561 /* p_pes still tmp, but now contains old config */
5562 pespid->u.p_pes->es.id = p_pes->es.id;
5563 if( pespid->u.p_pes->es.id )
5565 p_pes->es.id = NULL;
5566 es_out_Control( p_demux->out, ES_OUT_SET_ES_FMT,
5567 pespid->u.p_pes->es.id, pespid->u.p_pes->es.fmt );
5570 for( int i=0; i<pespid->u.p_pes->extra_es.i_size &&
5571 i<p_pes->extra_es.i_size; i++ )
5573 pespid->u.p_pes->extra_es.p_elems[i]->id = p_pes->extra_es.p_elems[i]->id;
5574 if( pespid->u.p_pes->extra_es.p_elems[i]->id )
5576 es_out_Control( p_demux->out, ES_OUT_SET_ES_FMT,
5577 pespid->u.p_pes->extra_es.p_elems[i]->id,
5578 pespid->u.p_pes->extra_es.p_elems[i]->fmt );
5579 p_pes->extra_es.p_elems[i]->id = NULL;
5584 ts_pes_Del( p_demux, p_pes ); // delete temp
5588 AddAndCreateES( p_demux, pespid, false );
5592 p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x09 );
5593 if( p_dr && p_dr->i_length >= 2 )
5595 msg_Dbg( p_demux, " * PMT descriptor : CA (0x9) SysID 0x%x",
5596 (p_dr->p_data[0] << 8) | p_dr->p_data[1] );
5600 /* Set CAM descrambling */
5601 if( !ProgramIsSelected( p_sys, p_pmt->i_number ) )
5603 dvbpsi_pmt_delete( p_dvbpsipmt );
5605 else if( stream_Control( p_sys->stream, STREAM_SET_PRIVATE_ID_CA,
5606 p_dvbpsipmt ) != VLC_SUCCESS )
5608 if ( p_sys->arib.e_mode == ARIBMODE_ENABLED && !p_sys->arib.b25stream )
5610 p_sys->arib.b25stream = stream_FilterNew( p_demux->s, "aribcam" );
5611 p_sys->stream = ( p_sys->arib.b25stream ) ? p_sys->arib.b25stream : p_demux->s;
5612 if (!p_sys->arib.b25stream)
5613 dvbpsi_pmt_delete( p_dvbpsipmt );
5614 } else dvbpsi_pmt_delete( p_dvbpsipmt );
5617 /* Decref or clean now unused es */
5618 for( int i = 0; i < old_es_rm.i_size; i++ )
5619 PIDRelease( p_demux, old_es_rm.p_elems[i] );
5620 ARRAY_RESET( old_es_rm );
5622 UpdatePESFilters( p_demux, p_sys->b_es_all );
5624 if( !p_sys->b_trust_pcr )
5626 int i_cand = FindPCRCandidate( p_pmt );
5627 p_pmt->i_pid_pcr = i_cand;
5628 p_pmt->pcr.b_disable = true;
5629 msg_Warn( p_demux, "PCR not trusted for program %d, set up workaround using pid %d",
5630 p_pmt->i_number, i_cand );
5633 /* Probe Boundaries */
5634 if( p_sys->b_canfastseek && p_pmt->i_last_dts == -1 )
5636 p_pmt->i_last_dts = 0;
5637 ProbeStart( p_demux, p_pmt->i_number );
5638 ProbeEnd( p_demux, p_pmt->i_number );
5642 static int PATCheck( demux_t *p_demux, dvbpsi_pat_t *p_pat )
5644 /* Some Dreambox streams have all PMT set to same pid */
5645 int i_prev_pid = -1;
5646 for( dvbpsi_pat_program_t * p_program = p_pat->p_first_program;
5648 p_program = p_program->p_next )
5650 if( p_program->i_pid == i_prev_pid )
5652 msg_Warn( p_demux, "PAT check failed: duplicate program pid %d", i_prev_pid );
5653 return VLC_EGENERIC;
5655 i_prev_pid = p_program->i_pid;
5660 static void PATCallBack( void *data, dvbpsi_pat_t *p_dvbpsipat )
5662 demux_t *p_demux = data;
5663 demux_sys_t *p_sys = p_demux->p_sys;
5664 dvbpsi_pat_program_t *p_program;
5665 ts_pid_t *patpid = PID(p_sys, 0);
5666 ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
5668 patpid->i_flags |= FLAG_SEEN;
5670 msg_Dbg( p_demux, "PATCallBack called" );
5672 if(unlikely( PID(p_sys, 0)->type != TYPE_PAT ))
5674 msg_Warn( p_demux, "PATCallBack called on invalid pid" );
5678 if( ( p_pat->i_version != -1 &&
5679 ( !p_dvbpsipat->b_current_next ||
5680 p_dvbpsipat->i_version == p_pat->i_version ) ) ||
5681 ( p_pat->i_ts_id != -1 && p_dvbpsipat->i_ts_id != p_pat->i_ts_id ) ||
5682 p_sys->b_user_pmt || PATCheck( p_demux, p_dvbpsipat ) )
5684 dvbpsi_pat_delete( p_dvbpsipat );
5688 msg_Dbg( p_demux, "new PAT ts_id=%d version=%d current_next=%d",
5689 p_dvbpsipat->i_ts_id, p_dvbpsipat->i_version, p_dvbpsipat->b_current_next );
5691 /* Save old programs array */
5692 DECL_ARRAY(ts_pid_t *) old_pmt_rm;
5693 old_pmt_rm.i_alloc = p_pat->programs.i_alloc;
5694 old_pmt_rm.i_size = p_pat->programs.i_size;
5695 old_pmt_rm.p_elems = p_pat->programs.p_elems;
5696 ARRAY_INIT(p_pat->programs);
5698 /* now create programs */
5699 for( p_program = p_dvbpsipat->p_first_program; p_program != NULL;
5700 p_program = p_program->p_next )
5702 msg_Dbg( p_demux, " * number=%d pid=%d", p_program->i_number,
5704 if( p_program->i_number == 0 )
5707 ts_pid_t *pmtpid = PID(p_sys, p_program->i_pid);
5709 ValidateDVBMeta( p_demux, p_program->i_pid );
5711 /* create or temporary incref pid */
5712 if( !PIDSetup( p_demux, TYPE_PMT, pmtpid, patpid ) )
5714 msg_Warn( p_demux, " * number=%d pid=%d (ignored)", p_program->i_number,
5719 pmtpid->u.p_pmt->i_number = p_program->i_number;
5721 if( !dvbpsi_pmt_attach( pmtpid->u.p_pmt->handle, p_program->i_number, PMTCallBack, p_demux ) )
5722 msg_Err( p_demux, "PATCallback failed attaching PMTCallback to program %d",
5723 p_program->i_number );
5725 ARRAY_APPEND( p_pat->programs, pmtpid );
5727 /* Now select PID at access level */
5728 if( p_sys->programs.i_size == 0 ||
5729 ProgramIsSelected( p_sys, p_program->i_number ) )
5731 if( p_sys->programs.i_size == 0 )
5733 msg_Dbg( p_demux, "temporary receiving program %d", p_program->i_number );
5734 p_sys->b_default_selection = true;
5735 ARRAY_APPEND( p_sys->programs, p_program->i_number );
5738 if( SetPIDFilter( p_sys, pmtpid, true ) )
5739 p_sys->b_access_control = false;
5740 else if ( p_sys->es_creation == DELAY_ES )
5741 p_sys->es_creation = CREATE_ES;
5744 p_pat->i_version = p_dvbpsipat->i_version;
5745 p_pat->i_ts_id = p_dvbpsipat->i_ts_id;
5747 for(int i=0; i<old_pmt_rm.i_size; i++)
5749 /* decref current or release now unreferenced */
5750 PIDRelease( p_demux, old_pmt_rm.p_elems[i] );
5752 ARRAY_RESET(old_pmt_rm);
5754 dvbpsi_pat_delete( p_dvbpsipat );
5757 static inline bool handle_Init( demux_t *p_demux, dvbpsi_t **handle )
5759 *handle = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG );
5762 (*handle)->p_sys = (void *) p_demux;
5766 static ts_pat_t *ts_pat_New( demux_t *p_demux )
5768 ts_pat_t *pat = malloc( sizeof( ts_pat_t ) );
5772 if( !handle_Init( p_demux, &pat->handle ) )
5778 pat->i_version = -1;
5780 ARRAY_INIT( pat->programs );
5785 static void ts_pat_Del( demux_t *p_demux, ts_pat_t *pat )
5787 if( dvbpsi_decoder_present( pat->handle ) )
5788 dvbpsi_pat_detach( pat->handle );
5789 dvbpsi_delete( pat->handle );
5790 for( int i=0; i<pat->programs.i_size; i++ )
5791 PIDRelease( p_demux, pat->programs.p_elems[i] );
5792 ARRAY_RESET( pat->programs );
5796 static ts_pmt_t *ts_pmt_New( demux_t *p_demux )
5798 ts_pmt_t *pmt = malloc( sizeof( ts_pmt_t ) );
5802 if( !handle_Init( p_demux, &pmt->handle ) )
5808 ARRAY_INIT( pmt->e_streams );
5810 pmt->i_version = -1;
5812 pmt->i_pid_pcr = 0x1FFF;
5815 pmt->i_last_dts = -1;
5817 pmt->pcr.i_current = -1;
5818 pmt->pcr.i_first = -1;
5819 pmt->pcr.b_disable = false;
5820 pmt->pcr.i_first_dts = VLC_TS_INVALID;
5821 pmt->pcr.i_pcroffset = -1;
5823 pmt->pcr.b_fix_done = false;
5828 static void ts_pmt_Del( demux_t *p_demux, ts_pmt_t *pmt )
5830 if( dvbpsi_decoder_present( pmt->handle ) )
5831 dvbpsi_pmt_detach( pmt->handle );
5832 dvbpsi_delete( pmt->handle );
5833 for( int i=0; i<pmt->e_streams.i_size; i++ )
5834 PIDRelease( p_demux, pmt->e_streams.p_elems[i] );
5835 ARRAY_RESET( pmt->e_streams );
5837 IODFree( pmt->iod );
5838 if( pmt->i_number > -1 )
5839 es_out_Control( p_demux->out, ES_OUT_DEL_GROUP, pmt->i_number );
5843 static ts_pes_t *ts_pes_New( demux_t *p_demux )
5845 VLC_UNUSED(p_demux);
5846 ts_pes_t *pes = malloc( sizeof( ts_pes_t ) );
5851 pes->es.p_mpeg4desc = NULL;
5852 es_format_Init( &pes->es.fmt, UNKNOWN_ES, 0 );
5853 ARRAY_INIT( pes->extra_es );
5854 pes->data_type = TS_ES_DATA_PES;
5855 pes->i_data_size = 0;
5856 pes->i_data_gathered = 0;
5858 pes->pp_last = &pes->p_data;
5859 pes->p_prepcr_outqueue = NULL;
5864 static void ts_pes_Del( demux_t *p_demux, ts_pes_t *pes )
5868 es_out_Del( p_demux->out, pes->es.id );
5869 p_demux->p_sys->i_pmt_es--;
5873 block_ChainRelease( pes->p_data );
5875 if( pes->p_prepcr_outqueue )
5876 block_ChainRelease( pes->p_prepcr_outqueue );
5878 es_format_Clean( &pes->es.fmt );
5880 for( int i = 0; i < pes->extra_es.i_size; i++ )
5882 if( pes->extra_es.p_elems[i]->id )
5884 es_out_Del( p_demux->out, pes->extra_es.p_elems[i]->id );
5885 p_demux->p_sys->i_pmt_es--;
5887 es_format_Clean( &pes->extra_es.p_elems[i]->fmt );
5888 free( pes->extra_es.p_elems[i] );
5890 ARRAY_RESET( pes->extra_es );
5895 static ts_psi_t *ts_psi_New( demux_t *p_demux )
5897 ts_psi_t *psi = malloc( sizeof( ts_psi_t ) );
5901 if( !handle_Init( p_demux, &psi->handle ) )
5907 psi->i_version = -1;
5912 static void ts_psi_Del( demux_t *p_demux, ts_psi_t *psi )
5914 VLC_UNUSED(p_demux);
5915 if( dvbpsi_decoder_present( psi->handle ) )
5916 dvbpsi_DetachDemux( psi->handle );
5917 dvbpsi_delete( psi->handle );