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 void PMTSetupEsISO14496( demux_t *p_demux, ts_pes_es_t *p_es,
4219 const ts_pmt_t *p_pmt, const dvbpsi_pmt_es_t *p_dvbpsies )
4221 es_format_t *p_fmt = &p_es->fmt;
4223 /* MPEG-4 stream: search FMC_DESCRIPTOR (SL Packetized stream) */
4224 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x1f );
4226 if( p_dr && p_dr->i_length == 2 && p_pmt->iod )
4228 const int i_es_id = ( p_dr->p_data[0] << 8 ) | p_dr->p_data[1];
4230 msg_Dbg( p_demux, "found FMC_descriptor declaring sl packetization on es_id=%d", i_es_id );
4232 p_es->p_mpeg4desc = NULL;
4234 for( int i = 0; i < ES_DESCRIPTOR_COUNT; i++ )
4236 iod_descriptor_t *iod = p_pmt->iod;
4237 if( iod->es_descr[i].i_es_id == i_es_id )
4239 if ( iod->es_descr[i].b_ok )
4240 p_es->p_mpeg4desc = &iod->es_descr[i];
4242 msg_Dbg( p_demux, "MPEG-4 descriptor not yet available on es_id=%d", i_es_id );
4247 if( !p_es->p_mpeg4desc )
4249 switch( p_dvbpsies->i_type )
4251 /* non fatal, set by packetizer */
4252 case 0x0f: /* ADTS */
4253 case 0x11: /* LOAS */
4254 msg_Info( p_demux, "MPEG-4 descriptor not found for pid 0x%x type 0x%x",
4255 p_dvbpsies->i_pid, p_dvbpsies->i_type );
4258 msg_Err( p_demux, "MPEG-4 descriptor not found for pid 0x%x type 0x%x",
4259 p_dvbpsies->i_pid, p_dvbpsies->i_type );
4265 const decoder_config_descriptor_t *dcd = &p_es->p_mpeg4desc->dec_descr;
4266 if( dcd->i_streamType == 0x04 ) /* VisualStream */
4268 p_fmt->i_cat = VIDEO_ES;
4269 switch( dcd->i_objectTypeIndication )
4271 case 0x0B: /* mpeg4 sub */
4272 p_fmt->i_cat = SPU_ES;
4273 p_fmt->i_codec = VLC_CODEC_SUBT;
4276 case 0x20: /* mpeg4 */
4277 p_fmt->i_codec = VLC_CODEC_MP4V;
4279 case 0x21: /* h264 */
4280 p_fmt->i_codec = VLC_CODEC_H264;
4287 case 0x65: /* mpeg2 */
4288 p_fmt->i_codec = VLC_CODEC_MPGV;
4290 case 0x6a: /* mpeg1 */
4291 p_fmt->i_codec = VLC_CODEC_MPGV;
4293 case 0x6c: /* mpeg1 */
4294 p_fmt->i_codec = VLC_CODEC_JPEG;
4297 p_fmt->i_cat = UNKNOWN_ES;
4301 else if( dcd->i_streamType == 0x05 ) /* AudioStream */
4303 p_fmt->i_cat = AUDIO_ES;
4304 switch( dcd->i_objectTypeIndication )
4306 case 0x40: /* mpeg4 */
4307 p_fmt->i_codec = VLC_CODEC_MP4A;
4311 case 0x68: /* mpeg2 aac */
4312 p_fmt->i_codec = VLC_CODEC_MP4A;
4314 case 0x69: /* mpeg2 */
4315 p_fmt->i_codec = VLC_CODEC_MPGA;
4317 case 0x6b: /* mpeg1 */
4318 p_fmt->i_codec = VLC_CODEC_MPGA;
4321 p_fmt->i_cat = UNKNOWN_ES;
4327 p_fmt->i_cat = UNKNOWN_ES;
4330 if( p_fmt->i_cat != UNKNOWN_ES )
4332 p_fmt->i_extra = __MIN(dcd->i_extra, INT32_MAX);
4333 if( p_fmt->i_extra > 0 )
4335 p_fmt->p_extra = malloc( p_fmt->i_extra );
4336 if( p_fmt->p_extra )
4337 memcpy( p_fmt->p_extra, dcd->p_extra, p_fmt->i_extra );
4350 } ts_teletext_page_t;
4352 static void PMTSetupEsTeletext( demux_t *p_demux, ts_pes_t *p_pes,
4353 const dvbpsi_pmt_es_t *p_dvbpsies )
4355 es_format_t *p_fmt = &p_pes->es.fmt;
4357 ts_teletext_page_t p_page[2 * 64 + 20];
4358 unsigned i_page = 0;
4360 /* Gather pages information */
4361 for( unsigned i_tag_idx = 0; i_tag_idx < 2; i_tag_idx++ )
4363 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, i_tag_idx == 0 ? 0x46 : 0x56 );
4367 dvbpsi_teletext_dr_t *p_sub = dvbpsi_DecodeTeletextDr( p_dr );
4371 for( int i = 0; i < p_sub->i_pages_number; i++ )
4373 const dvbpsi_teletextpage_t *p_src = &p_sub->p_pages[i];
4375 if( p_src->i_teletext_type >= 0x06 )
4378 assert( i_page < sizeof(p_page)/sizeof(*p_page) );
4380 ts_teletext_page_t *p_dst = &p_page[i_page++];
4382 p_dst->i_type = p_src->i_teletext_type;
4383 p_dst->i_magazine = p_src->i_teletext_magazine_number
4384 ? p_src->i_teletext_magazine_number : 8;
4385 p_dst->i_page = p_src->i_teletext_page_number;
4386 memcpy( p_dst->p_iso639, p_src->i_iso6392_language_code, 3 );
4390 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x59 );
4393 dvbpsi_subtitling_dr_t *p_sub = dvbpsi_DecodeSubtitlingDr( p_dr );
4394 for( int i = 0; p_sub && i < p_sub->i_subtitles_number; i++ )
4396 dvbpsi_subtitle_t *p_src = &p_sub->p_subtitle[i];
4398 if( p_src->i_subtitling_type < 0x01 || p_src->i_subtitling_type > 0x03 )
4401 assert( i_page < sizeof(p_page)/sizeof(*p_page) );
4403 ts_teletext_page_t *p_dst = &p_page[i_page++];
4405 switch( p_src->i_subtitling_type )
4408 p_dst->i_type = 0x02;
4411 p_dst->i_type = 0x03;
4414 /* FIXME check if it is the right split */
4415 p_dst->i_magazine = (p_src->i_composition_page_id >> 8)
4416 ? (p_src->i_composition_page_id >> 8) : 8;
4417 p_dst->i_page = p_src->i_composition_page_id & 0xff;
4418 memcpy( p_dst->p_iso639, p_src->i_iso6392_language_code, 3 );
4423 es_format_Init( p_fmt, SPU_ES, VLC_CODEC_TELETEXT );
4425 if( !p_demux->p_sys->b_split_es || i_page <= 0 )
4427 p_fmt->subs.teletext.i_magazine = -1;
4428 p_fmt->subs.teletext.i_page = 0;
4429 p_fmt->psz_description = strdup( vlc_gettext(ppsz_teletext_type[1]) );
4431 dvbpsi_descriptor_t *p_dr;
4432 p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x46 );
4434 p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x56 );
4436 if( !p_demux->p_sys->b_split_es && p_dr && p_dr->i_length > 0 )
4438 /* Descriptor pass-through */
4439 p_fmt->p_extra = malloc( p_dr->i_length );
4440 if( p_fmt->p_extra )
4442 p_fmt->i_extra = p_dr->i_length;
4443 memcpy( p_fmt->p_extra, p_dr->p_data, p_dr->i_length );
4449 for( unsigned i = 0; i < i_page; i++ )
4451 ts_pes_es_t *p_page_es;
4456 p_page_es = &p_pes->es;
4460 p_page_es = calloc( 1, sizeof(*p_page_es) );
4464 es_format_Copy( &p_page_es->fmt, p_fmt );
4465 free( p_page_es->fmt.psz_language );
4466 free( p_page_es->fmt.psz_description );
4467 p_page_es->fmt.psz_language = NULL;
4468 p_page_es->fmt.psz_description = NULL;
4470 ARRAY_APPEND( p_pes->extra_es, p_page_es );
4474 const ts_teletext_page_t *p = &p_page[i];
4475 p_page_es->fmt.i_priority = (p->i_type == 0x02 || p->i_type == 0x05) ?
4476 ES_PRIORITY_SELECTABLE_MIN : ES_PRIORITY_NOT_DEFAULTABLE;
4477 p_page_es->fmt.psz_language = strndup( p->p_iso639, 3 );
4478 p_page_es->fmt.psz_description = strdup(vlc_gettext(ppsz_teletext_type[p->i_type]));
4479 p_page_es->fmt.subs.teletext.i_magazine = p->i_magazine;
4480 p_page_es->fmt.subs.teletext.i_page = p->i_page;
4483 " * ttxt type=%s lan=%s page=%d%02x",
4484 p_page_es->fmt.psz_description,
4485 p_page_es->fmt.psz_language,
4486 p->i_magazine, p->i_page );
4490 static void PMTSetupEsDvbSubtitle( demux_t *p_demux, ts_pes_t *p_pes,
4491 const dvbpsi_pmt_es_t *p_dvbpsies )
4493 es_format_t *p_fmt = &p_pes->es.fmt;
4495 es_format_Init( p_fmt, SPU_ES, VLC_CODEC_DVBS );
4497 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x59 );
4499 dvbpsi_subtitling_dr_t *p_sub = dvbpsi_DecodeSubtitlingDr( p_dr );
4500 for( int i = 0; p_sub && i < p_sub->i_subtitles_number; i++ )
4502 const int i_type = p_sub->p_subtitle[i].i_subtitling_type;
4503 if( ( i_type >= 0x10 && i_type <= 0x14 ) ||
4504 ( i_type >= 0x20 && i_type <= 0x24 ) )
4508 if( !p_demux->p_sys->b_split_es || i_page <= 0 )
4510 p_fmt->subs.dvb.i_id = -1;
4511 p_fmt->psz_description = strdup( _("DVB subtitles") );
4513 if( !p_demux->p_sys->b_split_es && p_dr && p_dr->i_length > 0 )
4515 /* Descriptor pass-through */
4516 p_fmt->p_extra = malloc( p_dr->i_length );
4517 if( p_fmt->p_extra )
4519 p_fmt->i_extra = p_dr->i_length;
4520 memcpy( p_fmt->p_extra, p_dr->p_data, p_dr->i_length );
4526 for( int i = 0; i < p_sub->i_subtitles_number; i++ )
4528 ts_pes_es_t *p_subs_es;
4533 p_subs_es = &p_pes->es;
4537 p_subs_es = malloc( sizeof(*p_subs_es) );
4541 es_format_Copy( &p_subs_es->fmt, p_fmt );
4542 free( p_subs_es->fmt.psz_language );
4543 free( p_subs_es->fmt.psz_description );
4544 p_subs_es->fmt.psz_language = NULL;
4545 p_subs_es->fmt.psz_description = NULL;
4547 ARRAY_APPEND( p_pes->extra_es, p_subs_es );
4551 const dvbpsi_subtitle_t *p = &p_sub->p_subtitle[i];
4552 p_subs_es->fmt.psz_language = strndup( (char *)p->i_iso6392_language_code, 3 );
4553 switch( p->i_subtitling_type )
4555 case 0x10: /* unspec. */
4556 case 0x11: /* 4:3 */
4557 case 0x12: /* 16:9 */
4558 case 0x13: /* 2.21:1 */
4559 case 0x14: /* HD monitor */
4560 p_subs_es->fmt.psz_description = strdup( _("DVB subtitles") );
4562 case 0x20: /* Hearing impaired unspec. */
4563 case 0x21: /* h.i. 4:3 */
4564 case 0x22: /* h.i. 16:9 */
4565 case 0x23: /* h.i. 2.21:1 */
4566 case 0x24: /* h.i. HD monitor */
4567 p_subs_es->fmt.psz_description = strdup( _("DVB subtitles: hearing impaired") );
4574 p_subs_es->fmt.subs.dvb.i_id = ( p->i_composition_page_id << 0 ) |
4575 ( p->i_ancillary_page_id << 16 );
4580 static int vlc_ceil_log2( const unsigned int val )
4582 int n = 31 - clz(val);
4583 if ((1U << n) != val)
4589 static void OpusSetup(demux_t *demux, uint8_t *p, size_t len, es_format_t *p_fmt)
4593 /* default mapping */
4594 static const unsigned char map[8] = { 0, 1, 2, 3, 4, 5, 6, 7 };
4595 memcpy(h.stream_map, map, sizeof(map));
4599 int stream_count = 0;
4600 int ccc = p[1]; // channel_config_code
4604 mapping = channels > 2;
4607 channels = 2; // dual mono
4609 static const uint8_t p_csc[8] = { 0, 1, 1, 2, 2, 2, 3, 3 };
4610 csc = p_csc[channels - 1];
4611 stream_count = channels - csc;
4613 static const uint8_t map[6][7] = {
4622 memcpy(&h.stream_map[1], map[channels-3], channels - 1);
4623 } else if (ccc == 0x81) {
4625 goto explicit_config_too_short;
4632 bs_init(&s, &p[4], len - 4);
4635 int bits = vlc_ceil_log2(channels);
4636 if (s.i_left < bits)
4637 goto explicit_config_too_short;
4638 stream_count = bs_read(&s, bits) + 1;
4639 bits = vlc_ceil_log2(stream_count + 1);
4640 if (s.i_left < bits)
4641 goto explicit_config_too_short;
4642 csc = bs_read(&s, bits);
4644 int channel_bits = vlc_ceil_log2(stream_count + csc + 1);
4645 if (s.i_left < channels * channel_bits)
4646 goto explicit_config_too_short;
4648 unsigned char silence = (1U << (stream_count + csc + 1)) - 1;
4649 for (int i = 0; i < channels; i++) {
4650 unsigned char m = bs_read(&s, channel_bits);
4653 h.stream_map[i] = m;
4656 } else if (ccc >= 0x80 && ccc <= 0x88) {
4657 channels = ccc - 0x80;
4662 channels = 2; // dual mono
4665 stream_count = channels;
4667 msg_Err(demux, "Opus channel configuration 0x%.2x is reserved", ccc);
4671 msg_Err(demux, "Opus channel configuration 0x%.2x not supported yet", p[1]);
4675 opus_prepare_header(channels, 0, &h);
4677 h.input_sample_rate = 48000;
4679 h.nb_streams = channels - csc;
4680 h.channel_mapping = mapping;
4683 opus_write_header((uint8_t**)&p_fmt->p_extra, &p_fmt->i_extra, &h, NULL /* FIXME */);
4684 if (p_fmt->p_extra) {
4685 p_fmt->i_cat = AUDIO_ES;
4686 p_fmt->i_codec = VLC_CODEC_OPUS;
4687 p_fmt->audio.i_channels = h.channels;
4688 p_fmt->audio.i_rate = 48000;
4694 explicit_config_too_short:
4695 msg_Err(demux, "Opus descriptor too short");
4698 static void PMTSetupEs0x06( demux_t *p_demux, ts_pes_t *p_pes,
4699 const dvbpsi_pmt_es_t *p_dvbpsies )
4701 es_format_t *p_fmt = &p_pes->es.fmt;
4702 dvbpsi_descriptor_t *p_subs_dr = PMTEsFindDescriptor( p_dvbpsies, 0x59 );
4703 dvbpsi_descriptor_t *desc;
4705 if( PMTEsHasRegistration( p_demux, p_dvbpsies, "AC-3" ) ||
4706 PMTEsFindDescriptor( p_dvbpsies, 0x6a ) ||
4707 PMTEsFindDescriptor( p_dvbpsies, 0x81 ) )
4709 p_fmt->i_cat = AUDIO_ES;
4710 p_fmt->i_codec = VLC_CODEC_A52;
4712 else if( (desc = PMTEsFindDescriptor( p_dvbpsies, 0x7f ) ) && desc->i_length >= 2 &&
4713 PMTEsHasRegistration(p_demux, p_dvbpsies, "Opus"))
4715 OpusSetup(p_demux, desc->p_data, desc->i_length, p_fmt);
4717 else if( PMTEsFindDescriptor( p_dvbpsies, 0x7a ) )
4719 /* DVB with stream_type 0x06 (ETS EN 300 468) */
4720 p_fmt->i_cat = AUDIO_ES;
4721 p_fmt->i_codec = VLC_CODEC_EAC3;
4723 else if( PMTEsHasRegistration( p_demux, p_dvbpsies, "DTS1" ) ||
4724 PMTEsHasRegistration( p_demux, p_dvbpsies, "DTS2" ) ||
4725 PMTEsHasRegistration( p_demux, p_dvbpsies, "DTS3" ) ||
4726 PMTEsFindDescriptor( p_dvbpsies, 0x73 ) )
4728 /*registration descriptor(ETSI TS 101 154 Annex F)*/
4729 p_fmt->i_cat = AUDIO_ES;
4730 p_fmt->i_codec = VLC_CODEC_DTS;
4732 else if( PMTEsHasRegistration( p_demux, p_dvbpsies, "BSSD" ) && !p_subs_dr )
4734 /* BSSD is AES3 DATA, but could also be subtitles
4735 * we need to check for secondary descriptor then s*/
4736 p_fmt->i_cat = AUDIO_ES;
4737 p_fmt->b_packetized = true;
4738 p_fmt->i_codec = VLC_CODEC_302M;
4740 else if( PMTEsHasRegistration( p_demux, p_dvbpsies, "HEVC" ) )
4742 p_fmt->i_cat = VIDEO_ES;
4743 p_fmt->i_codec = VLC_CODEC_HEVC;
4745 else if ( p_demux->p_sys->arib.e_mode == ARIBMODE_ENABLED )
4747 /* Lookup our data component descriptor first ARIB STD B10 6.4 */
4748 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0xFD );
4749 /* and check that it maps to something ARIB STD B14 Table 5.1/5.2 */
4750 if ( p_dr && p_dr->i_length >= 2 )
4752 if( !memcmp( p_dr->p_data, "\x00\x08", 2 ) && (
4753 PMTEsHasComponentTag( p_dvbpsies, 0x30 ) ||
4754 PMTEsHasComponentTag( p_dvbpsies, 0x31 ) ||
4755 PMTEsHasComponentTag( p_dvbpsies, 0x32 ) ||
4756 PMTEsHasComponentTag( p_dvbpsies, 0x33 ) ||
4757 PMTEsHasComponentTag( p_dvbpsies, 0x34 ) ||
4758 PMTEsHasComponentTag( p_dvbpsies, 0x35 ) ||
4759 PMTEsHasComponentTag( p_dvbpsies, 0x36 ) ||
4760 PMTEsHasComponentTag( p_dvbpsies, 0x37 ) ) )
4762 es_format_Init( p_fmt, SPU_ES, VLC_CODEC_ARIB_A );
4763 p_fmt->psz_language = strndup ( "jpn", 3 );
4764 p_fmt->psz_description = strdup( _("ARIB subtitles") );
4766 else if( !memcmp( p_dr->p_data, "\x00\x12", 2 ) && (
4767 PMTEsHasComponentTag( p_dvbpsies, 0x87 ) ||
4768 PMTEsHasComponentTag( p_dvbpsies, 0x88 ) ) )
4770 es_format_Init( p_fmt, SPU_ES, VLC_CODEC_ARIB_C );
4771 p_fmt->psz_language = strndup ( "jpn", 3 );
4772 p_fmt->psz_description = strdup( _("ARIB subtitles") );
4778 /* Subtitle/Teletext/VBI fallbacks */
4779 dvbpsi_subtitling_dr_t *p_sub;
4780 if( p_subs_dr && ( p_sub = dvbpsi_DecodeSubtitlingDr( p_subs_dr ) ) )
4782 for( int i = 0; i < p_sub->i_subtitles_number; i++ )
4784 if( p_fmt->i_cat != UNKNOWN_ES )
4787 switch( p_sub->p_subtitle[i].i_subtitling_type )
4789 case 0x01: /* EBU Teletext subtitles */
4790 case 0x02: /* Associated EBU Teletext */
4791 case 0x03: /* VBI data */
4792 PMTSetupEsTeletext( p_demux, p_pes, p_dvbpsies );
4794 case 0x10: /* DVB Subtitle (normal) with no monitor AR critical */
4795 case 0x11: /* ... on 4:3 AR monitor */
4796 case 0x12: /* ... on 16:9 AR monitor */
4797 case 0x13: /* ... on 2.21:1 AR monitor */
4798 case 0x14: /* ... for display on a high definition monitor */
4799 case 0x20: /* DVB Subtitle (impaired) with no monitor AR critical */
4800 case 0x21: /* ... on 4:3 AR monitor */
4801 case 0x22: /* ... on 16:9 AR monitor */
4802 case 0x23: /* ... on 2.21:1 AR monitor */
4803 case 0x24: /* ... for display on a high definition monitor */
4804 PMTSetupEsDvbSubtitle( p_demux, p_pes, p_dvbpsies );
4807 msg_Err( p_demux, "Unrecognized DVB subtitle type (0x%x)",
4808 p_sub->p_subtitle[i].i_subtitling_type );
4814 if( p_fmt->i_cat == UNKNOWN_ES &&
4815 ( PMTEsFindDescriptor( p_dvbpsies, 0x45 ) || /* VBI Data descriptor */
4816 PMTEsFindDescriptor( p_dvbpsies, 0x46 ) || /* VBI Teletext descriptor */
4817 PMTEsFindDescriptor( p_dvbpsies, 0x56 ) ) ) /* EBU Teletext descriptor */
4820 PMTSetupEsTeletext( p_demux, p_pes, p_dvbpsies );
4824 /* FIXME is it useful ? */
4825 if( PMTEsFindDescriptor( p_dvbpsies, 0x52 ) )
4827 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x52 );
4828 dvbpsi_stream_identifier_dr_t *p_si = dvbpsi_DecodeStreamIdentifierDr( p_dr );
4830 msg_Dbg( p_demux, " * Stream Component Identifier: %d", p_si->i_component_tag );
4834 static void PMTSetupEs0xEA( demux_t *p_demux, ts_pes_es_t *p_es,
4835 const dvbpsi_pmt_es_t *p_dvbpsies )
4837 /* Registration Descriptor */
4838 if( !PMTEsHasRegistration( p_demux, p_dvbpsies, "VC-1" ) )
4840 msg_Err( p_demux, "Registration descriptor not found or invalid" );
4844 es_format_t *p_fmt = &p_es->fmt;
4846 /* registration descriptor for VC-1 (SMPTE rp227) */
4847 p_fmt->i_cat = VIDEO_ES;
4848 p_fmt->i_codec = VLC_CODEC_VC1;
4850 /* XXX With Simple and Main profile the SEQUENCE
4851 * header is modified: video width and height are
4852 * inserted just after the start code as 2 int16_t
4853 * The packetizer will take care of that. */
4856 static void PMTSetupEs0xD1( demux_t *p_demux, ts_pes_es_t *p_es,
4857 const dvbpsi_pmt_es_t *p_dvbpsies )
4859 /* Registration Descriptor */
4860 if( !PMTEsHasRegistration( p_demux, p_dvbpsies, "drac" ) )
4862 msg_Err( p_demux, "Registration descriptor not found or invalid" );
4866 es_format_t *p_fmt = &p_es->fmt;
4868 /* registration descriptor for Dirac
4869 * (backwards compatable with VC-2 (SMPTE Sxxxx:2008)) */
4870 p_fmt->i_cat = VIDEO_ES;
4871 p_fmt->i_codec = VLC_CODEC_DIRAC;
4874 static void PMTSetupEs0xA0( demux_t *p_demux, ts_pes_es_t *p_es,
4875 const dvbpsi_pmt_es_t *p_dvbpsies )
4877 /* MSCODEC sent by vlc */
4878 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0xa0 );
4879 if( !p_dr || p_dr->i_length < 10 )
4882 "private MSCODEC (vlc) without bih private descriptor" );
4886 es_format_t *p_fmt = &p_es->fmt;
4887 p_fmt->i_cat = VIDEO_ES;
4888 p_fmt->i_codec = VLC_FOURCC( p_dr->p_data[0], p_dr->p_data[1],
4889 p_dr->p_data[2], p_dr->p_data[3] );
4890 p_fmt->video.i_width = GetWBE( &p_dr->p_data[4] );
4891 p_fmt->video.i_height = GetWBE( &p_dr->p_data[6] );
4892 p_fmt->i_extra = GetWBE( &p_dr->p_data[8] );
4894 if( p_fmt->i_extra > 0 )
4896 p_fmt->p_extra = malloc( p_fmt->i_extra );
4897 if( p_fmt->p_extra )
4898 memcpy( p_fmt->p_extra, &p_dr->p_data[10],
4899 __MIN( p_fmt->i_extra, p_dr->i_length - 10 ) );
4903 /* For such stream we will gather them ourself and don't launch a
4905 * Yes it's ugly but it's the only way to have DIV3 working */
4906 p_fmt->b_packetized = true;
4909 static void PMTSetupEs0x83( const dvbpsi_pmt_t *p_pmt, ts_pes_es_t *p_es, int i_pid )
4911 /* WiDi broadcasts without registration on PMT 0x1, PCR 0x1000 and
4912 * with audio track pid being 0x1100..0x11FF */
4913 if ( p_pmt->i_program_number == 0x1 &&
4914 p_pmt->i_pcr_pid == 0x1000 &&
4915 ( i_pid >> 8 ) == 0x11 )
4917 /* Not enough ? might contain 0x83 private descriptor, 2 bytes 0x473F */
4918 es_format_Init( &p_es->fmt, AUDIO_ES, VLC_CODEC_WIDI_LPCM );
4921 es_format_Init( &p_es->fmt, AUDIO_ES, VLC_CODEC_DVD_LPCM );
4924 static bool PMTSetupEsHDMV( demux_t *p_demux, ts_pes_es_t *p_es,
4925 const dvbpsi_pmt_es_t *p_dvbpsies )
4927 es_format_t *p_fmt = &p_es->fmt;
4929 /* Blu-Ray mapping */
4930 switch( p_dvbpsies->i_type )
4933 p_fmt->i_cat = AUDIO_ES;
4934 p_fmt->i_codec = VLC_CODEC_BD_LPCM;
4937 p_fmt->i_cat = AUDIO_ES;
4938 p_fmt->i_codec = VLC_CODEC_A52;
4941 case 0x85: /* DTS-HD High resolution audio */
4942 case 0x86: /* DTS-HD Master audio */
4943 case 0xA2: /* Secondary DTS audio */
4944 p_fmt->i_cat = AUDIO_ES;
4945 p_fmt->i_codec = VLC_CODEC_DTS;
4948 case 0x83: /* TrueHD AC3 */
4949 p_fmt->i_cat = AUDIO_ES;
4950 p_fmt->i_codec = VLC_CODEC_TRUEHD;
4953 case 0x84: /* E-AC3 */
4954 case 0xA1: /* Secondary E-AC3 */
4955 p_fmt->i_cat = AUDIO_ES;
4956 p_fmt->i_codec = VLC_CODEC_EAC3;
4958 case 0x90: /* Presentation graphics */
4959 p_fmt->i_cat = SPU_ES;
4960 p_fmt->i_codec = VLC_CODEC_BD_PG;
4962 case 0x91: /* Interactive graphics */
4963 case 0x92: /* Subtitle */
4966 p_fmt->i_cat = VIDEO_ES;
4967 p_fmt->i_codec = VLC_CODEC_VC1;
4970 msg_Info( p_demux, "HDMV registration not implemented for pid 0x%x type 0x%x",
4971 p_dvbpsies->i_pid, p_dvbpsies->i_type );
4978 static bool PMTSetupEsRegistration( demux_t *p_demux, ts_pes_es_t *p_es,
4979 const dvbpsi_pmt_es_t *p_dvbpsies )
4985 vlc_fourcc_t i_codec;
4987 { "AC-3", AUDIO_ES, VLC_CODEC_A52 },
4988 { "DTS1", AUDIO_ES, VLC_CODEC_DTS },
4989 { "DTS2", AUDIO_ES, VLC_CODEC_DTS },
4990 { "DTS3", AUDIO_ES, VLC_CODEC_DTS },
4991 { "BSSD", AUDIO_ES, VLC_CODEC_302M },
4992 { "VC-1", VIDEO_ES, VLC_CODEC_VC1 },
4993 { "drac", VIDEO_ES, VLC_CODEC_DIRAC },
4994 { "", UNKNOWN_ES, 0 }
4996 es_format_t *p_fmt = &p_es->fmt;
4998 for( int i = 0; p_regs[i].i_cat != UNKNOWN_ES; i++ )
5000 if( PMTEsHasRegistration( p_demux, p_dvbpsies, p_regs[i].psz_tag ) )
5002 p_fmt->i_cat = p_regs[i].i_cat;
5003 p_fmt->i_codec = p_regs[i].i_codec;
5004 if (p_dvbpsies->i_type == 0x87)
5005 p_fmt->i_codec = VLC_CODEC_EAC3;
5012 static char *GetAudioTypeDesc(demux_t *p_demux, int type)
5014 static const char *audio_type[] = {
5016 N_("clean effects"),
5017 N_("hearing impaired"),
5018 N_("visual impaired commentary"),
5021 if (type < 0 || type > 3)
5022 msg_Dbg( p_demux, "unknown audio type: %d", type);
5024 return strdup(audio_type[type]);
5028 static void PMTParseEsIso639( demux_t *p_demux, ts_pes_es_t *p_es,
5029 const dvbpsi_pmt_es_t *p_dvbpsies )
5031 /* get language descriptor */
5032 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x0a );
5037 dvbpsi_iso639_dr_t *p_decoded = dvbpsi_DecodeISO639Dr( p_dr );
5040 msg_Err( p_demux, "Failed to decode a ISO 639 descriptor" );
5044 #if defined(DR_0A_API_VER) && (DR_0A_API_VER >= 2)
5045 p_es->fmt.psz_language = malloc( 4 );
5046 if( p_es->fmt.psz_language )
5048 memcpy( p_es->fmt.psz_language, p_decoded->code[0].iso_639_code, 3 );
5049 p_es->fmt.psz_language[3] = 0;
5050 msg_Dbg( p_demux, "found language: %s", p_es->fmt.psz_language);
5052 int type = p_decoded->code[0].i_audio_type;
5053 p_es->fmt.psz_description = GetAudioTypeDesc(p_demux, type);
5055 p_es->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN + 1; // prioritize normal audio tracks
5057 p_es->fmt.i_extra_languages = p_decoded->i_code_count-1;
5058 if( p_es->fmt.i_extra_languages > 0 )
5059 p_es->fmt.p_extra_languages =
5060 malloc( sizeof(*p_es->fmt.p_extra_languages) *
5061 p_es->fmt.i_extra_languages );
5062 if( p_es->fmt.p_extra_languages )
5064 for( unsigned i = 0; i < p_es->fmt.i_extra_languages; i++ )
5066 p_es->fmt.p_extra_languages[i].psz_language = malloc(4);
5067 if( p_es->fmt.p_extra_languages[i].psz_language )
5069 memcpy( p_es->fmt.p_extra_languages[i].psz_language,
5070 p_decoded->code[i+1].iso_639_code, 3 );
5071 p_es->fmt.p_extra_languages[i].psz_language[3] = '\0';
5073 int type = p_decoded->code[i].i_audio_type;
5074 p_es->fmt.p_extra_languages[i].psz_description = GetAudioTypeDesc(p_demux, type);
5078 p_es->fmt.psz_language = malloc( 4 );
5079 if( p_es->fmt.psz_language )
5081 memcpy( p_es->fmt.psz_language,
5082 p_decoded->i_iso_639_code, 3 );
5083 p_es->fmt.psz_language[3] = 0;
5088 static inline void SetExtraESGroupAndID( demux_sys_t *p_sys, es_format_t *p_fmt,
5089 const es_format_t *p_parent_fmt )
5091 if ( p_sys->b_es_id_pid ) /* pid is 13 bits */
5092 p_fmt->i_id = (p_sys->i_next_extraid++ << 13) | p_parent_fmt->i_id;
5093 p_fmt->i_group = p_parent_fmt->i_group;
5096 static void AddAndCreateES( demux_t *p_demux, ts_pid_t *pid, bool b_create_delayed )
5098 demux_sys_t *p_sys = p_demux->p_sys;
5100 if( b_create_delayed )
5101 p_sys->es_creation = CREATE_ES;
5103 if( pid && p_sys->es_creation == CREATE_ES )
5105 /* FIXME: other owners / shared pid */
5106 pid->u.p_pes->es.id = es_out_Add( p_demux->out, &pid->u.p_pes->es.fmt );
5107 for( int i = 0; i < pid->u.p_pes->extra_es.i_size; i++ )
5109 es_format_t *p_fmt = &pid->u.p_pes->extra_es.p_elems[i]->fmt;
5110 SetExtraESGroupAndID( p_sys, p_fmt, &pid->u.p_pes->es.fmt );
5111 pid->u.p_pes->extra_es.p_elems[i]->id = es_out_Add( p_demux->out, p_fmt );
5113 p_sys->i_pmt_es += 1 + pid->u.p_pes->extra_es.i_size;
5115 /* Update the default program == first created ES group */
5116 if( p_sys->b_default_selection )
5118 p_sys->b_default_selection = false;
5119 assert(p_sys->programs.i_size == 1);
5120 if( p_sys->programs.p_elems[0] != pid->p_parent->u.p_pmt->i_number )
5121 p_sys->programs.p_elems[0] = pid->p_parent->u.p_pmt->i_number;
5122 msg_Dbg( p_demux, "Default program is %d", pid->p_parent->u.p_pmt->i_number );
5126 if( b_create_delayed )
5128 ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
5129 for( int i=0; i< p_pat->programs.i_size; i++ )
5131 ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
5132 for( int j=0; j<p_pmt->e_streams.i_size; j++ )
5134 ts_pid_t *pid = p_pmt->e_streams.p_elems[j];
5135 if( pid->u.p_pes->es.id )
5138 pid->u.p_pes->es.id = es_out_Add( p_demux->out, &pid->u.p_pes->es.fmt );
5139 for( int k = 0; k < pid->u.p_pes->extra_es.i_size; k++ )
5141 es_format_t *p_fmt = &pid->u.p_pes->extra_es.p_elems[k]->fmt;
5142 SetExtraESGroupAndID( p_sys, p_fmt, &pid->u.p_pes->es.fmt );
5143 pid->u.p_pes->extra_es.p_elems[k]->id = es_out_Add( p_demux->out, p_fmt );
5145 p_sys->i_pmt_es += 1 + pid->u.p_pes->extra_es.i_size;
5150 UpdatePESFilters( p_demux, p_sys->b_es_all );
5153 static void PMTCallBack( void *data, dvbpsi_pmt_t *p_dvbpsipmt )
5155 demux_t *p_demux = data;
5156 demux_sys_t *p_sys = p_demux->p_sys;
5158 ts_pid_t *pmtpid = NULL;
5159 ts_pmt_t *p_pmt = NULL;
5161 msg_Dbg( p_demux, "PMTCallBack called" );
5163 if (unlikely(PID(p_sys, 0)->type != TYPE_PAT))
5165 assert(PID(p_sys, 0)->type == TYPE_PAT);
5166 dvbpsi_pmt_delete(p_dvbpsipmt);
5169 const ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
5171 /* First find this PMT declared in PAT */
5172 for( int i = 0; !pmtpid && i < p_pat->programs.i_size; i++ )
5174 const int i_pmt_prgnumber = p_pat->programs.p_elems[i]->u.p_pmt->i_number;
5175 if( i_pmt_prgnumber != TS_USER_PMT_NUMBER &&
5176 i_pmt_prgnumber == p_dvbpsipmt->i_program_number )
5178 pmtpid = p_pat->programs.p_elems[i];
5179 assert(pmtpid->type == TYPE_PMT);
5180 p_pmt = pmtpid->u.p_pmt;
5184 if( pmtpid == NULL )
5186 msg_Warn( p_demux, "unreferenced program (broken stream)" );
5187 dvbpsi_pmt_delete(p_dvbpsipmt);
5191 pmtpid->i_flags |= FLAG_SEEN;
5193 if( p_pmt->i_version != -1 &&
5194 ( !p_dvbpsipmt->b_current_next || p_pmt->i_version == p_dvbpsipmt->i_version ) )
5196 dvbpsi_pmt_delete( p_dvbpsipmt );
5200 /* Save old es array */
5201 DECL_ARRAY(ts_pid_t *) old_es_rm;
5202 old_es_rm.i_alloc = p_pmt->e_streams.i_alloc;
5203 old_es_rm.i_size = p_pmt->e_streams.i_size;
5204 old_es_rm.p_elems = p_pmt->e_streams.p_elems;
5205 ARRAY_INIT(p_pmt->e_streams);
5209 IODFree( p_pmt->iod );
5213 msg_Dbg( p_demux, "new PMT program number=%d version=%d pid_pcr=%d",
5214 p_dvbpsipmt->i_program_number, p_dvbpsipmt->i_version, p_dvbpsipmt->i_pcr_pid );
5215 p_pmt->i_pid_pcr = p_dvbpsipmt->i_pcr_pid;
5216 p_pmt->i_version = p_dvbpsipmt->i_version;
5218 ValidateDVBMeta( p_demux, p_pmt->i_pid_pcr );
5220 if( ProgramIsSelected( p_sys, p_pmt->i_number ) )
5221 SetPIDFilter( p_sys, PID(p_sys, p_pmt->i_pid_pcr), true ); /* Set demux filter */
5223 /* Parse PMT descriptors */
5224 ts_pmt_registration_type_t registration_type = TS_PMT_REGISTRATION_NONE;
5225 dvbpsi_descriptor_t *p_dr;
5227 /* First pass for standard detection */
5228 if ( p_sys->arib.e_mode == ARIBMODE_AUTO )
5230 int i_arib_flags = 0; /* Descriptors can be repeated */
5231 for( p_dr = p_dvbpsipmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
5237 dvbpsi_ca_dr_t *p_cadr = dvbpsi_DecodeCADr( p_dr );
5238 i_arib_flags |= (p_cadr->i_ca_system_id == 0x05);
5242 i_arib_flags |= 1 << 1;
5245 i_arib_flags |= 1 << 2;
5251 if ( i_arib_flags == 0x07 ) //0b111
5252 p_sys->arib.e_mode = ARIBMODE_ENABLED;
5255 for( p_dr = p_dvbpsipmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
5257 /* special descriptors handling */
5260 case 0x1d: /* We have found an IOD descriptor */
5261 msg_Dbg( p_demux, " * PMT descriptor : IOD (0x1d)" );
5262 p_pmt->iod = IODNew( p_dr->i_length, p_dr->p_data );
5266 msg_Dbg( p_demux, " * PMT descriptor : CA (0x9) SysID 0x%x",
5267 (p_dr->p_data[0] << 8) | p_dr->p_data[1] );
5270 case 0x5: /* Registration Descriptor */
5271 if( p_dr->i_length != 4 )
5273 msg_Warn( p_demux, " * PMT invalid Registration Descriptor" );
5277 msg_Dbg( p_demux, " * PMT descriptor : registration %4.4s", p_dr->p_data );
5278 if( !memcmp( p_dr->p_data, "HDMV", 4 ) || !memcmp( p_dr->p_data, "HDPR", 4 ) )
5279 registration_type = TS_PMT_REGISTRATION_HDMV; /* Blu-Ray */
5284 msg_Dbg( p_demux, " * PMT descriptor : Private Data (0x0f)" );
5288 msg_Dbg( p_demux, " * PMT descriptor : Digital copy control (0xC1)" );
5291 case 0x88: /* EACEM Simulcast HD Logical channels ordering */
5292 msg_Dbg( p_demux, " * descriptor : EACEM Simulcast HD" );
5293 /* TODO: apply visibility flags */
5297 msg_Dbg( p_demux, " * PMT descriptor : unknown (0x%x)", p_dr->i_tag );
5301 dvbpsi_pmt_es_t *p_dvbpsies;
5302 for( p_dvbpsies = p_dvbpsipmt->p_first_es; p_dvbpsies != NULL; p_dvbpsies = p_dvbpsies->p_next )
5304 bool b_reusing_pid = false;
5307 ts_pid_t *pespid = PID(p_sys, p_dvbpsies->i_pid);
5308 if ( pespid->type == TYPE_PES && pespid->p_parent->u.p_pmt->i_number != p_pmt->i_number )
5310 msg_Warn( p_demux, " * PMT wants to get a share or pid %d (unsupported)", pespid->i_pid );
5314 /* Find out if the PID was already declared */
5315 for( int i = 0; i < old_es_rm.i_size; i++ )
5317 if( old_es_rm.p_elems[i]->i_pid == p_dvbpsies->i_pid )
5319 b_reusing_pid = true;
5323 ValidateDVBMeta( p_demux, p_dvbpsies->i_pid );
5325 char const * psz_typedesc = "";
5326 switch(p_dvbpsies->i_type)
5329 psz_typedesc = "ISO/IEC Reserved";
5332 psz_typedesc = "ISO/IEC 11172 Video";
5335 psz_typedesc = "ISO/IEC 13818-2 Video or ISO/IEC 11172-2 constrained parameter video stream";
5338 psz_typedesc = "ISO/IEC 11172 Audio";
5341 psz_typedesc = "ISO/IEC 13818-3 Audio";
5344 psz_typedesc = "ISO/IEC 13818-1 private_sections";
5347 psz_typedesc = "ISO/IEC 13818-1 PES packets containing private data";
5350 psz_typedesc = "ISO/IEC 13522 MHEG";
5353 psz_typedesc = "ISO/IEC 13818-1 Annex A DSM CC";
5356 psz_typedesc = "ITU-T Rec. H.222.1";
5359 psz_typedesc = "ISO/IEC 13818-6 type A";
5362 psz_typedesc = "ISO/IEC 13818-6 type B";
5365 psz_typedesc = "ISO/IEC 13818-6 type C";
5368 psz_typedesc = "ISO/IEC 13818-6 type D";
5371 psz_typedesc = "ISO/IEC 13818-1 auxiliary";
5374 if (p_dvbpsies->i_type >= 0x0F && p_dvbpsies->i_type <=0x7F)
5375 psz_typedesc = "ISO/IEC 13818-1 Reserved";
5377 psz_typedesc = "User Private";
5380 msg_Dbg( p_demux, " * pid=%d type=0x%x %s",
5381 p_dvbpsies->i_pid, p_dvbpsies->i_type, psz_typedesc );
5383 for( p_dr = p_dvbpsies->p_first_descriptor; p_dr != NULL;
5384 p_dr = p_dr->p_next )
5386 msg_Dbg( p_demux, " - descriptor tag 0x%x",
5390 if ( !PIDSetup( p_demux, TYPE_PES, pespid, pmtpid ) )
5392 msg_Warn( p_demux, " * pid=%d type=0x%x %s (skipped)",
5393 p_dvbpsies->i_pid, p_dvbpsies->i_type, psz_typedesc );
5400 p_pes = ts_pes_New( p_demux );
5406 p_pes = pespid->u.p_pes;
5410 ARRAY_APPEND( p_pmt->e_streams, pespid );
5412 PIDFillFormat( &p_pes->es.fmt, p_dvbpsies->i_type );
5414 pespid->i_flags |= SEEN(PID(p_sys, p_dvbpsies->i_pid));
5416 bool b_registration_applied = false;
5417 if ( p_dvbpsies->i_type >= 0x80 ) /* non standard, extensions */
5419 if ( registration_type == TS_PMT_REGISTRATION_HDMV )
5421 if (( b_registration_applied = PMTSetupEsHDMV( p_demux, &p_pes->es, p_dvbpsies ) ))
5422 msg_Dbg( p_demux, " + HDMV registration applied to pid %d type 0x%x",
5423 p_dvbpsies->i_pid, p_dvbpsies->i_type );
5427 if (( b_registration_applied = PMTSetupEsRegistration( p_demux, &p_pes->es, p_dvbpsies ) ))
5428 msg_Dbg( p_demux, " + registration applied to pid %d type 0x%x",
5429 p_dvbpsies->i_pid, p_dvbpsies->i_type );
5433 if ( !b_registration_applied )
5435 switch( p_dvbpsies->i_type )
5438 /* Handle PES private data */
5439 PMTSetupEs0x06( p_demux, p_pes, p_dvbpsies );
5441 /* All other private or reserved types */
5446 PMTSetupEsISO14496( p_demux, &p_pes->es, p_pmt, p_dvbpsies );
5450 PMTSetupEs0x83( p_dvbpsipmt, &p_pes->es, p_dvbpsies->i_pid );
5453 PMTSetupEs0xA0( p_demux, &p_pes->es, p_dvbpsies );
5456 PMTSetupEs0xD1( p_demux, &p_pes->es, p_dvbpsies );
5459 PMTSetupEs0xEA( p_demux, &p_pes->es, p_dvbpsies );
5465 if( p_pes->es.fmt.i_cat == AUDIO_ES ||
5466 ( p_pes->es.fmt.i_cat == SPU_ES &&
5467 p_pes->es.fmt.i_codec != VLC_CODEC_DVBS &&
5468 p_pes->es.fmt.i_codec != VLC_CODEC_TELETEXT ) )
5470 PMTParseEsIso639( p_demux, &p_pes->es, p_dvbpsies );
5473 switch( p_pes->es.fmt.i_codec )
5475 case VLC_CODEC_SCTE_27:
5476 p_pes->data_type = TS_ES_DATA_TABLE_SECTION;
5479 //pid->es->data_type = TS_ES_DATA_PES;
5483 /* Set Groups / ID */
5484 p_pes->es.fmt.i_group = p_dvbpsipmt->i_program_number;
5485 if( p_sys->b_es_id_pid )
5486 p_pes->es.fmt.i_id = p_dvbpsies->i_pid;
5488 if( p_pes->es.fmt.i_cat == UNKNOWN_ES )
5490 msg_Dbg( p_demux, " => pid %d content is *unknown*",
5491 p_dvbpsies->i_pid );
5492 p_pes->es.fmt.psz_description = strdup( psz_typedesc );
5496 msg_Dbg( p_demux, " => pid %d has now es fcc=%4.4s",
5497 p_dvbpsies->i_pid, (char*)&p_pes->es.fmt.i_codec );
5499 /* Check if we can avoid restarting the ES */
5502 /* p_pes points to a tmp pes */
5503 if( pespid->u.p_pes->es.fmt.i_codec != p_pes->es.fmt.i_codec ||
5504 pespid->u.p_pes->es.fmt.i_extra != p_pes->es.fmt.i_extra ||
5505 pespid->u.p_pes->es.fmt.i_extra != 0 ||
5506 pespid->u.p_pes->extra_es.i_size != p_pes->extra_es.i_size ||
5507 !( ( !pespid->u.p_pes->es.fmt.psz_language &&
5508 !p_pes->es.fmt.psz_language ) ||
5509 ( pespid->u.p_pes->es.fmt.psz_language &&
5510 p_pes->es.fmt.psz_language &&
5511 !strcmp( pespid->u.p_pes->es.fmt.psz_language,
5512 p_pes->es.fmt.psz_language ) ) ) )
5514 /* Differs, swap then */
5515 ts_pes_t *e = pespid->u.p_pes;
5516 pespid->u.p_pes = p_pes;
5519 /* p_pes still tmp, but now contains old config */
5520 pespid->u.p_pes->es.id = p_pes->es.id;
5521 if( pespid->u.p_pes->es.id )
5523 p_pes->es.id = NULL;
5524 es_out_Control( p_demux->out, ES_OUT_SET_ES_FMT,
5525 pespid->u.p_pes->es.id, pespid->u.p_pes->es.fmt );
5528 for( int i=0; i<pespid->u.p_pes->extra_es.i_size &&
5529 i<p_pes->extra_es.i_size; i++ )
5531 pespid->u.p_pes->extra_es.p_elems[i]->id = p_pes->extra_es.p_elems[i]->id;
5532 if( pespid->u.p_pes->extra_es.p_elems[i]->id )
5534 es_out_Control( p_demux->out, ES_OUT_SET_ES_FMT,
5535 pespid->u.p_pes->extra_es.p_elems[i]->id,
5536 pespid->u.p_pes->extra_es.p_elems[i]->fmt );
5537 p_pes->extra_es.p_elems[i]->id = NULL;
5542 ts_pes_Del( p_demux, p_pes ); // delete temp
5546 AddAndCreateES( p_demux, pespid, false );
5550 p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x09 );
5551 if( p_dr && p_dr->i_length >= 2 )
5553 msg_Dbg( p_demux, " * PMT descriptor : CA (0x9) SysID 0x%x",
5554 (p_dr->p_data[0] << 8) | p_dr->p_data[1] );
5558 /* Set CAM descrambling */
5559 if( !ProgramIsSelected( p_sys, p_pmt->i_number ) )
5561 dvbpsi_pmt_delete( p_dvbpsipmt );
5563 else if( stream_Control( p_sys->stream, STREAM_SET_PRIVATE_ID_CA,
5564 p_dvbpsipmt ) != VLC_SUCCESS )
5566 if ( p_sys->arib.e_mode == ARIBMODE_ENABLED && !p_sys->arib.b25stream )
5568 p_sys->arib.b25stream = stream_FilterNew( p_demux->s, "aribcam" );
5569 p_sys->stream = ( p_sys->arib.b25stream ) ? p_sys->arib.b25stream : p_demux->s;
5570 if (!p_sys->arib.b25stream)
5571 dvbpsi_pmt_delete( p_dvbpsipmt );
5572 } else dvbpsi_pmt_delete( p_dvbpsipmt );
5575 /* Decref or clean now unused es */
5576 for( int i = 0; i < old_es_rm.i_size; i++ )
5577 PIDRelease( p_demux, old_es_rm.p_elems[i] );
5578 ARRAY_RESET( old_es_rm );
5580 UpdatePESFilters( p_demux, p_sys->b_es_all );
5582 if( !p_sys->b_trust_pcr )
5584 int i_cand = FindPCRCandidate( p_pmt );
5585 p_pmt->i_pid_pcr = i_cand;
5586 p_pmt->pcr.b_disable = true;
5587 msg_Warn( p_demux, "PCR not trusted for program %d, set up workaround using pid %d",
5588 p_pmt->i_number, i_cand );
5591 /* Probe Boundaries */
5592 if( p_sys->b_canfastseek && p_pmt->i_last_dts == -1 )
5594 p_pmt->i_last_dts = 0;
5595 ProbeStart( p_demux, p_pmt->i_number );
5596 ProbeEnd( p_demux, p_pmt->i_number );
5600 static int PATCheck( demux_t *p_demux, dvbpsi_pat_t *p_pat )
5602 /* Some Dreambox streams have all PMT set to same pid */
5603 int i_prev_pid = -1;
5604 for( dvbpsi_pat_program_t * p_program = p_pat->p_first_program;
5606 p_program = p_program->p_next )
5608 if( p_program->i_pid == i_prev_pid )
5610 msg_Warn( p_demux, "PAT check failed: duplicate program pid %d", i_prev_pid );
5611 return VLC_EGENERIC;
5613 i_prev_pid = p_program->i_pid;
5618 static void PATCallBack( void *data, dvbpsi_pat_t *p_dvbpsipat )
5620 demux_t *p_demux = data;
5621 demux_sys_t *p_sys = p_demux->p_sys;
5622 dvbpsi_pat_program_t *p_program;
5623 ts_pid_t *patpid = PID(p_sys, 0);
5624 ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
5626 patpid->i_flags |= FLAG_SEEN;
5628 msg_Dbg( p_demux, "PATCallBack called" );
5630 if(unlikely( PID(p_sys, 0)->type != TYPE_PAT ))
5632 msg_Warn( p_demux, "PATCallBack called on invalid pid" );
5636 if( ( p_pat->i_version != -1 &&
5637 ( !p_dvbpsipat->b_current_next ||
5638 p_dvbpsipat->i_version == p_pat->i_version ) ) ||
5639 ( p_pat->i_ts_id != -1 && p_dvbpsipat->i_ts_id != p_pat->i_ts_id ) ||
5640 p_sys->b_user_pmt || PATCheck( p_demux, p_dvbpsipat ) )
5642 dvbpsi_pat_delete( p_dvbpsipat );
5646 msg_Dbg( p_demux, "new PAT ts_id=%d version=%d current_next=%d",
5647 p_dvbpsipat->i_ts_id, p_dvbpsipat->i_version, p_dvbpsipat->b_current_next );
5649 /* Save old programs array */
5650 DECL_ARRAY(ts_pid_t *) old_pmt_rm;
5651 old_pmt_rm.i_alloc = p_pat->programs.i_alloc;
5652 old_pmt_rm.i_size = p_pat->programs.i_size;
5653 old_pmt_rm.p_elems = p_pat->programs.p_elems;
5654 ARRAY_INIT(p_pat->programs);
5656 /* now create programs */
5657 for( p_program = p_dvbpsipat->p_first_program; p_program != NULL;
5658 p_program = p_program->p_next )
5660 msg_Dbg( p_demux, " * number=%d pid=%d", p_program->i_number,
5662 if( p_program->i_number == 0 )
5665 ts_pid_t *pmtpid = PID(p_sys, p_program->i_pid);
5667 ValidateDVBMeta( p_demux, p_program->i_pid );
5669 /* create or temporary incref pid */
5670 if( !PIDSetup( p_demux, TYPE_PMT, pmtpid, patpid ) )
5672 msg_Warn( p_demux, " * number=%d pid=%d (ignored)", p_program->i_number,
5677 pmtpid->u.p_pmt->i_number = p_program->i_number;
5679 if( !dvbpsi_pmt_attach( pmtpid->u.p_pmt->handle, p_program->i_number, PMTCallBack, p_demux ) )
5680 msg_Err( p_demux, "PATCallback failed attaching PMTCallback to program %d",
5681 p_program->i_number );
5683 ARRAY_APPEND( p_pat->programs, pmtpid );
5685 /* Now select PID at access level */
5686 if( p_sys->programs.i_size == 0 ||
5687 ProgramIsSelected( p_sys, p_program->i_number ) )
5689 if( p_sys->programs.i_size == 0 )
5691 msg_Dbg( p_demux, "temporary receiving program %d", p_program->i_number );
5692 p_sys->b_default_selection = true;
5693 ARRAY_APPEND( p_sys->programs, p_program->i_number );
5696 if( SetPIDFilter( p_sys, pmtpid, true ) )
5697 p_sys->b_access_control = false;
5698 else if ( p_sys->es_creation == DELAY_ES )
5699 p_sys->es_creation = CREATE_ES;
5702 p_pat->i_version = p_dvbpsipat->i_version;
5703 p_pat->i_ts_id = p_dvbpsipat->i_ts_id;
5705 for(int i=0; i<old_pmt_rm.i_size; i++)
5707 /* decref current or release now unreferenced */
5708 PIDRelease( p_demux, old_pmt_rm.p_elems[i] );
5710 ARRAY_RESET(old_pmt_rm);
5712 dvbpsi_pat_delete( p_dvbpsipat );
5715 static inline bool handle_Init( demux_t *p_demux, dvbpsi_t **handle )
5717 *handle = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG );
5720 (*handle)->p_sys = (void *) p_demux;
5724 static ts_pat_t *ts_pat_New( demux_t *p_demux )
5726 ts_pat_t *pat = malloc( sizeof( ts_pat_t ) );
5730 if( !handle_Init( p_demux, &pat->handle ) )
5736 pat->i_version = -1;
5738 ARRAY_INIT( pat->programs );
5743 static void ts_pat_Del( demux_t *p_demux, ts_pat_t *pat )
5745 if( dvbpsi_decoder_present( pat->handle ) )
5746 dvbpsi_pat_detach( pat->handle );
5747 dvbpsi_delete( pat->handle );
5748 for( int i=0; i<pat->programs.i_size; i++ )
5749 PIDRelease( p_demux, pat->programs.p_elems[i] );
5750 ARRAY_RESET( pat->programs );
5754 static ts_pmt_t *ts_pmt_New( demux_t *p_demux )
5756 ts_pmt_t *pmt = malloc( sizeof( ts_pmt_t ) );
5760 if( !handle_Init( p_demux, &pmt->handle ) )
5766 ARRAY_INIT( pmt->e_streams );
5768 pmt->i_version = -1;
5770 pmt->i_pid_pcr = 0x1FFF;
5773 pmt->i_last_dts = -1;
5775 pmt->pcr.i_current = -1;
5776 pmt->pcr.i_first = -1;
5777 pmt->pcr.b_disable = false;
5778 pmt->pcr.i_first_dts = VLC_TS_INVALID;
5779 pmt->pcr.i_pcroffset = -1;
5781 pmt->pcr.b_fix_done = false;
5786 static void ts_pmt_Del( demux_t *p_demux, ts_pmt_t *pmt )
5788 if( dvbpsi_decoder_present( pmt->handle ) )
5789 dvbpsi_pmt_detach( pmt->handle );
5790 dvbpsi_delete( pmt->handle );
5791 for( int i=0; i<pmt->e_streams.i_size; i++ )
5792 PIDRelease( p_demux, pmt->e_streams.p_elems[i] );
5793 ARRAY_RESET( pmt->e_streams );
5795 IODFree( pmt->iod );
5796 if( pmt->i_number > -1 )
5797 es_out_Control( p_demux->out, ES_OUT_DEL_GROUP, pmt->i_number );
5801 static ts_pes_t *ts_pes_New( demux_t *p_demux )
5803 VLC_UNUSED(p_demux);
5804 ts_pes_t *pes = malloc( sizeof( ts_pes_t ) );
5809 pes->es.p_mpeg4desc = NULL;
5810 es_format_Init( &pes->es.fmt, UNKNOWN_ES, 0 );
5811 ARRAY_INIT( pes->extra_es );
5812 pes->data_type = TS_ES_DATA_PES;
5813 pes->i_data_size = 0;
5814 pes->i_data_gathered = 0;
5816 pes->pp_last = &pes->p_data;
5817 pes->p_prepcr_outqueue = NULL;
5822 static void ts_pes_Del( demux_t *p_demux, ts_pes_t *pes )
5826 es_out_Del( p_demux->out, pes->es.id );
5827 p_demux->p_sys->i_pmt_es--;
5831 block_ChainRelease( pes->p_data );
5833 if( pes->p_prepcr_outqueue )
5834 block_ChainRelease( pes->p_prepcr_outqueue );
5836 es_format_Clean( &pes->es.fmt );
5838 for( int i = 0; i < pes->extra_es.i_size; i++ )
5840 if( pes->extra_es.p_elems[i]->id )
5842 es_out_Del( p_demux->out, pes->extra_es.p_elems[i]->id );
5843 p_demux->p_sys->i_pmt_es--;
5845 es_format_Clean( &pes->extra_es.p_elems[i]->fmt );
5846 free( pes->extra_es.p_elems[i] );
5848 ARRAY_RESET( pes->extra_es );
5853 static ts_psi_t *ts_psi_New( demux_t *p_demux )
5855 ts_psi_t *psi = malloc( sizeof( ts_psi_t ) );
5859 if( !handle_Init( p_demux, &psi->handle ) )
5865 psi->i_version = -1;
5870 static void ts_psi_Del( demux_t *p_demux, ts_psi_t *psi )
5872 VLC_UNUSED(p_demux);
5873 if( dvbpsi_decoder_present( psi->handle ) )
5874 dvbpsi_DetachDemux( psi->handle );
5875 dvbpsi_delete( psi->handle );