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 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;
321 ts_es_data_type_t data_type;
327 es_mpeg4_descriptor_t *p_mpeg4desc;
329 block_t * p_prepcr_outqueue;
351 #define SEEN(x) ((x).i_flags & FLAG_SEEN)
352 #define SCRAMBLED(x) ((x).i_flags & FLAG_SCRAMBLED)
359 uint8_t i_cc; /* countinuity counter */
362 /* PSI owner (ie PMT -> PAT, ES -> PMT */
377 vlc_fourcc_t i_fourcc;
389 #define MIN_ES_PID 4 /* Should be 32.. broken muxers */
390 #define MAX_ES_PID 8190
391 #define MIN_PAT_INTERVAL CLOCK_FREQ // DVB is 500ms
393 #define FROM_SCALE(x) (VLC_TS_0 + ((x) * 100 / 9))
394 #define TO_SCALE(x) (((x) - VLC_TS_0) * 9 / 100)
401 vlc_mutex_t csa_lock;
403 /* TS packet size (188, 192, 204) */
404 unsigned i_packet_size;
406 /* Additional TS packet header size (BluRay TS packets have 4-byte header before sync byte) */
407 unsigned i_packet_header_size;
409 /* how many TS packet we read at once */
412 bool b_force_seek_per_percent;
418 arib_instance_t *p_instance;
428 bool b_es_all; /* If we need to return all es/programs */
432 NO_ES, /* for preparse */
436 #define PREPARSING p_sys->es_creation == NO_ES
440 uint16_t i_next_extraid;
449 bool b_access_control;
456 int64_t i_dvb_length;
457 bool b_broken_charset; /* True if broken encoding is used in EPG/SDT */
459 /* Selected programs */
460 DECL_ARRAY( int ) programs; /* List of selected/access-filtered programs */
461 bool b_default_selection; /* True if set by default to first pmt seen (to get data from filtered access) */
465 mtime_t i_first_dts; /* first dts encountered for the stream */
466 int i_timesourcepid; /* which pid we saved the dts from */
467 bool b_pat_deadline; /* set if we haven't seen PAT within MIN_PAT_INTERVAL */
476 static int Demux ( demux_t *p_demux );
477 static int Control( demux_t *p_demux, int i_query, va_list args );
479 static void PIDFillFormat( es_format_t *fmt, int i_stream_type );
481 static bool PIDSetup( demux_t *p_demux, ts_pid_type_t i_type, ts_pid_t *pid, ts_pid_t *p_parent );
482 static void PIDRelease( demux_t *p_demux, ts_pid_t *pid );
484 static void PATCallBack( void*, dvbpsi_pat_t * );
485 static void PMTCallBack( void *data, dvbpsi_pmt_t *p_pmt );
486 static void PSINewTableCallBack( dvbpsi_t *handle, uint8_t i_table_id,
487 uint16_t i_extension, demux_t * );
489 static int ChangeKeyCallback( vlc_object_t *, char const *, vlc_value_t, vlc_value_t, void * );
492 static ts_pat_t *ts_pat_New( demux_t * );
493 static void ts_pat_Del( demux_t *, ts_pat_t * );
494 static ts_pmt_t *ts_pmt_New( demux_t * );
495 static void ts_pmt_Del( demux_t *, ts_pmt_t * );
496 static ts_pes_t *ts_pes_New( demux_t * );
497 static void ts_pes_Del( demux_t *, ts_pes_t * );
498 static ts_psi_t *ts_psi_New( demux_t * );
499 static void ts_psi_Del( demux_t *, ts_psi_t * );
502 static ts_pmt_t * GetProgramByID( demux_sys_t *, int i_program );
503 static bool ProgramIsSelected( demux_sys_t *, uint16_t i_pgrm );
504 static void UpdatePESFilters( demux_t *p_demux, bool b_all );
505 static inline void FlushESBuffer( ts_pes_t *p_pes );
506 static void UpdateScrambledState( demux_t *p_demux, ts_pid_t *p_pid, bool );
507 static inline int PIDGet( block_t *p )
509 return ( (p->p_buffer[1]&0x1f)<<8 )|p->p_buffer[2];
512 static bool GatherData( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk );
513 static void AddAndCreateES( demux_t *p_demux, ts_pid_t *pid, bool );
514 static void ProgramSetPCR( demux_t *p_demux, ts_pmt_t *p_prg, mtime_t i_pcr );
516 static block_t* ReadTSPacket( demux_t *p_demux );
517 static int ProbeStart( demux_t *p_demux, int i_program );
518 static int ProbeEnd( demux_t *p_demux, int i_program );
519 static int SeekToTime( demux_t *p_demux, ts_pmt_t *, int64_t time );
520 static void ReadyQueuesPostSeek( demux_t *p_demux );
521 static void PCRHandle( demux_t *p_demux, ts_pid_t *, block_t * );
522 static void PCRFixHandle( demux_t *, ts_pmt_t *, block_t * );
523 static int64_t TimeStampWrapAround( ts_pmt_t *, int64_t );
525 static void IODFree( iod_descriptor_t * );
527 #define TS_USER_PMT_NUMBER (0)
528 static int UserPmt( demux_t *p_demux, const char * );
530 static int SetPIDFilter( demux_sys_t *, ts_pid_t *, bool b_selected );
532 #define TS_PACKET_SIZE_188 188
533 #define TS_PACKET_SIZE_192 192
534 #define TS_PACKET_SIZE_204 204
535 #define TS_PACKET_SIZE_MAX 204
536 #define TS_HEADER_SIZE 4
538 static int DetectPacketSize( demux_t *p_demux, unsigned *pi_header_size, int i_offset )
540 const uint8_t *p_peek;
542 if( stream_Peek( p_demux->s,
543 &p_peek, i_offset + TS_PACKET_SIZE_MAX ) < i_offset + TS_PACKET_SIZE_MAX )
546 for( int i_sync = 0; i_sync < TS_PACKET_SIZE_MAX; i_sync++ )
548 if( p_peek[i_offset + i_sync] != 0x47 )
551 /* Check next 3 sync bytes */
552 int i_peek = i_offset + TS_PACKET_SIZE_MAX * 3 + i_sync + 1;
553 if( ( stream_Peek( p_demux->s, &p_peek, i_peek ) ) < i_peek )
555 msg_Err( p_demux, "cannot peek" );
558 if( p_peek[i_offset + i_sync + 1 * TS_PACKET_SIZE_188] == 0x47 &&
559 p_peek[i_offset + i_sync + 2 * TS_PACKET_SIZE_188] == 0x47 &&
560 p_peek[i_offset + i_sync + 3 * TS_PACKET_SIZE_188] == 0x47 )
562 return TS_PACKET_SIZE_188;
564 else if( p_peek[i_offset + i_sync + 1 * TS_PACKET_SIZE_192] == 0x47 &&
565 p_peek[i_offset + i_sync + 2 * TS_PACKET_SIZE_192] == 0x47 &&
566 p_peek[i_offset + i_sync + 3 * TS_PACKET_SIZE_192] == 0x47 )
570 *pi_header_size = 4; /* BluRay TS packets have 4-byte header */
572 return TS_PACKET_SIZE_192;
574 else if( p_peek[i_offset + i_sync + 1 * TS_PACKET_SIZE_204] == 0x47 &&
575 p_peek[i_offset + i_sync + 2 * TS_PACKET_SIZE_204] == 0x47 &&
576 p_peek[i_offset + i_sync + 3 * TS_PACKET_SIZE_204] == 0x47 )
578 return TS_PACKET_SIZE_204;
582 if( p_demux->b_force )
584 msg_Warn( p_demux, "this does not look like a TS stream, continuing" );
585 return TS_PACKET_SIZE_188;
587 msg_Dbg( p_demux, "TS module discarded (lost sync)" );
591 #define TOPFIELD_HEADER_SIZE 3712
593 static int DetectPVRHeadersAndHeaderSize( demux_t *p_demux, unsigned *pi_header_size, vdr_info_t *p_vdr )
595 const uint8_t *p_peek;
597 int i_packet_size = -1;
599 if( stream_Peek( p_demux->s,
600 &p_peek, TS_PACKET_SIZE_MAX ) < TS_PACKET_SIZE_MAX )
603 if( memcmp( p_peek, "TFrc", 4 ) == 0 &&
604 p_peek[6] == 0 && memcmp( &p_peek[53], "\x80\x00\x00", 4 ) == 0 &&
605 stream_Peek( p_demux->s, &p_peek, TOPFIELD_HEADER_SIZE + TS_PACKET_SIZE_MAX )
606 == TOPFIELD_HEADER_SIZE + TS_PACKET_SIZE_MAX )
608 i_packet_size = DetectPacketSize( p_demux, pi_header_size, TOPFIELD_HEADER_SIZE );
609 if( i_packet_size != -1 )
611 msg_Dbg( p_demux, "this is a topfield file" );
613 /* I used the TF5000PVR 2004 Firmware .doc header documentation,
614 * http://www.i-topfield.com/data/product/firmware/Structure%20of%20Recorded%20File%20in%20TF5000PVR%20(Feb%2021%202004).doc
615 * but after the filename the offsets seem to be incorrect. - DJ */
616 int i_duration, i_name;
617 char *psz_name = xmalloc(25);
618 char *psz_event_name;
619 char *psz_event_text = xmalloc(130);
620 char *psz_ext_text = xmalloc(1025);
622 // 2 bytes version Uimsbf (4,5)
623 // 2 bytes reserved (6,7)
624 // 2 bytes duration in minutes Uimsbf (8,9(
625 i_duration = (int) (p_peek[8] << 8) | p_peek[9];
626 msg_Dbg( p_demux, "Topfield recording length: +/- %d minutes", i_duration);
627 // 2 bytes service number in channel list (10, 11)
628 // 2 bytes service type Bslbf 0=TV 1=Radio Bslb (12, 13)
629 // 4 bytes of reserved + tuner info (14,15,16,17)
630 // 2 bytes of Service ID Bslbf (18,19)
631 // 2 bytes of PMT PID Uimsbf (20,21)
632 // 2 bytes of PCR PID Uimsbf (22,23)
633 // 2 bytes of Video PID Uimsbf (24,25)
634 // 2 bytes of Audio PID Uimsbf (26,27)
635 // 24 bytes filename Bslbf
636 memcpy( psz_name, &p_peek[28], 24 );
638 msg_Dbg( p_demux, "recordingname=%s", psz_name );
639 // 1 byte of sat index Uimsbf (52)
640 // 3 bytes (1 bit of polarity Bslbf +23 bits reserved)
641 // 4 bytes of freq. Uimsbf (56,57,58,59)
642 // 2 bytes of symbol rate Uimsbf (60,61)
643 // 2 bytes of TS stream ID Uimsbf (62,63)
646 // 2 bytes duration Uimsbf (70,71)
647 //i_duration = (int) (p_peek[70] << 8) | p_peek[71];
648 //msg_Dbg( p_demux, "Topfield 2nd duration field: +/- %d minutes", i_duration);
649 // 4 bytes EventID Uimsbf (72-75)
650 // 8 bytes of Start and End time info (76-83)
651 // 1 byte reserved (84)
652 // 1 byte event name length Uimsbf (89)
653 i_name = (int)(p_peek[89]&~0x81);
654 msg_Dbg( p_demux, "event name length = %d", i_name);
655 psz_event_name = xmalloc( i_name+1 );
656 // 1 byte parental rating (90)
657 // 129 bytes of event text
658 memcpy( psz_event_name, &p_peek[91], i_name );
659 psz_event_name[i_name] = '\0';
660 memcpy( psz_event_text, &p_peek[91+i_name], 129-i_name );
661 psz_event_text[129-i_name] = '\0';
662 msg_Dbg( p_demux, "event name=%s", psz_event_name );
663 msg_Dbg( p_demux, "event text=%s", psz_event_text );
664 // 12 bytes reserved (220)
666 // 2 bytes Event Text Length Uimsbf
667 // 4 bytes EventID Uimsbf
668 // FIXME We just have 613 bytes. not enough for this entire text
669 // 1024 bytes Extended Event Text Bslbf
670 memcpy( psz_ext_text, p_peek+372, 1024 );
671 psz_ext_text[1024] = '\0';
672 msg_Dbg( p_demux, "extended event text=%s", psz_ext_text );
673 // 52 bytes reserved Bslbf
675 p_vdr->i_service = GetWBE(&p_peek[18]);
677 return i_packet_size;
678 //return TS_PACKET_SIZE_188;
682 return DetectPacketSize( p_demux, pi_header_size, 0 );
685 static inline mtime_t ExtractPESTimestamp( const uint8_t *p_data )
687 return ((mtime_t)(p_data[ 0]&0x0e ) << 29)|
688 (mtime_t)(p_data[1] << 22)|
689 ((mtime_t)(p_data[2]&0xfe) << 14)|
690 (mtime_t)(p_data[3] << 7)|
691 (mtime_t)(p_data[4] >> 1);
694 static void ProbePES( demux_t *p_demux, ts_pid_t *pid, const uint8_t *p_pesstart, size_t i_data, bool b_adaptfield )
696 demux_sys_t *p_sys = p_demux->p_sys;
697 const uint8_t *p_pes = p_pesstart;
698 pid->probed.i_type = -1;
705 uint8_t len = *p_pes;
710 p_pes++; i_data--;/* stuffing */
716 if( len >= 7 && (p_pes[1] & 0x10) )
717 pid->probed.i_pcr_count++;
726 if( p_pes[0] != 0 || p_pes[1] != 0 || p_pes[2] != 1 )
729 size_t i_pesextoffset = 8;
731 if( p_pes[7] & 0x80 ) // PTS
734 if ( i_data < i_pesextoffset )
736 i_dts = ExtractPESTimestamp( &p_pes[9] );
738 if( p_pes[7] & 0x40 ) // DTS
741 if ( i_data < i_pesextoffset )
743 i_dts = ExtractPESTimestamp( &p_pes[14] );
745 if( p_pes[7] & 0x20 ) // ESCR
747 if( p_pes[7] & 0x10 ) // ESrate
749 if( p_pes[7] & 0x08 ) // DSM
751 if( p_pes[7] & 0x04 ) // CopyInfo
753 if( p_pes[7] & 0x02 ) // PESCRC
756 if ( i_data < i_pesextoffset )
759 /* HeaderdataLength */
760 const size_t i_payloadoffset = 8 + 1 + p_pes[8];
763 if ( i_data < i_pesextoffset || i_data < i_payloadoffset )
766 i_data -= 8 + 1 + p_pes[8];
768 if( p_pes[7] & 0x01 ) // PESExt
770 size_t i_extension2_offset = 1;
771 if ( p_pes[i_pesextoffset] & 0x80 ) // private data
772 i_extension2_offset += 16;
773 if ( p_pes[i_pesextoffset] & 0x40 ) // pack
774 i_extension2_offset += 1;
775 if ( p_pes[i_pesextoffset] & 0x20 ) // seq
776 i_extension2_offset += 2;
777 if ( p_pes[i_pesextoffset] & 0x10 ) // P-STD
778 i_extension2_offset += 2;
779 if ( p_pes[i_pesextoffset] & 0x01 ) // Extension 2
781 uint8_t i_len = p_pes[i_pesextoffset + i_extension2_offset] & 0x7F;
782 i_extension2_offset += i_len;
784 if( i_data < i_extension2_offset )
787 i_data -= i_extension2_offset;
789 /* (i_payloadoffset - i_pesextoffset) 0xFF stuffing */
794 const uint8_t *p_data = &p_pes[i_payloadoffset];
796 if(p_pes[3] >= 0xC0 && p_pes[3] <= 0xDF)
798 if( !memcmp( p_data, "\x7F\xFE\x80\x01", 4 ) )
800 pid->probed.i_type = 0x06;
801 pid->probed.i_fourcc = VLC_CODEC_DTS;
803 else if( !memcmp( p_data, "\x0B\x77", 2 ) )
805 pid->probed.i_type = 0x06;
806 pid->probed.i_fourcc = VLC_CODEC_EAC3;
808 else if( p_data[0] == 0xFF && (p_data[1] & 0xE0) == 0xE0 )
810 switch(p_data[1] & 18)
812 /* 10 - MPEG Version 2 (ISO/IEC 13818-3)
813 11 - MPEG Version 1 (ISO/IEC 11172-3) */
815 pid->probed.i_type = 0x04;
818 pid->probed.i_type = 0x03;
823 switch(p_data[1] & 6)
829 pid->probed.i_type = 0x04;
830 pid->probed.i_fourcc = VLC_CODEC_MPGA;
833 pid->probed.i_type = 0x04;
834 pid->probed.i_fourcc = VLC_CODEC_MP2;
837 pid->probed.i_type = 0x04;
838 pid->probed.i_fourcc = VLC_CODEC_MP3;
845 else if( p_pes[3] >= 0xE0 && p_pes[3] <= 0xEF )
847 if( !memcmp( p_data, "\x00\x00\x00", 4 ) )
849 pid->probed.i_type = 0x1b;
850 pid->probed.i_fourcc = VLC_CODEC_H264;
852 else if( !memcmp( p_data, "\x00\x00\x01", 4 ) )
854 pid->probed.i_type = 0x02;
855 pid->probed.i_fourcc = VLC_CODEC_MPGV;
859 /* Track timestamps and flag missing PAT */
860 if( !p_sys->patfix.i_timesourcepid && i_dts > -1 )
862 p_sys->patfix.i_first_dts = i_dts;
863 p_sys->patfix.i_timesourcepid = pid->i_pid;
865 else if( p_sys->patfix.i_timesourcepid == pid->i_pid && i_dts > -1 &&
866 !p_sys->patfix.b_pat_deadline )
868 if( i_dts - p_sys->patfix.i_first_dts > TO_SCALE(MIN_PAT_INTERVAL) )
869 p_sys->patfix.b_pat_deadline = true;
874 static void BuildPATCallback( void *p_opaque, block_t *p_block )
876 ts_pid_t *pat_pid = (ts_pid_t *) p_opaque;
877 dvbpsi_packet_push( pat_pid->u.p_pat->handle, p_block->p_buffer );
880 static void BuildPMTCallback( void *p_opaque, block_t *p_block )
882 ts_pid_t *program_pid = (ts_pid_t *) p_opaque;
883 assert(program_pid->type == TYPE_PMT);
886 dvbpsi_packet_push( program_pid->u.p_pmt->handle,
888 p_block = p_block->p_next;
892 static void MissingPATPMTFixup( demux_t *p_demux )
894 demux_sys_t *p_sys = p_demux->p_sys;
895 int i_program_number = 1234;
896 int i_program_pid = 1337;
897 int i_pcr_pid = 0x1FFF;
900 if( SEEN(p_sys->pid[i_program_pid]) )
902 /* Find a free one */
903 for( i_program_pid = MIN_ES_PID;
904 i_program_pid <= MAX_ES_PID && SEEN(p_sys->pid[i_program_pid]);
908 for( int i = MIN_ES_PID; i <= MAX_ES_PID; i++ )
910 if( !SEEN(p_sys->pid[i]) ||
911 p_sys->pid[i].probed.i_type == -1 )
914 if( i_pcr_pid == 0x1FFF && ( p_sys->pid[i].probed.i_type == 0x03 ||
915 p_sys->pid[i].probed.i_pcr_count ) )
916 i_pcr_pid = p_sys->pid[i].i_pid;
924 ts_stream_t patstream =
927 .i_continuity_counter = 0x10,
928 .b_discontinuity = false
931 ts_stream_t pmtprogramstream =
933 .i_pid = i_program_pid,
934 .i_continuity_counter = 0x0,
935 .b_discontinuity = false
938 BuildPAT( p_sys->pid[0].u.p_pat->handle,
939 &p_sys->pid[0], BuildPATCallback,
942 1, &pmtprogramstream, &i_program_number );
944 if( p_sys->pid[i_program_pid].type != TYPE_PMT )
946 msg_Err( p_demux, "PAT creation failed" );
955 es_format_t esfmt = {0};
956 struct esstreams_t *esstreams = calloc( i_num_pes, sizeof(struct esstreams_t) );
957 pes_mapped_stream_t *mapped = calloc( i_num_pes, sizeof(pes_mapped_stream_t) );
958 if( esstreams && mapped )
961 for( int i = MIN_ES_PID; i <= MAX_ES_PID; i++ )
963 if( !SEEN(p_sys->pid[i]) ||
964 p_sys->pid[i].probed.i_type == -1 )
967 esstreams[j].pes.i_stream_type = p_sys->pid[i].probed.i_type;
968 esstreams[j].pes.i_stream_type = p_sys->pid[i].probed.i_type;
969 esstreams[j].ts.i_pid = p_sys->pid[i].i_pid;
970 mapped[j].pes = &esstreams[j].pes;
971 mapped[j].ts = &esstreams[j].ts;
972 mapped[j].fmt = &esfmt;
976 BuildPMT( p_sys->pid[0].u.p_pat->handle, VLC_OBJECT(p_demux),
977 &p_sys->pid[i_program_pid], BuildPMTCallback,
981 1, &pmtprogramstream, &i_program_number,
988 /*****************************************************************************
990 *****************************************************************************/
991 static int Open( vlc_object_t *p_this )
993 demux_t *p_demux = (demux_t*)p_this;
997 unsigned i_packet_header_size = 0;
1000 vdr_info_t vdr = {0};
1002 /* Search first sync byte */
1003 i_packet_size = DetectPVRHeadersAndHeaderSize( p_demux, &i_packet_header_size, &vdr );
1004 if( i_packet_size < 0 )
1005 return VLC_EGENERIC;
1007 p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
1010 memset( p_sys, 0, sizeof( demux_sys_t ) );
1011 vlc_mutex_init( &p_sys->csa_lock );
1013 p_demux->pf_demux = Demux;
1014 p_demux->pf_control = Control;
1016 /* Init p_sys field */
1017 p_sys->b_dvb_meta = true;
1018 p_sys->b_access_control = true;
1019 p_sys->b_end_preparse = false;
1020 ARRAY_INIT( p_sys->programs );
1021 p_sys->b_default_selection = false;
1022 p_sys->i_tdt_delta = 0;
1023 p_sys->i_dvb_start = 0;
1024 p_sys->i_dvb_length = 0;
1028 p_sys->arib.b25stream = NULL;
1029 p_sys->stream = p_demux->s;
1031 p_sys->b_broken_charset = false;
1033 for( int i = 0; i < 8192; i++ )
1035 ts_pid_t *pid = &p_sys->pid[i];
1037 pid->i_flags = FLAGS_NONE;
1038 pid->probed.i_fourcc = 0;
1039 pid->probed.i_type = 0;
1041 /* PID 8191 is padding */
1042 p_sys->pid[8191].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 = &p_sys->pid[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, &p_sys->pid[0x11], NULL ) ||
1076 !PIDSetup( p_demux, TYPE_EIT, &p_sys->pid[0x12], NULL ) ||
1077 !PIDSetup( p_demux, TYPE_TDT, &p_sys->pid[0x14], NULL ) )
1079 PIDRelease( p_demux, &p_sys->pid[0x11] );
1080 PIDRelease( p_demux, &p_sys->pid[0x12] );
1081 PIDRelease( p_demux, &p_sys->pid[0x14] );
1082 p_sys->b_dvb_meta = false;
1086 VLC_DVBPSI_DEMUX_TABLE_INIT(&p_sys->pid[0x11], p_demux);
1087 VLC_DVBPSI_DEMUX_TABLE_INIT(&p_sys->pid[0x12], p_demux);
1088 VLC_DVBPSI_DEMUX_TABLE_INIT(&p_sys->pid[0x14], p_demux);
1089 if( p_sys->b_access_control &&
1090 ( SetPIDFilter( p_sys, &p_sys->pid[0x11], true ) ||
1091 SetPIDFilter( p_sys, &p_sys->pid[0x14], true ) ||
1092 SetPIDFilter( p_sys, &p_sys->pid[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, &p_sys->pid[0] );
1199 if( p_sys->b_dvb_meta )
1201 PIDRelease( p_demux, &p_sys->pid[0x11] );
1202 PIDRelease( p_demux, &p_sys->pid[0x12] );
1203 PIDRelease( p_demux, &p_sys->pid[0x14] );
1207 for( int i = 0; i < 8192; i++ )
1209 ts_pid_t *pid = &p_sys->pid[i];
1210 if( pid->type != TYPE_FREE )
1211 msg_Err( p_demux, "PID %d type %d not freed", pid->i_pid, pid->type );
1215 vlc_mutex_lock( &p_sys->csa_lock );
1218 var_DelCallback( p_demux, "ts-csa-ck", ChangeKeyCallback, NULL );
1219 var_DelCallback( p_demux, "ts-csa2-ck", ChangeKeyCallback, NULL );
1220 csa_Delete( p_sys->csa );
1222 vlc_mutex_unlock( &p_sys->csa_lock );
1224 ARRAY_RESET( p_sys->programs );
1227 if ( p_sys->arib.p_instance )
1228 arib_instance_destroy( p_sys->arib.p_instance );
1231 if ( p_sys->arib.b25stream )
1233 p_sys->arib.b25stream->p_source = NULL; /* don't chain kill demuxer's source */
1234 stream_Delete( p_sys->arib.b25stream );
1237 vlc_mutex_destroy( &p_sys->csa_lock );
1241 /*****************************************************************************
1242 * ChangeKeyCallback: called when changing the odd encryption key on the fly.
1243 *****************************************************************************/
1244 static int ChangeKeyCallback( vlc_object_t *p_this, char const *psz_cmd,
1245 vlc_value_t oldval, vlc_value_t newval,
1248 VLC_UNUSED(psz_cmd); VLC_UNUSED(oldval);
1249 demux_t *p_demux = (demux_t*)p_this;
1250 demux_sys_t *p_sys = p_demux->p_sys;
1251 int i_tmp = (intptr_t)p_data;
1253 vlc_mutex_lock( &p_sys->csa_lock );
1255 i_tmp = csa_SetCW( p_this, p_sys->csa, newval.psz_string, true );
1257 i_tmp = csa_SetCW( p_this, p_sys->csa, newval.psz_string, false );
1259 vlc_mutex_unlock( &p_sys->csa_lock );
1263 /*****************************************************************************
1265 *****************************************************************************/
1266 static int Demux( demux_t *p_demux )
1268 demux_sys_t *p_sys = p_demux->p_sys;
1269 bool b_wait_es = p_sys->i_pmt_es <= 0;
1271 /* If we had no PAT within MIN_PAT_INTERVAL, create PAT/PMT from probed streams */
1272 if( p_sys->i_pmt_es == 0 && !SEEN(p_sys->pid[0]) && p_sys->patfix.b_pat_deadline )
1273 MissingPATPMTFixup( p_demux );
1275 /* We read at most 100 TS packet or until a frame is completed */
1276 for( unsigned i_pkt = 0; i_pkt < p_sys->i_ts_read; i_pkt++ )
1278 bool b_frame = false;
1280 if( !(p_pkt = ReadTSPacket( p_demux )) )
1282 return VLC_DEMUXER_EOF;
1285 if( p_sys->b_start_record )
1287 /* Enable recording once synchronized */
1288 stream_Control( p_sys->stream, STREAM_SET_RECORD_STATE, true, "ts" );
1289 p_sys->b_start_record = false;
1292 /* Parse the TS packet */
1293 ts_pid_t *p_pid = &p_sys->pid[PIDGet( p_pkt )];
1295 if( SCRAMBLED(*p_pid) != !!(p_pkt->p_buffer[3] & 0x80) )
1296 UpdateScrambledState( p_demux, p_pid, p_pkt->p_buffer[3] & 0x80 );
1300 if( p_pid->type == TYPE_FREE )
1301 msg_Dbg( p_demux, "pid[%d] unknown", p_pid->i_pid );
1302 p_pid->i_flags |= FLAG_SEEN;
1305 if ( SCRAMBLED(*p_pid) && !p_demux->p_sys->csa )
1307 block_Release( p_pkt );
1311 /* Probe streams to build PAT/PMT after MIN_PAT_INTERVAL in case we don't see any PAT */
1312 if( !SEEN(p_sys->pid[0]) &&
1313 (p_pid->probed.i_type == 0 || p_pid->i_pid == p_sys->patfix.i_timesourcepid) &&
1314 (p_pkt->p_buffer[1] & 0xC0) == 0x40 && /* Payload start but not corrupt */
1315 (p_pkt->p_buffer[3] & 0xD0) == 0x10 ) /* Has payload but is not encrypted */
1317 ProbePES( p_demux, p_pid, p_pkt->p_buffer + TS_HEADER_SIZE,
1318 p_pkt->i_buffer - TS_HEADER_SIZE, p_pkt->p_buffer[3] & 0x20 /* Adaptation field */);
1321 switch( p_pid->type )
1324 dvbpsi_packet_push( p_pid->u.p_pat->handle, p_pkt->p_buffer );
1325 block_Release( p_pkt );
1329 dvbpsi_packet_push( p_pid->u.p_pmt->handle, p_pkt->p_buffer );
1330 block_Release( p_pkt );
1334 p_sys->b_end_preparse = true;
1336 if( p_sys->es_creation == DELAY_ES ) /* No longer delay ES since that pid's program sends data */
1338 msg_Dbg( p_demux, "Creating delayed ES" );
1339 AddAndCreateES( p_demux, p_pid, true );
1342 if( !p_sys->b_access_control && !(p_pid->i_flags & FLAG_FILTERED) )
1344 /* That packet is for an unselected ES, don't waste time/memory gathering its data */
1345 block_Release( p_pkt );
1349 b_frame = GatherData( p_demux, p_pid, p_pkt );
1355 if( p_sys->b_dvb_meta )
1356 dvbpsi_packet_push( p_pid->u.p_psi->handle, p_pkt->p_buffer );
1357 block_Release( p_pkt );
1361 /* We have to handle PCR if present */
1362 PCRHandle( p_demux, p_pid, p_pkt );
1363 block_Release( p_pkt );
1367 if( b_frame || ( b_wait_es && p_sys->i_pmt_es > 0 ) )
1371 demux_UpdateTitleFromStream( p_demux );
1372 return VLC_DEMUXER_SUCCESS;
1375 /*****************************************************************************
1377 *****************************************************************************/
1378 static int DVBEventInformation( demux_t *p_demux, int64_t *pi_time, int64_t *pi_length )
1380 demux_sys_t *p_sys = p_demux->p_sys;
1386 if( p_sys->i_dvb_length > 0 )
1388 const int64_t t = mdate() + p_sys->i_tdt_delta;
1390 if( p_sys->i_dvb_start <= t && t < p_sys->i_dvb_start + p_sys->i_dvb_length )
1393 *pi_length = p_sys->i_dvb_length;
1395 *pi_time = t - p_sys->i_dvb_start;
1399 return VLC_EGENERIC;
1402 static void UpdatePESFilters( demux_t *p_demux, bool b_all )
1404 demux_sys_t *p_sys = p_demux->p_sys;
1405 ts_pat_t *p_pat = p_sys->pid[0].u.p_pat;
1406 for( int i=0; i< p_pat->programs.i_size; i++ )
1408 ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
1409 bool b_program_selected;
1410 if( (p_sys->b_default_selection && !p_sys->b_access_control) || b_all )
1411 b_program_selected = true;
1413 b_program_selected = ProgramIsSelected( p_sys, p_pmt->i_number );
1415 SetPIDFilter( p_sys, p_pat->programs.p_elems[i], b_program_selected );
1417 for( int j=0; j<p_pmt->e_streams.i_size; j++ )
1419 ts_pid_t *espid = p_pmt->e_streams.p_elems[j];
1420 bool b_stream_selected = b_program_selected;
1421 if( b_program_selected && !b_all && espid->u.p_pes->es.id )
1422 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
1423 espid->u.p_pes->es.id, &b_stream_selected );
1425 if( !p_sys->b_es_all && espid->u.p_pes->es.fmt.i_cat == UNKNOWN_ES )
1426 b_stream_selected = false;
1428 if( b_stream_selected )
1429 msg_Dbg( p_demux, "enabling pid %d from program %d", espid->i_pid, p_pmt->i_number );
1431 SetPIDFilter( p_sys, espid, b_stream_selected );
1432 if( !b_stream_selected )
1433 FlushESBuffer( espid->u.p_pes );
1436 /* Select pcr last in case it is handled by unselected ES */
1437 if( p_pmt->i_pid_pcr > 0 )
1439 SetPIDFilter( p_sys, &p_sys->pid[p_pmt->i_pid_pcr], b_program_selected );
1440 if( b_program_selected )
1441 msg_Dbg( p_demux, "enabling pcr pid %d from program %d", p_pmt->i_pid_pcr, p_pmt->i_number );
1446 static int Control( demux_t *p_demux, int i_query, va_list args )
1448 demux_sys_t *p_sys = p_demux->p_sys;
1450 bool b_bool, *pb_bool;
1455 int i_first_program = ( p_sys->programs.i_size ) ? p_sys->programs.p_elems[0] : 0;
1457 if( PREPARSING || !i_first_program || p_sys->b_default_selection )
1459 if( likely(p_sys->pid[0].type == TYPE_PAT) )
1461 ts_pat_t *p_pat = p_sys->pid[0].u.p_pat;
1462 /* Set default program for preparse time (no program has been selected) */
1463 for( int i = 0; i < p_pat->programs.i_size; i++ )
1465 assert(p_pat->programs.p_elems[i]->type == TYPE_PMT);
1466 p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
1467 if( ( p_pmt->pcr.i_first > -1 || p_pmt->pcr.i_first_dts > VLC_TS_INVALID ) && p_pmt->i_last_dts > 0 )
1469 i_first_program = p_pmt->i_number;
1478 case DEMUX_GET_POSITION:
1479 pf = (double*) va_arg( args, double* );
1481 /* Access control test is because EPG for recordings is not relevant */
1482 if( p_sys->b_dvb_meta && p_sys->b_access_control )
1484 int64_t i_time, i_length;
1485 if( !DVBEventInformation( p_demux, &i_time, &i_length ) && i_length > 0 )
1487 *pf = (double)i_time/(double)i_length;
1492 if( (p_pmt = GetProgramByID( p_sys, i_first_program )) &&
1493 p_pmt->pcr.i_first > -1 && p_pmt->i_last_dts > VLC_TS_INVALID &&
1494 p_pmt->pcr.i_current > -1 )
1496 double i_length = TimeStampWrapAround( p_pmt,
1497 p_pmt->i_last_dts ) - p_pmt->pcr.i_first;
1498 i_length += p_pmt->pcr.i_pcroffset;
1499 double i_pos = TimeStampWrapAround( p_pmt,
1500 p_pmt->pcr.i_current ) - p_pmt->pcr.i_first;
1501 *pf = i_pos / i_length;
1505 if( (i64 = stream_Size( p_sys->stream) ) > 0 )
1507 int64_t offset = stream_Tell( p_sys->stream );
1508 *pf = (double)offset / (double)i64;
1513 case DEMUX_SET_POSITION:
1514 f = (double) va_arg( args, double );
1516 if(!p_sys->b_canseek)
1519 if( p_sys->b_dvb_meta && p_sys->b_access_control &&
1520 !p_sys->b_force_seek_per_percent &&
1521 (p_pmt = GetProgramByID( p_sys, i_first_program )) )
1523 int64_t i_time, i_length;
1524 if( !DVBEventInformation( p_demux, &i_time, &i_length ) &&
1525 i_length > 0 && !SeekToTime( p_demux, p_pmt, TO_SCALE(i_length) * f ) )
1527 ReadyQueuesPostSeek( p_demux );
1528 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME,
1529 TO_SCALE(i_length) * f );
1534 if( !p_sys->b_force_seek_per_percent &&
1535 (p_pmt = GetProgramByID( p_sys, i_first_program )) &&
1536 p_pmt->pcr.i_first > -1 && p_pmt->i_last_dts > VLC_TS_INVALID &&
1537 p_pmt->pcr.i_current > -1 )
1539 double i_length = TimeStampWrapAround( p_pmt,
1540 p_pmt->i_last_dts ) - p_pmt->pcr.i_first;
1541 if( !SeekToTime( p_demux, p_pmt, p_pmt->pcr.i_first + i_length * f ) )
1543 ReadyQueuesPostSeek( p_demux );
1544 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME,
1545 FROM_SCALE(p_pmt->pcr.i_first + i_length * f) );
1550 i64 = stream_Size( p_sys->stream );
1552 stream_Seek( p_sys->stream, (int64_t)(i64 * f) ) == VLC_SUCCESS )
1554 ReadyQueuesPostSeek( p_demux );
1559 case DEMUX_SET_TIME:
1560 i64 = (int64_t)va_arg( args, int64_t );
1562 if( p_sys->b_canseek &&
1563 (p_pmt = GetProgramByID( p_sys, i_first_program )) &&
1564 p_pmt->pcr.i_first > -1 &&
1565 !SeekToTime( p_demux, p_pmt, p_pmt->pcr.i_first + TO_SCALE(i64) ) )
1567 ReadyQueuesPostSeek( p_demux );
1568 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME,
1569 FROM_SCALE(p_pmt->pcr.i_first) + i64 - VLC_TS_0 );
1574 case DEMUX_GET_TIME:
1575 pi64 = (int64_t*)va_arg( args, int64_t * );
1577 if( p_sys->b_dvb_meta && p_sys->b_access_control )
1579 if( !DVBEventInformation( p_demux, pi64, NULL ) )
1583 if( (p_pmt = GetProgramByID( p_sys, i_first_program )) &&
1584 p_pmt->pcr.i_current > -1 && p_pmt->pcr.i_first > -1 )
1586 int64_t i_pcr = TimeStampWrapAround( p_pmt, p_pmt->pcr.i_current );
1587 *pi64 = FROM_SCALE(i_pcr - p_pmt->pcr.i_first);
1592 case DEMUX_GET_LENGTH:
1593 pi64 = (int64_t*)va_arg( args, int64_t * );
1595 if( p_sys->b_dvb_meta && p_sys->b_access_control )
1597 if( !DVBEventInformation( p_demux, NULL, pi64 ) )
1601 if( (p_pmt = GetProgramByID( p_sys, i_first_program )) &&
1602 ( p_pmt->pcr.i_first > -1 || p_pmt->pcr.i_first_dts > VLC_TS_INVALID ) &&
1603 p_pmt->i_last_dts > 0 )
1605 int64_t i_start = (p_pmt->pcr.i_first > -1) ? p_pmt->pcr.i_first :
1606 TO_SCALE(p_pmt->pcr.i_first_dts);
1607 int64_t i_last = TimeStampWrapAround( p_pmt, p_pmt->i_last_dts );
1608 i_last += p_pmt->pcr.i_pcroffset;
1609 *pi64 = FROM_SCALE(i_last - i_start);
1614 case DEMUX_SET_GROUP:
1618 i_int = (int)va_arg( args, int );
1619 p_list = (vlc_list_t *)va_arg( args, vlc_list_t * );
1620 msg_Dbg( p_demux, "DEMUX_SET_GROUP %d %p", i_int, p_list );
1622 if( i_int != 0 ) /* If not default program */
1624 /* Deselect/filter current ones */
1628 p_sys->b_es_all = false;
1629 ARRAY_APPEND( p_sys->programs, i_int );
1630 UpdatePESFilters( p_demux, false );
1632 else if( likely( p_list != NULL ) )
1634 p_sys->b_es_all = false;
1635 for( int i = 0; i < p_list->i_count; i++ )
1636 ARRAY_APPEND( p_sys->programs, p_list->p_values[i].i_int );
1637 UpdatePESFilters( p_demux, false );
1641 p_sys->b_es_all = true;
1642 ts_pat_t *p_pat = p_sys->pid[0].u.p_pat;
1643 for( int i = 0; i < p_pat->programs.i_size; i++ )
1644 ARRAY_APPEND( p_sys->programs, p_pat->programs.p_elems[i]->i_pid );
1645 UpdatePESFilters( p_demux, true );
1648 p_sys->b_default_selection = false;
1656 i_int = (int)va_arg( args, int );
1657 msg_Dbg( p_demux, "DEMUX_SET_ES %d", i_int );
1659 if( !p_sys->b_es_all ) /* Won't change anything */
1660 UpdatePESFilters( p_demux, false );
1665 case DEMUX_GET_TITLE_INFO:
1667 struct input_title_t ***v = va_arg( args, struct input_title_t*** );
1668 int *c = va_arg( args, int * );
1670 *va_arg( args, int* ) = 0; /* Title offset */
1671 *va_arg( args, int* ) = 0; /* Chapter offset */
1672 return stream_Control( p_sys->stream, STREAM_GET_TITLE_INFO, v, c );
1675 case DEMUX_SET_TITLE:
1676 return stream_vaControl( p_sys->stream, STREAM_SET_TITLE, args );
1678 case DEMUX_SET_SEEKPOINT:
1679 return stream_vaControl( p_sys->stream, STREAM_SET_SEEKPOINT, args );
1681 case DEMUX_GET_META:
1682 return stream_vaControl( p_sys->stream, STREAM_GET_META, args );
1684 case DEMUX_CAN_RECORD:
1685 pb_bool = (bool*)va_arg( args, bool * );
1689 case DEMUX_SET_RECORD_STATE:
1690 b_bool = (bool)va_arg( args, int );
1693 stream_Control( p_sys->stream, STREAM_SET_RECORD_STATE, false );
1694 p_sys->b_start_record = b_bool;
1697 case DEMUX_GET_SIGNAL:
1698 return stream_vaControl( p_sys->stream, STREAM_GET_SIGNAL, args );
1704 return VLC_EGENERIC;
1707 /*****************************************************************************
1709 *****************************************************************************/
1710 static int UserPmt( demux_t *p_demux, const char *psz_fmt )
1712 demux_sys_t *p_sys = p_demux->p_sys;
1713 char *psz_dup = strdup( psz_fmt );
1714 char *psz = psz_dup;
1722 i_pid = strtol( psz, &psz, 0 );
1723 if( i_pid < 2 || i_pid >= 8192 )
1726 /* Parse optional program number */
1729 i_number = strtol( &psz[1], &psz, 0 );
1732 ts_pid_t *pmtpid = &p_sys->pid[i_pid];
1734 msg_Dbg( p_demux, "user pmt specified (pid=%d,number=%d)", i_pid, i_number );
1735 if ( !PIDSetup( p_demux, TYPE_PMT, pmtpid, &p_sys->pid[0] ) )
1739 ts_pmt_t *p_pmt = pmtpid->u.p_pmt;
1740 p_pmt->i_number = i_number != 0 ? i_number : TS_USER_PMT_NUMBER;
1741 if( !dvbpsi_pmt_attach( p_pmt->handle,
1742 ((i_number != TS_USER_PMT_NUMBER ? i_number : 1)),
1743 PMTCallBack, p_demux ) )
1745 PIDRelease( p_demux, pmtpid );
1749 ARRAY_APPEND( p_sys->pid[0].u.p_pat->programs, pmtpid );
1751 psz = strchr( psz, '=' );
1754 while( psz && *psz )
1756 char *psz_next = strchr( psz, ',' );
1762 i_pid = strtol( psz, &psz, 0 );
1763 if( *psz != ':' || i_pid < 2 || i_pid >= 8192 )
1766 char *psz_opt = &psz[1];
1767 if( !strcmp( psz_opt, "pcr" ) )
1769 p_pmt->i_pid_pcr = i_pid;
1771 else if( p_sys->pid[i_pid].type == TYPE_FREE )
1773 ts_pid_t *pid = &p_sys->pid[i_pid];
1775 char *psz_arg = strchr( psz_opt, '=' );
1779 if ( !PIDSetup( p_demux, TYPE_PES, pid, pmtpid ) )
1782 ARRAY_APPEND( p_pmt->e_streams, pid );
1784 if( p_pmt->i_pid_pcr <= 0 )
1785 p_pmt->i_pid_pcr = i_pid;
1787 es_format_t *fmt = &pid->u.p_pes->es.fmt;
1789 if( psz_arg && strlen( psz_arg ) == 4 )
1791 const vlc_fourcc_t i_codec = VLC_FOURCC( psz_arg[0], psz_arg[1],
1792 psz_arg[2], psz_arg[3] );
1793 int i_cat = UNKNOWN_ES;
1795 if( !strcmp( psz_opt, "video" ) )
1797 else if( !strcmp( psz_opt, "audio" ) )
1799 else if( !strcmp( psz_opt, "spu" ) )
1802 es_format_Init( fmt, i_cat, i_codec );
1803 fmt->b_packetized = false;
1807 const int i_stream_type = strtol( psz_opt, NULL, 0 );
1808 PIDFillFormat( fmt, i_stream_type );
1811 fmt->i_group = i_number;
1812 if( p_sys->b_es_id_pid )
1815 if( fmt->i_cat != UNKNOWN_ES )
1817 msg_Dbg( p_demux, " * es pid=%d fcc=%4.4s", i_pid,
1818 (char*)&fmt->i_codec );
1819 pid->u.p_pes->es.id = es_out_Add( p_demux->out, fmt );
1828 p_sys->b_user_pmt = true;
1834 return VLC_EGENERIC;
1837 static int SetPIDFilter( demux_sys_t *p_sys, ts_pid_t *p_pid, bool b_selected )
1840 p_pid->i_flags |= FLAG_FILTERED;
1842 p_pid->i_flags &= ~FLAG_FILTERED;
1844 if( !p_sys->b_access_control )
1845 return VLC_EGENERIC;
1847 return stream_Control( p_sys->stream, STREAM_SET_PRIVATE_ID_STATE,
1848 p_pid->i_pid, b_selected );
1851 static void PIDReset( ts_pid_t *pid )
1853 assert(pid->i_refcount == 0);
1855 pid->i_flags &= ~FLAG_SCRAMBLED;
1856 pid->p_parent = NULL;
1857 pid->type = TYPE_FREE;
1860 static bool PIDSetup( demux_t *p_demux, ts_pid_type_t i_type, ts_pid_t *pid, ts_pid_t *p_parent )
1862 if( pid == p_parent || pid->i_pid == 0x1FFF )
1865 if( pid->i_refcount == 0 )
1867 assert( pid->type == TYPE_FREE );
1870 case TYPE_FREE: /* nonsense ?*/
1876 pid->u.p_pat = ts_pat_New( p_demux );
1883 pid->u.p_pmt = ts_pmt_New( p_demux );
1890 pid->u.p_pes = ts_pes_New( p_demux );
1899 pid->u.p_psi = ts_psi_New( p_demux );
1911 pid->p_parent = p_parent;
1913 else if( pid->type == i_type && pid->i_refcount < UINT8_MAX )
1919 if( pid->type != TYPE_FREE )
1920 msg_Warn( p_demux, "Tried to redeclare pid %d with another type", pid->i_pid );
1927 static void PIDRelease( demux_t *p_demux, ts_pid_t *pid )
1929 if( pid->i_refcount == 0 )
1931 assert( pid->type == TYPE_FREE );
1934 else if( pid->i_refcount == 1 )
1938 else if( pid->i_refcount > 1 )
1940 assert( pid->type != TYPE_FREE && pid->type != TYPE_PAT );
1944 if( pid->i_refcount == 0 )
1949 case TYPE_FREE: /* nonsense ?*/
1950 assert( pid->type != TYPE_FREE );
1954 ts_pat_Del( p_demux, pid->u.p_pat );
1955 pid->u.p_pat = NULL;
1959 ts_pmt_Del( p_demux, pid->u.p_pmt );
1960 pid->u.p_pmt = NULL;
1964 ts_pes_Del( p_demux, pid->u.p_pes );
1965 pid->u.p_pes = NULL;
1971 ts_psi_Del( p_demux, pid->u.p_psi );
1972 pid->u.p_psi = NULL;
1977 SetPIDFilter( p_demux->p_sys, pid, false );
1982 static int16_t read_opus_flag(uint8_t **buf, size_t *len)
1987 int16_t ret = ((*buf)[0] << 8) | (*buf)[1];
1998 static block_t *Opus_Parse(demux_t *demux, block_t *block)
2000 block_t *out = NULL;
2001 block_t **last = NULL;
2003 uint8_t *buf = block->p_buffer;
2004 size_t len = block->i_buffer;
2006 while (len > 3 && ((buf[0] << 3) | (buf[1] >> 5)) == 0x3ff) {
2007 int16_t start_trim = 0, end_trim = 0;
2008 int start_trim_flag = (buf[1] >> 4) & 1;
2009 int end_trim_flag = (buf[1] >> 3) & 1;
2010 int control_extension_flag = (buf[1] >> 2) & 1;
2015 unsigned au_size = 0;
2023 if (start_trim_flag) {
2024 start_trim = read_opus_flag(&buf, &len);
2025 if (start_trim < 0) {
2026 msg_Err(demux, "Invalid start trimming flag");
2029 if (end_trim_flag) {
2030 end_trim = read_opus_flag(&buf, &len);
2032 msg_Err(demux, "Invalid end trimming flag");
2035 if (control_extension_flag && len) {
2036 unsigned l = *buf++; len--;
2038 msg_Err(demux, "Invalid control extension length %d > %zu", l, len);
2045 if (!au_size || au_size > len) {
2046 msg_Err(demux, "Invalid Opus AU size %d (PES %zu)", au_size, len);
2050 block_t *au = block_Alloc(au_size);
2053 memcpy(au->p_buffer, buf, au_size);
2054 block_CopyProperties(au, block);
2063 au->i_nb_samples = opus_frame_duration(buf, au_size);
2064 if (end_trim && (uint16_t) end_trim <= au->i_nb_samples)
2065 au->i_length = end_trim; /* Blatant abuse of the i_length field. */
2069 if (start_trim && start_trim < (au->i_nb_samples - au->i_length)) {
2070 au->i_nb_samples -= start_trim;
2071 if (au->i_nb_samples == 0)
2072 au->i_flags |= BLOCK_FLAG_PREROLL;
2079 block_Release(block);
2083 /****************************************************************************
2085 ****************************************************************************/
2086 static int ParsePESHeader( demux_t *p_demux, const uint8_t *p_header, size_t i_header,
2087 unsigned *pi_skip, mtime_t *pi_dts, mtime_t *pi_pts )
2092 return VLC_EGENERIC;
2094 switch( p_header[3] )
2096 case 0xBC: /* Program stream map */
2097 case 0xBE: /* Padding */
2098 case 0xBF: /* Private stream 2 */
2099 case 0xF0: /* ECM */
2100 case 0xF1: /* EMM */
2101 case 0xFF: /* Program stream directory */
2102 case 0xF2: /* DSMCC stream */
2103 case 0xF8: /* ITU-T H.222.1 type E stream */
2107 if( ( p_header[6]&0xC0 ) == 0x80 )
2110 i_skip = p_header[8] + 9;
2112 if( p_header[7]&0x80 ) /* has pts */
2114 if( i_header < 9 + 5 )
2115 return VLC_EGENERIC;
2116 *pi_pts = ExtractPESTimestamp( &p_header[9] );
2118 if( p_header[7]&0x40 ) /* has dts */
2120 if( i_header < 14 + 5 )
2121 return VLC_EGENERIC;
2122 *pi_dts = ExtractPESTimestamp( &p_header[14] );
2129 if( i_header < i_skip + 1 )
2130 return VLC_EGENERIC;
2131 while( i_skip < 23 && p_header[i_skip] == 0xff )
2134 if( i_header < i_skip + 1 )
2135 return VLC_EGENERIC;
2139 msg_Err( p_demux, "too much MPEG-1 stuffing" );
2140 return VLC_EGENERIC;
2142 if( ( p_header[i_skip] & 0xC0 ) == 0x40 )
2147 if( i_header < i_skip + 1 )
2148 return VLC_EGENERIC;
2150 if( p_header[i_skip]&0x20 )
2152 if( i_header < i_skip + 5 )
2153 return VLC_EGENERIC;
2154 *pi_pts = ExtractPESTimestamp( &p_header[i_skip] );
2156 if( p_header[i_skip]&0x10 ) /* has dts */
2158 if( i_header < i_skip + 10 )
2159 return VLC_EGENERIC;
2160 *pi_dts = ExtractPESTimestamp( &p_header[i_skip+5] );
2180 static void ParsePES( demux_t *p_demux, ts_pid_t *pid, block_t *p_pes )
2183 unsigned i_pes_size = 0;
2184 unsigned i_skip = 0;
2187 mtime_t i_length = 0;
2189 assert(pid->type == TYPE_PES);
2190 assert(pid->p_parent && pid->p_parent->type == TYPE_PMT);
2192 const int i_max = block_ChainExtract( p_pes, header, 34 );
2195 block_ChainRelease( p_pes );
2199 if( SCRAMBLED(*pid) || header[0] != 0 || header[1] != 0 || header[2] != 1 )
2201 if ( !SCRAMBLED(*pid) )
2202 msg_Warn( p_demux, "invalid header [0x%02x:%02x:%02x:%02x] (pid: %d)",
2203 header[0], header[1],header[2],header[3], pid->i_pid );
2204 block_ChainRelease( p_pes );
2208 if( ParsePESHeader( p_demux, (uint8_t*)&header, i_max, &i_skip, &i_dts, &i_pts ) == VLC_EGENERIC )
2210 block_ChainRelease( p_pes );
2216 i_pts = TimeStampWrapAround( pid->p_parent->u.p_pmt, i_pts );
2218 i_dts = TimeStampWrapAround( pid->p_parent->u.p_pmt, i_dts );
2221 if( pid->u.p_pes->es.fmt.i_codec == VLC_FOURCC( 'a', '5', '2', 'b' ) ||
2222 pid->u.p_pes->es.fmt.i_codec == VLC_FOURCC( 'd', 't', 's', 'b' ) )
2226 else if( pid->u.p_pes->es.fmt.i_codec == VLC_FOURCC( 'l', 'p', 'c', 'b' ) ||
2227 pid->u.p_pes->es.fmt.i_codec == VLC_FOURCC( 's', 'p', 'u', 'b' ) ||
2228 pid->u.p_pes->es.fmt.i_codec == VLC_FOURCC( 's', 'd', 'd', 'b' ) )
2232 else if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_SUBT &&
2233 pid->u.p_pes->es.p_mpeg4desc )
2235 decoder_config_descriptor_t *dcd = &pid->u.p_pes->es.p_mpeg4desc->dec_descr;
2237 if( dcd->i_extra > 2 &&
2238 dcd->p_extra[0] == 0x10 &&
2239 ( dcd->p_extra[1]&0x10 ) )
2241 /* display length */
2242 if( p_pes->i_buffer + 2 <= i_skip )
2243 i_length = GetWBE( &p_pes->p_buffer[i_skip] );
2247 if( p_pes->i_buffer + 2 <= i_skip )
2248 i_pes_size = GetWBE( &p_pes->p_buffer[i_skip] );
2254 while( p_pes && i_skip > 0 )
2256 if( p_pes->i_buffer <= i_skip )
2258 block_t *p_next = p_pes->p_next;
2260 i_skip -= p_pes->i_buffer;
2261 block_Release( p_pes );
2266 p_pes->i_buffer -= i_skip;
2267 p_pes->p_buffer += i_skip;
2272 /* ISO/IEC 13818-1 2.7.5: if no pts and no dts, then dts == pts */
2273 if( i_pts >= 0 && i_dts < 0 )
2281 p_pes->i_dts = VLC_TS_0 + i_dts * 100 / 9;
2284 p_pes->i_pts = VLC_TS_0 + i_pts * 100 / 9;
2286 p_pes->i_length = i_length * 100 / 9;
2288 p_block = block_ChainGather( p_pes );
2289 if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_SUBT )
2291 if( i_pes_size > 0 && p_block->i_buffer > i_pes_size )
2293 p_block->i_buffer = i_pes_size;
2296 p_block = block_Realloc( p_block, 0, p_block->i_buffer + 1 );
2299 p_block->p_buffer[p_block->i_buffer -1] = '\0';
2301 else if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_TELETEXT )
2303 if( p_block->i_pts <= VLC_TS_INVALID && pid->p_parent )
2305 /* Teletext may have missing PTS (ETSI EN 300 472 Annexe A)
2306 * In this case use the last PCR + 40ms */
2307 assert( pid->p_parent->type == TYPE_PMT );
2308 if( likely(pid->p_parent->type == TYPE_PMT) )
2310 mtime_t i_pcr = pid->p_parent->u.p_pmt->pcr.i_current;
2311 if( i_pcr > VLC_TS_INVALID )
2312 p_block->i_pts = VLC_TS_0 + i_pcr * 100 / 9 + 40000;
2316 else if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_ARIB_A ||
2317 pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_ARIB_C )
2319 if( p_block->i_pts <= VLC_TS_INVALID )
2321 if( i_pes_size > 0 && p_block->i_buffer > i_pes_size )
2323 p_block->i_buffer = i_pes_size;
2326 p_block = block_Realloc( p_block, 0, p_block->i_buffer + 1 );
2329 p_block->p_buffer[p_block->i_buffer -1] = '\0';
2332 else if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_OPUS)
2334 p_block = Opus_Parse(p_demux, p_block);
2337 if( !pid->p_parent || pid->p_parent->type != TYPE_PMT )
2339 block_Release( p_block );
2343 ts_pmt_t *p_pmt = pid->p_parent->u.p_pmt;
2346 block_t *p_next = p_block->p_next;
2347 p_block->p_next = NULL;
2349 if( !p_pmt->pcr.b_fix_done ) /* Not seen yet */
2350 PCRFixHandle( p_demux, p_pmt, p_block );
2352 if( pid->u.p_pes->es.id && (p_pmt->pcr.i_current > -1 || p_pmt->pcr.b_disable) )
2354 if( pid->u.p_pes->p_prepcr_outqueue )
2356 block_ChainAppend( &pid->u.p_pes->p_prepcr_outqueue, p_block );
2357 p_block = pid->u.p_pes->p_prepcr_outqueue;
2358 p_next = p_block->p_next;
2359 p_block->p_next = NULL;
2360 pid->u.p_pes->p_prepcr_outqueue = NULL;
2363 if ( p_pmt->pcr.b_disable && p_block->i_dts > VLC_TS_INVALID &&
2364 ( p_pmt->i_pid_pcr == pid->i_pid || p_pmt->i_pid_pcr == 0x1FFF ) )
2366 ProgramSetPCR( p_demux, p_pmt, (p_block->i_dts - VLC_TS_0) * 9 / 100 - 120000 );
2369 /* Compute PCR/DTS offset if any */
2370 if( p_pmt->pcr.i_pcroffset == -1 && p_block->i_dts > VLC_TS_INVALID &&
2371 p_pmt->pcr.i_current > VLC_TS_INVALID )
2373 int64_t i_dts27 = (p_block->i_dts - VLC_TS_0) * 9 / 100;
2374 int64_t i_pcr = TimeStampWrapAround( p_pmt, p_pmt->pcr.i_current );
2375 if( i_dts27 < i_pcr )
2377 p_pmt->pcr.i_pcroffset = i_pcr - i_dts27 + 80000;
2378 msg_Warn( p_demux, "Broken stream: pid %d sends packets with dts %"PRId64
2379 "us later than pcr, applying delay",
2380 pid->i_pid, p_pmt->pcr.i_pcroffset * 100 / 9 );
2382 else p_pmt->pcr.i_pcroffset = 0;
2385 if( p_pmt->pcr.i_pcroffset != -1 )
2387 if( p_block->i_dts > VLC_TS_INVALID )
2388 p_block->i_dts += (p_pmt->pcr.i_pcroffset * 100 / 9);
2389 if( p_block->i_pts > VLC_TS_INVALID )
2390 p_block->i_pts += (p_pmt->pcr.i_pcroffset * 100 / 9);
2393 for( int i = 0; i < pid->u.p_pes->extra_es.i_size; i++ )
2395 es_out_Send( p_demux->out, pid->u.p_pes->extra_es.p_elems[i]->id,
2396 block_Duplicate( p_block ) );
2399 es_out_Send( p_demux->out, pid->u.p_pes->es.id, p_block );
2403 if( !p_pmt->pcr.b_fix_done ) /* Not seen yet */
2404 PCRFixHandle( p_demux, p_pmt, p_block );
2406 block_ChainAppend( &pid->u.p_pes->p_prepcr_outqueue, p_block );
2414 msg_Warn( p_demux, "empty pes" );
2418 static void ParseTableSection( demux_t *p_demux, ts_pid_t *pid, block_t *p_data )
2420 block_t *p_content = block_ChainGather( p_data );
2422 if ( pid->p_parent && pid->p_parent->type == TYPE_PMT )
2424 ts_pmt_t *p_pmt = pid->p_parent->u.p_pmt;
2425 mtime_t i_date = p_pmt->pcr.i_current;
2427 if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_SCTE_27 )
2429 /* We need to extract the truncated pts stored inside the payload */
2430 if( p_content->i_buffer > 9 && p_content->p_buffer[0] == 0xc6 )
2433 size_t i_offset = 4;
2434 if( p_content->p_buffer[3] & 0x40 )
2436 i_index = ((p_content->p_buffer[7] & 0x0f) << 8) |
2437 p_content->p_buffer[8];
2440 if( i_index == 0 && p_content->i_buffer > i_offset + 8 )
2442 bool is_immediate = p_content->p_buffer[i_offset + 3] & 0x40;
2445 mtime_t i_display_in = GetDWBE( &p_content->p_buffer[i_offset + 4] );
2446 if( i_display_in < i_date )
2447 i_date = i_display_in + (1ll << 32);
2449 i_date = i_display_in;
2456 p_content->i_dts = p_content->i_pts = VLC_TS_0 + i_date * 100 / 9;
2457 PCRFixHandle( p_demux, p_pmt, p_content );
2460 es_out_Send( p_demux->out, pid->u.p_pes->es.id, p_content );
2463 static void ParseData( demux_t *p_demux, ts_pid_t *pid )
2465 block_t *p_data = pid->u.p_pes->p_data;
2470 /* remove the pes from pid */
2471 pid->u.p_pes->p_data = NULL;
2472 pid->u.p_pes->i_data_size = 0;
2473 pid->u.p_pes->i_data_gathered = 0;
2474 pid->u.p_pes->pp_last = &pid->u.p_pes->p_data;
2476 if( pid->u.p_pes->data_type == TS_ES_DATA_PES )
2478 ParsePES( p_demux, pid, p_data );
2480 else if( pid->u.p_pes->data_type == TS_ES_DATA_TABLE_SECTION )
2482 ParseTableSection( p_demux, pid, p_data );
2486 block_ChainRelease( p_data );
2490 static block_t* ReadTSPacket( demux_t *p_demux )
2492 demux_sys_t *p_sys = p_demux->p_sys;
2496 /* Get a new TS packet */
2497 if( !( p_pkt = stream_Block( p_sys->stream, p_sys->i_packet_size ) ) )
2499 if( stream_Tell( p_sys->stream ) == stream_Size( p_sys->stream ) )
2500 msg_Dbg( p_demux, "EOF at %"PRId64, stream_Tell( p_sys->stream ) );
2502 msg_Dbg( p_demux, "Can't read TS packet at %"PRId64, stream_Tell(p_sys->stream) );
2506 if( p_pkt->i_buffer < TS_HEADER_SIZE + p_sys->i_packet_header_size )
2508 block_Release( p_pkt );
2512 /* Skip header (BluRay streams).
2513 * re-sync logic would do this (by adjusting packet start), but this would result in losing first and last ts packets.
2514 * First packet is usually PAT, and losing it means losing whole first GOP. This is fatal with still-image based menus.
2516 p_pkt->p_buffer += p_sys->i_packet_header_size;
2517 p_pkt->i_buffer -= p_sys->i_packet_header_size;
2519 /* Check sync byte and re-sync if needed */
2520 if( p_pkt->p_buffer[0] != 0x47 )
2522 msg_Warn( p_demux, "lost synchro" );
2523 block_Release( p_pkt );
2526 const uint8_t *p_peek;
2528 unsigned i_skip = 0;
2530 i_peek = stream_Peek( p_sys->stream, &p_peek,
2531 p_sys->i_packet_size * 10 );
2532 if( i_peek < 0 || (unsigned)i_peek < p_sys->i_packet_size + 1 )
2534 msg_Dbg( p_demux, "eof ?" );
2538 while( i_skip < i_peek - p_sys->i_packet_size )
2540 if( p_peek[i_skip + p_sys->i_packet_header_size] == 0x47 &&
2541 p_peek[i_skip + p_sys->i_packet_header_size + p_sys->i_packet_size] == 0x47 )
2547 msg_Dbg( p_demux, "skipping %d bytes of garbage", i_skip );
2548 stream_Read( p_sys->stream, NULL, i_skip );
2550 if( i_skip < i_peek - p_sys->i_packet_size )
2555 if( !( p_pkt = stream_Block( p_sys->stream, p_sys->i_packet_size ) ) )
2557 msg_Dbg( p_demux, "eof ?" );
2564 static int64_t TimeStampWrapAround( ts_pmt_t *p_pmt, int64_t i_time )
2566 int64_t i_adjust = 0;
2567 if( p_pmt && p_pmt->pcr.i_first > 0x0FFFFFFFF && i_time < 0x0FFFFFFFF )
2568 i_adjust = 0x1FFFFFFFF;
2570 return i_time + i_adjust;
2573 static mtime_t GetPCR( block_t *p_pkt )
2575 const uint8_t *p = p_pkt->p_buffer;
2579 if( ( p[3]&0x20 ) && /* adaptation */
2583 /* PCR is 33 bits */
2584 i_pcr = ( (mtime_t)p[6] << 25 ) |
2585 ( (mtime_t)p[7] << 17 ) |
2586 ( (mtime_t)p[8] << 9 ) |
2587 ( (mtime_t)p[9] << 1 ) |
2588 ( (mtime_t)p[10] >> 7 );
2593 static void UpdateScrambledState( demux_t *p_demux, ts_pid_t *p_pid, bool b_scrambled )
2595 if( !SCRAMBLED(*p_pid) == !b_scrambled )
2598 msg_Warn( p_demux, "scrambled state changed on pid %d (%d->%d)",
2599 p_pid->i_pid, SCRAMBLED(*p_pid), b_scrambled );
2601 p_pid->i_flags |= (b_scrambled) ? FLAG_SCRAMBLED : FLAGS_NONE;
2603 if( p_pid->type == TYPE_PES && p_pid->u.p_pes->es.id )
2605 for( int i = 0; i < p_pid->u.p_pes->extra_es.i_size; i++ )
2607 if( p_pid->u.p_pes->extra_es.p_elems[i]->id )
2608 es_out_Control( p_demux->out, ES_OUT_SET_ES_SCRAMBLED_STATE,
2609 p_pid->u.p_pes->extra_es.p_elems[i]->id, b_scrambled );
2611 es_out_Control( p_demux->out, ES_OUT_SET_ES_SCRAMBLED_STATE,
2612 p_pid->u.p_pes->es.id, b_scrambled );
2616 static inline void FlushESBuffer( ts_pes_t *p_pes )
2620 p_pes->i_data_gathered = p_pes->i_data_size = 0;
2621 block_ChainRelease( p_pes->p_data );
2622 p_pes->p_data = NULL;
2623 p_pes->pp_last = &p_pes->p_data;
2627 static void ReadyQueuesPostSeek( demux_t *p_demux )
2629 demux_sys_t *p_sys = p_demux->p_sys;
2631 ts_pat_t *p_pat = p_sys->pid[0].u.p_pat;
2632 for( int i=0; i< p_pat->programs.i_size; i++ )
2634 ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
2635 for( int j=0; j<p_pmt->e_streams.i_size; j++ )
2637 ts_pid_t *pid = p_pmt->e_streams.p_elems[j];
2639 if( pid->type != TYPE_PES )
2642 if( pid->u.p_pes->es.id )
2644 block_t *p_block = block_Alloc(1);
2647 p_block->i_buffer = 0;
2648 p_block->i_flags = BLOCK_FLAG_DISCONTINUITY | BLOCK_FLAG_CORRUPTED;
2649 es_out_Send( p_demux->out, pid->u.p_pes->es.id, p_block );
2655 if( pid->u.p_pes->p_prepcr_outqueue )
2657 block_ChainRelease( pid->u.p_pes->p_prepcr_outqueue );
2658 pid->u.p_pes->p_prepcr_outqueue = NULL;
2661 FlushESBuffer( pid->u.p_pes );
2663 p_pmt->pcr.i_current = -1;
2667 static int SeekToTime( demux_t *p_demux, ts_pmt_t *p_pmt, int64_t i_scaledtime )
2669 demux_sys_t *p_sys = p_demux->p_sys;
2671 /* Deal with common but worst binary search case */
2672 if( p_pmt->pcr.i_first == i_scaledtime && p_sys->b_canseek )
2673 return stream_Seek( p_sys->stream, 0 );
2675 if( !p_sys->b_canfastseek )
2676 return VLC_EGENERIC;
2678 int64_t i_initial_pos = stream_Tell( p_sys->stream );
2680 /* Find the time position by using binary search algorithm. */
2681 int64_t i_head_pos = 0;
2682 int64_t i_tail_pos = stream_Size( p_sys->stream ) - p_sys->i_packet_size;
2683 if( i_head_pos >= i_tail_pos )
2684 return VLC_EGENERIC;
2686 bool b_found = false;
2687 while( (i_head_pos + p_sys->i_packet_size) <= i_tail_pos && !b_found )
2689 /* Round i_pos to a multiple of p_sys->i_packet_size */
2690 int64_t i_splitpos = i_head_pos + (i_tail_pos - i_head_pos) / 2;
2691 int64_t i_div = i_splitpos % p_sys->i_packet_size;
2692 i_splitpos -= i_div;
2694 if ( stream_Seek( p_sys->stream, i_splitpos ) != VLC_SUCCESS )
2697 int64_t i_pos = i_splitpos;
2698 while( i_pos > -1 && i_pos < i_tail_pos )
2701 block_t *p_pkt = ReadTSPacket( p_demux );
2704 i_head_pos = i_tail_pos;
2708 i_pos = stream_Tell( p_sys->stream );
2710 int i_pid = PIDGet( p_pkt );
2711 if( i_pid != 0x1FFF && p_sys->pid[i_pid].type == TYPE_PES &&
2712 p_sys->pid[i_pid].p_parent->u.p_pmt == p_pmt &&
2713 (p_pkt->p_buffer[1] & 0xC0) == 0x40 && /* Payload start but not corrupt */
2714 (p_pkt->p_buffer[3] & 0xD0) == 0x10 /* Has payload but is not encrypted */
2717 unsigned i_skip = 4;
2718 if ( p_pkt->p_buffer[3] & 0x20 ) // adaptation field
2720 if( p_pkt->i_buffer >= 4 + 2 + 5 )
2722 i_pcr = GetPCR( p_pkt );
2723 i_skip += 1 + p_pkt->p_buffer[4];
2730 if ( VLC_SUCCESS == ParsePESHeader( p_demux, &p_pkt->p_buffer[i_skip],
2731 p_pkt->i_buffer - i_skip, &i_skip, &i_dts, &i_pts ) )
2738 block_Release( p_pkt );
2742 int64_t i_diff = i_scaledtime - TimeStampWrapAround( p_pmt, i_pcr );
2744 i_tail_pos = i_splitpos - p_sys->i_packet_size;
2745 else if( i_diff < TO_SCALE(VLC_TS_0 + CLOCK_FREQ / 2) ) // 500ms
2753 if ( !b_found && i_pos > i_tail_pos - p_sys->i_packet_size )
2754 i_tail_pos = i_splitpos - p_sys->i_packet_size;
2759 msg_Dbg( p_demux, "Seek():cannot find a time position." );
2760 stream_Seek( p_sys->stream, i_initial_pos );
2761 return VLC_EGENERIC;
2766 static ts_pmt_t * GetProgramByID( demux_sys_t *p_sys, int i_program )
2768 if(unlikely(p_sys->pid[0].type != TYPE_PAT))
2771 ts_pat_t *p_pat = p_sys->pid[0].u.p_pat;
2772 for( int i = 0; i < p_pat->programs.i_size; i++ )
2774 assert(p_pat->programs.p_elems[i]->type == TYPE_PMT);
2775 ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
2776 if( p_pmt->i_number == i_program )
2782 #define PROBE_CHUNK_COUNT 250
2784 static int ProbeChunk( demux_t *p_demux, int i_program, bool b_end, int64_t *pi_pcr, bool *pb_found )
2786 demux_sys_t *p_sys = p_demux->p_sys;
2788 block_t *p_pkt = NULL;
2794 if( i_count++ > PROBE_CHUNK_COUNT || !( p_pkt = ReadTSPacket( p_demux ) ) )
2799 const int i_pid = PIDGet( p_pkt );
2800 ts_pid_t *p_pid = &p_sys->pid[i_pid];
2802 p_pid->i_flags |= FLAG_SEEN;
2804 if( i_pid != 0x1FFF && (p_pkt->p_buffer[1] & 0x80) == 0 ) /* not corrupt */
2806 bool b_pcrresult = true;
2807 bool b_adaptfield = p_pkt->p_buffer[3] & 0x20;
2809 if( b_adaptfield && p_pkt->i_buffer >= 4 + 2 + 5 )
2810 *pi_pcr = GetPCR( p_pkt );
2812 if( *pi_pcr == -1 &&
2813 (p_pkt->p_buffer[1] & 0xC0) == 0x40 && /* payload start */
2814 (p_pkt->p_buffer[3] & 0xD0) == 0x10 && /* Has payload but is not encrypted */
2815 p_pid->type == TYPE_PES &&
2816 p_pid->u.p_pes->es.fmt.i_cat != UNKNOWN_ES
2819 b_pcrresult = false;
2822 unsigned i_skip = 4;
2823 if ( b_adaptfield ) // adaptation field
2824 i_skip += 1 + p_pkt->p_buffer[4];
2826 if ( VLC_SUCCESS == ParsePESHeader( p_demux, &p_pkt->p_buffer[i_skip],
2827 p_pkt->i_buffer - i_skip,
2828 &i_skip, &i_dts, &i_pts ) )
2832 else if( i_pts != -1 )
2839 ts_pat_t *p_pat = p_sys->pid[0].u.p_pat;
2840 for( int i=0; i<p_pat->programs.i_size; i++ )
2842 ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
2843 if( ( p_pmt->i_pid_pcr == p_pid->i_pid ||
2844 ( p_pmt->i_pid_pcr == 0x1FFF && p_pid->p_parent == p_pat->programs.p_elems[i] ) ) )
2848 p_pmt->i_last_dts = *pi_pcr;
2850 /* Start, only keep first */
2851 else if( b_pcrresult && p_pmt->pcr.i_first == -1 )
2853 p_pmt->pcr.i_first = *pi_pcr;
2855 else if( p_pmt->pcr.i_first_dts < VLC_TS_0 )
2857 p_pmt->pcr.i_first_dts = FROM_SCALE(*pi_pcr);
2860 if( i_program == 0 || i_program == p_pmt->i_number )
2867 block_Release( p_pkt );
2873 static int ProbeStart( demux_t *p_demux, int i_program )
2875 demux_sys_t *p_sys = p_demux->p_sys;
2876 const int64_t i_initial_pos = stream_Tell( p_sys->stream );
2877 int64_t i_stream_size = stream_Size( p_sys->stream );
2879 int i_probe_count = 0;
2882 bool b_found = false;
2886 i_pos = p_sys->i_packet_size * i_probe_count;
2887 i_pos = __MIN( i_pos, i_stream_size );
2889 if( stream_Seek( p_sys->stream, i_pos ) )
2890 return VLC_EGENERIC;
2892 ProbeChunk( p_demux, i_program, false, &i_pcr, &b_found );
2894 /* Go ahead one more chunk if end of file contained only stuffing packets */
2895 i_probe_count += PROBE_CHUNK_COUNT;
2896 } while( i_pos > 0 && (i_pcr == -1 || !b_found) && i_probe_count < (2 * PROBE_CHUNK_COUNT) );
2898 stream_Seek( p_sys->stream, i_initial_pos );
2900 return (b_found) ? VLC_SUCCESS : VLC_EGENERIC;
2903 static int ProbeEnd( demux_t *p_demux, int i_program )
2905 demux_sys_t *p_sys = p_demux->p_sys;
2906 const int64_t i_initial_pos = stream_Tell( p_sys->stream );
2907 int64_t i_stream_size = stream_Size( p_sys->stream );
2909 int i_probe_count = PROBE_CHUNK_COUNT;
2912 bool b_found = false;
2916 i_pos = i_stream_size - (p_sys->i_packet_size * i_probe_count);
2917 i_pos = __MAX( i_pos, 0 );
2919 if( stream_Seek( p_sys->stream, i_pos ) )
2920 return VLC_EGENERIC;
2922 ProbeChunk( p_demux, i_program, true, &i_pcr, &b_found );
2924 /* Go ahead one more chunk if end of file contained only stuffing packets */
2925 i_probe_count += PROBE_CHUNK_COUNT;
2926 } while( i_pos > 0 && (i_pcr == -1 || !b_found) && i_probe_count < (6 * PROBE_CHUNK_COUNT) );
2928 stream_Seek( p_sys->stream, i_initial_pos );
2930 return (b_found) ? VLC_SUCCESS : VLC_EGENERIC;
2933 static void ProgramSetPCR( demux_t *p_demux, ts_pmt_t *p_pmt, mtime_t i_pcr )
2935 demux_sys_t *p_sys = p_demux->p_sys;
2937 /* Check if we have enqueued blocks waiting the/before the
2938 PCR barrier, and then adapt pcr so they have valid PCR when dequeuing */
2939 if( p_pmt->pcr.i_current == -1 && p_pmt->pcr.b_fix_done )
2941 mtime_t i_mindts = -1;
2943 ts_pat_t *p_pat = p_sys->pid[0].u.p_pat;
2944 for( int i=0; i< p_pat->programs.i_size; i++ )
2946 ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
2947 for( int j=0; j<p_pmt->e_streams.i_size; j++ )
2949 ts_pid_t *p_pid = p_pmt->e_streams.p_elems[j];
2950 block_t *p_block = p_pid->u.p_pes->p_prepcr_outqueue;
2951 while( p_block && p_block->i_dts == VLC_TS_INVALID )
2952 p_block = p_block->p_next;
2954 if( p_block && ( i_mindts == -1 || p_block->i_dts < i_mindts ) )
2955 i_mindts = p_block->i_dts;
2959 if( i_mindts > VLC_TS_INVALID )
2961 msg_Dbg( p_demux, "Program %d PCR prequeue fixup %"PRId64"->%"PRId64,
2962 p_pmt->i_number, TO_SCALE(i_mindts), i_pcr );
2963 i_pcr = TO_SCALE(i_mindts);
2967 p_pmt->pcr.i_current = i_pcr;
2968 if( p_pmt->pcr.i_first == -1 )
2970 p_pmt->pcr.i_first = i_pcr; // now seen
2973 if ( p_sys->i_pmt_es )
2975 es_out_Control( p_demux->out, ES_OUT_SET_GROUP_PCR,
2976 p_pmt->i_number, VLC_TS_0 + i_pcr * 100 / 9 );
2980 static void PCRHandle( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
2982 demux_sys_t *p_sys = p_demux->p_sys;
2984 if( p_sys->i_pmt_es <= 0 )
2987 mtime_t i_pcr = GetPCR( p_bk );
2991 pid->probed.i_pcr_count++;
2993 if(unlikely(p_sys->pid[0].type != TYPE_PAT))
2996 /* Search program and set the PCR */
2997 ts_pat_t *p_pat = p_sys->pid[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 mtime_t i_program_pcr = TimeStampWrapAround( p_pmt, i_pcr );
3003 if( p_pmt->i_pid_pcr == 0x1FFF ) /* That program has no dedicated PCR pid ISO/IEC 13818-1 2.4.4.9 */
3005 if( pid->p_parent == p_pat->programs.p_elems[i] ) /* PCR shall be on pid itself */
3007 /* ? update PCR for the whole group program ? */
3008 ProgramSetPCR( p_demux, p_pmt, i_program_pcr );
3011 else /* set PCR provided by current pid to program(s) referencing it */
3013 /* Can be dedicated PCR pid (no owned then) or another pid (owner == pmt) */
3014 if( p_pmt->i_pid_pcr == pid->i_pid ) /* If that program references current pid as PCR */
3016 /* We've found a target group for update */
3017 ProgramSetPCR( p_demux, p_pmt, i_program_pcr );
3024 static int FindPCRCandidate( ts_pmt_t *p_pmt )
3026 ts_pid_t *p_cand = NULL;
3027 int i_previous = p_pmt->i_pid_pcr;
3029 for( int i=0; i<p_pmt->e_streams.i_size; i++ )
3031 ts_pid_t *p_pid = p_pmt->e_streams.p_elems[i];
3033 (!p_cand || p_cand->i_pid != i_previous) )
3035 if( p_pid->probed.i_pcr_count ) /* check PCR frequency first */
3037 if( !p_cand || p_pid->probed.i_pcr_count > p_cand->probed.i_pcr_count )
3044 if( p_pid->u.p_pes->es.fmt.i_cat == AUDIO_ES )
3049 else if ( p_pid->u.p_pes->es.fmt.i_cat == VIDEO_ES ) /* Otherwise prioritize video dts */
3051 if( !p_cand || p_cand->u.p_pes->es.fmt.i_cat == AUDIO_ES )
3058 return p_cand->i_pid;
3063 /* Tries to reselect a new PCR when none has been received */
3064 static void PCRFixHandle( demux_t *p_demux, ts_pmt_t *p_pmt, block_t *p_block )
3066 if ( p_pmt->pcr.b_disable || p_pmt->pcr.b_fix_done )
3070 /* Record the first data packet timestamp in case there wont be any PCR */
3071 else if( !p_pmt->pcr.i_first_dts )
3073 p_pmt->pcr.i_first_dts = p_block->i_dts;
3075 else if( p_block->i_dts - p_pmt->pcr.i_first_dts > CLOCK_FREQ / 2 ) /* "PCR repeat rate shall not exceed 100ms" */
3077 if( p_pmt->pcr.i_current < 0 )
3079 int i_cand = FindPCRCandidate( p_pmt );
3080 p_pmt->i_pid_pcr = i_cand;
3081 msg_Warn( p_demux, "No PCR received for program %d, set up workaround using pid %d",
3082 p_pmt->i_number, i_cand );
3083 UpdatePESFilters( p_demux, p_demux->p_sys->b_es_all );
3084 p_pmt->pcr.b_fix_done = true;
3089 static bool GatherData( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
3091 const uint8_t *p = p_bk->p_buffer;
3092 const bool b_unit_start = p[1]&0x40;
3093 const bool b_adaptation = p[3]&0x20;
3094 const bool b_payload = p[3]&0x10;
3095 const int i_cc = p[3]&0x0f; /* continuity counter */
3096 bool b_discontinuity = false; /* discontinuity */
3098 /* transport_scrambling_control is ignored */
3103 msg_Dbg( p_demux, "pid=%d unit_start=%d adaptation=%d payload=%d "
3104 "cc=0x%x", pid->i_pid, b_unit_start, b_adaptation,
3108 /* For now, ignore additional error correction
3109 * TODO: handle Reed-Solomon 204,188 error correction */
3110 p_bk->i_buffer = TS_PACKET_SIZE_188;
3114 msg_Dbg( p_demux, "transport_error_indicator set (pid=%d)",
3116 if( pid->u.p_pes->p_data ) //&& pid->es->fmt.i_cat == VIDEO_ES )
3117 pid->u.p_pes->p_data->i_flags |= BLOCK_FLAG_CORRUPTED;
3120 if( p_demux->p_sys->csa )
3122 vlc_mutex_lock( &p_demux->p_sys->csa_lock );
3123 csa_Decrypt( p_demux->p_sys->csa, p_bk->p_buffer, p_demux->p_sys->i_csa_pkt_size );
3124 vlc_mutex_unlock( &p_demux->p_sys->csa_lock );
3129 /* We don't have any adaptation_field, so payload starts
3130 * immediately after the 4 byte TS header */
3135 /* p[4] is adaptation_field_length minus one */
3139 /* discontinuity indicator found in stream */
3140 b_discontinuity = (p[5]&0x80) ? true : false;
3141 if( b_discontinuity && pid->u.p_pes->p_data )
3143 msg_Warn( p_demux, "discontinuity indicator (pid=%d) ",
3145 /* pid->es->p_data->i_flags |= BLOCK_FLAG_DISCONTINUITY; */
3149 msg_Dbg( p_demux, "random access indicator (pid=%d) ", pid->i_pid );
3154 /* Test continuity counter */
3155 /* continuous when (one of this):
3157 * diff == 0 and payload == 0
3158 * diff == 0 and duplicate packet (playload != 0) <- should we
3159 * test the content ?
3161 const int i_diff = ( i_cc - pid->i_cc )&0x0f;
3162 if( b_payload && i_diff == 1 )
3164 pid->i_cc = ( pid->i_cc + 1 ) & 0xf;
3168 if( pid->i_cc == 0xff )
3170 msg_Warn( p_demux, "first packet for pid=%d cc=0x%x",
3174 else if( i_diff != 0 && !b_discontinuity )
3176 msg_Warn( p_demux, "discontinuity received 0x%x instead of 0x%x (pid=%d)",
3177 i_cc, ( pid->i_cc + 1 )&0x0f, pid->i_pid );
3180 if( pid->u.p_pes->p_data && pid->u.p_pes->es.fmt.i_cat != VIDEO_ES &&
3181 pid->u.p_pes->es.fmt.i_cat != AUDIO_ES )
3183 /* Small audio/video artifacts are usually better than
3184 * dropping full frames */
3185 pid->u.p_pes->p_data->i_flags |= BLOCK_FLAG_CORRUPTED;
3190 PCRHandle( p_demux, pid, p_bk );
3194 block_Release( p_bk );
3198 /* We have to gather it */
3199 p_bk->p_buffer += i_skip;
3200 p_bk->i_buffer -= i_skip;
3204 if( pid->u.p_pes->data_type == TS_ES_DATA_TABLE_SECTION && p_bk->i_buffer > 0 )
3206 int i_pointer_field = __MIN( p_bk->p_buffer[0], p_bk->i_buffer - 1 );
3207 block_t *p = block_Duplicate( p_bk );
3210 p->i_buffer = i_pointer_field;
3212 block_ChainLastAppend( &pid->u.p_pes->pp_last, p );
3214 p_bk->i_buffer -= 1 + i_pointer_field;
3215 p_bk->p_buffer += 1 + i_pointer_field;
3217 if( pid->u.p_pes->p_data )
3219 ParseData( p_demux, pid );
3223 block_ChainLastAppend( &pid->u.p_pes->pp_last, p_bk );
3224 if( pid->u.p_pes->data_type == TS_ES_DATA_PES )
3226 if( p_bk->i_buffer > 6 )
3228 pid->u.p_pes->i_data_size = GetWBE( &p_bk->p_buffer[4] );
3229 if( pid->u.p_pes->i_data_size > 0 )
3231 pid->u.p_pes->i_data_size += 6;
3235 else if( pid->u.p_pes->data_type == TS_ES_DATA_TABLE_SECTION )
3237 if( p_bk->i_buffer > 3 && p_bk->p_buffer[0] != 0xff )
3239 pid->u.p_pes->i_data_size = 3 + (((p_bk->p_buffer[1] & 0xf) << 8) | p_bk->p_buffer[2]);
3242 pid->u.p_pes->i_data_gathered += p_bk->i_buffer;
3243 if( pid->u.p_pes->i_data_size > 0 &&
3244 pid->u.p_pes->i_data_gathered >= pid->u.p_pes->i_data_size )
3246 ParseData( p_demux, pid );
3252 if( pid->u.p_pes->p_data == NULL )
3254 /* msg_Dbg( p_demux, "broken packet" ); */
3255 block_Release( p_bk );
3259 block_ChainLastAppend( &pid->u.p_pes->pp_last, p_bk );
3260 pid->u.p_pes->i_data_gathered += p_bk->i_buffer;
3262 if( pid->u.p_pes->i_data_size > 0 &&
3263 pid->u.p_pes->i_data_gathered >= pid->u.p_pes->i_data_size )
3265 ParseData( p_demux, pid );
3274 static void PIDFillFormat( es_format_t *fmt, int i_stream_type )
3276 switch( i_stream_type )
3278 case 0x01: /* MPEG-1 video */
3279 case 0x02: /* MPEG-2 video */
3280 case 0x80: /* MPEG-2 MOTO video */
3281 es_format_Init( fmt, VIDEO_ES, VLC_CODEC_MPGV );
3283 case 0x03: /* MPEG-1 audio */
3284 case 0x04: /* MPEG-2 audio */
3285 es_format_Init( fmt, AUDIO_ES, VLC_CODEC_MPGA );
3287 case 0x11: /* MPEG4 (audio) LATM */
3288 case 0x0f: /* ISO/IEC 13818-7 Audio with ADTS transport syntax */
3289 case 0x1c: /* ISO/IEC 14496-3 Audio, without using any additional
3290 transport syntax, such as DST, ALS and SLS */
3291 es_format_Init( fmt, AUDIO_ES, VLC_CODEC_MP4A );
3293 case 0x10: /* MPEG4 (video) */
3294 es_format_Init( fmt, VIDEO_ES, VLC_CODEC_MP4V );
3296 case 0x1B: /* H264 <- check transport syntax/needed descriptor */
3297 es_format_Init( fmt, VIDEO_ES, VLC_CODEC_H264 );
3299 case 0x24: /* HEVC */
3300 es_format_Init( fmt, VIDEO_ES, VLC_CODEC_HEVC );
3302 case 0x42: /* CAVS (Chinese AVS) */
3303 es_format_Init( fmt, VIDEO_ES, VLC_CODEC_CAVS );
3306 case 0x81: /* A52 (audio) */
3307 es_format_Init( fmt, AUDIO_ES, VLC_CODEC_A52 );
3309 case 0x82: /* SCTE-27 (sub) */
3310 es_format_Init( fmt, SPU_ES, VLC_CODEC_SCTE_27 );
3312 case 0x84: /* SDDS (audio) */
3313 es_format_Init( fmt, AUDIO_ES, VLC_CODEC_SDDS );
3315 case 0x85: /* DTS (audio) */
3316 es_format_Init( fmt, AUDIO_ES, VLC_CODEC_DTS );
3318 case 0x87: /* E-AC3 */
3319 es_format_Init( fmt, AUDIO_ES, VLC_CODEC_EAC3 );
3322 case 0x91: /* A52 vls (audio) */
3323 es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'a', '5', '2', 'b' ) );
3325 case 0x92: /* DVD_SPU vls (sub) */
3326 es_format_Init( fmt, SPU_ES, VLC_FOURCC( 's', 'p', 'u', 'b' ) );
3329 case 0x94: /* SDDS (audio) */
3330 es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 's', 'd', 'd', 'b' ) );
3333 case 0xa0: /* MSCODEC vlc (video) (fixed later) */
3334 es_format_Init( fmt, UNKNOWN_ES, 0 );
3337 case 0x06: /* PES_PRIVATE (fixed later) */
3338 case 0x12: /* MPEG-4 generic (sub/scene/...) (fixed later) */
3339 case 0xEA: /* Privately managed ES (VC-1) (fixed later */
3341 es_format_Init( fmt, UNKNOWN_ES, 0 );
3345 /* PES packets usually contain truncated frames */
3346 fmt->b_packetized = false;
3349 /*****************************************************************************
3350 * MP4 specific functions (IOD parser)
3351 *****************************************************************************/
3352 static unsigned IODDescriptorLength( unsigned *pi_data, uint8_t **pp_data )
3355 unsigned int i_len = 0;
3361 i_len = ( i_len << 7 ) + ( i_b&0x7f );
3363 } while( i_b&0x80 && *pi_data > 0 );
3365 if (i_len > *pi_data)
3371 static unsigned IODGetBytes( unsigned *pi_data, uint8_t **pp_data, size_t bytes )
3374 while( *pi_data > 0 && bytes-- )
3385 static char* IODGetURL( unsigned *pi_data, uint8_t **pp_data )
3387 unsigned len = IODGetBytes( pi_data, pp_data, 1 );
3390 char *url = strndup( (char*)*pp_data, len );
3396 static iod_descriptor_t *IODNew( unsigned i_data, uint8_t *p_data )
3398 uint8_t i_iod_tag, i_iod_label, byte1, byte2, byte3;
3400 iod_descriptor_t *p_iod = calloc( 1, sizeof( iod_descriptor_t ) );
3409 byte1 = IODGetBytes( &i_data, &p_data, 1 );
3410 byte2 = IODGetBytes( &i_data, &p_data, 1 );
3411 byte3 = IODGetBytes( &i_data, &p_data, 1 );
3412 if( byte2 == 0x02 ) //old vlc's buggy implementation of the IOD_descriptor
3414 i_iod_label = byte1;
3417 else //correct implementation of the IOD_descriptor
3419 i_iod_label = byte2;
3423 ts_debug( "\n* iod label:%d tag:0x%x", i_iod_label, i_iod_tag );
3425 if( i_iod_tag != 0x02 )
3427 ts_debug( "\n ERR: tag %02x != 0x02", i_iod_tag );
3431 IODDescriptorLength( &i_data, &p_data );
3433 uint16_t i_od_id = ( IODGetBytes( &i_data, &p_data, 1 ) << 2 );
3434 uint8_t i_flags = IODGetBytes( &i_data, &p_data, 1 );
3435 i_od_id |= i_flags >> 6;
3436 ts_debug( "\n* od_id:%d", i_od_id );
3437 ts_debug( "\n* includeInlineProfileLevel flag:%d", ( i_flags >> 4 )&0x01 );
3438 if ((i_flags >> 5) & 0x01)
3440 p_iod->psz_url = IODGetURL( &i_data, &p_data );
3441 ts_debug( "\n* url string:%s", p_iod->psz_url );
3442 ts_debug( "\n*****************************\n" );
3447 p_iod->psz_url = NULL;
3450 /* Profile Level Indication */
3451 IODGetBytes( &i_data, &p_data, 1 ); /* OD */
3452 IODGetBytes( &i_data, &p_data, 1 ); /* scene */
3453 IODGetBytes( &i_data, &p_data, 1 ); /* audio */
3454 IODGetBytes( &i_data, &p_data, 1 ); /* visual */
3455 IODGetBytes( &i_data, &p_data, 1 ); /* graphics */
3457 unsigned i_length = 0;
3458 unsigned i_data_sav = i_data;
3459 uint8_t *p_data_sav = p_data;
3460 for (unsigned i = 0; i_data > 0 && i < ES_DESCRIPTOR_COUNT; i++)
3462 es_mpeg4_descriptor_t *es_descr = &p_iod->es_descr[i];
3464 p_data = p_data_sav + i_length;
3465 i_data = i_data_sav - i_length;
3467 uint8_t i_tag = IODGetBytes( &i_data, &p_data, 1 );
3468 i_length = IODDescriptorLength( &i_data, &p_data );
3470 i_data_sav = i_data;
3471 p_data_sav = p_data;
3475 if ( i_tag != 0x03 )
3477 ts_debug( "\n* - OD tag:0x%x Unsupported", i_tag );
3481 es_descr->i_es_id = IODGetBytes( &i_data, &p_data, 2 );
3482 uint8_t i_flags = IODGetBytes( &i_data, &p_data, 1 );
3483 bool b_streamDependenceFlag = ( i_flags >> 7 )&0x01;
3484 if( b_streamDependenceFlag )
3485 IODGetBytes( &i_data, &p_data, 2 ); /* dependOn_es_id */
3487 if( (i_flags >> 6) & 0x01 )
3488 es_descr->psz_url = IODGetURL( &i_data, &p_data );
3490 bool b_OCRStreamFlag = ( i_flags >> 5 )&0x01;
3491 if( b_OCRStreamFlag )
3492 IODGetBytes( &i_data, &p_data, 2 ); /* OCR_es_id */
3494 if( IODGetBytes( &i_data, &p_data, 1 ) != 0x04 )
3496 ts_debug( "\n* ERR missing DecoderConfigDescr" );
3499 unsigned i_config_desc_length = IODDescriptorLength( &i_data, &p_data ); /* DecoderConfigDescr_length */
3500 decoder_config_descriptor_t *dec_descr = &es_descr->dec_descr;
3501 dec_descr->i_objectTypeIndication = IODGetBytes( &i_data, &p_data, 1 );
3502 i_flags = IODGetBytes( &i_data, &p_data, 1 );
3503 dec_descr->i_streamType = i_flags >> 2;
3505 IODGetBytes( &i_data, &p_data, 3); /* bufferSizeDB */
3506 IODGetBytes( &i_data, &p_data, 4); /* maxBitrate */
3507 IODGetBytes( &i_data, &p_data, 4 ); /* avgBitrate */
3509 if( i_config_desc_length > 13 && IODGetBytes( &i_data, &p_data, 1 ) == 0x05 )
3511 dec_descr->i_extra = IODDescriptorLength( &i_data, &p_data );
3512 if( dec_descr->i_extra > 0 )
3514 dec_descr->p_extra = xmalloc( dec_descr->i_extra );
3515 memcpy(dec_descr->p_extra, p_data, dec_descr->i_extra);
3516 p_data += dec_descr->i_extra;
3517 i_data -= dec_descr->i_extra;
3522 dec_descr->i_extra = 0;
3523 dec_descr->p_extra = NULL;
3526 if( IODGetBytes( &i_data, &p_data, 1 ) != 0x06 )
3528 ts_debug( "\n* ERR missing SLConfigDescr" );
3531 IODDescriptorLength( &i_data, &p_data ); /* SLConfigDescr_length */
3532 switch( IODGetBytes( &i_data, &p_data, 1 ) /* predefined */ )
3535 ts_debug( "\n* ERR unsupported SLConfigDescr predefined" );
3540 es_descr->b_ok = true;
3546 static void IODFree( iod_descriptor_t *p_iod )
3548 if( p_iod->psz_url )
3550 free( p_iod->psz_url );
3555 for( int i = 0; i < 255; i++ )
3557 #define es_descr p_iod->es_descr[i]
3560 if( es_descr.psz_url )
3561 free( es_descr.psz_url );
3563 free( es_descr.dec_descr.p_extra );
3570 /****************************************************************************
3571 ****************************************************************************
3572 ** libdvbpsi callbacks
3573 ****************************************************************************
3574 ****************************************************************************/
3575 static bool ProgramIsSelected( demux_sys_t *p_sys, uint16_t i_pgrm )
3577 for(int i=0; i<p_sys->programs.i_size; i++)
3578 if( p_sys->programs.p_elems[i] == i_pgrm )
3584 static void ValidateDVBMeta( demux_t *p_demux, int i_pid )
3586 demux_sys_t *p_sys = p_demux->p_sys;
3588 if( !p_sys->b_dvb_meta || ( i_pid != 0x11 && i_pid != 0x12 && i_pid != 0x14 ) )
3591 msg_Warn( p_demux, "Switching to non DVB mode" );
3593 /* This doesn't look like a DVB stream so don't try
3594 * parsing the SDT/EDT/TDT */
3596 PIDRelease( p_demux, &p_sys->pid[0x11] );
3597 PIDRelease( p_demux, &p_sys->pid[0x12] );
3598 PIDRelease( p_demux, &p_sys->pid[0x14] );
3599 p_sys->b_dvb_meta = false;
3602 #include "dvb-text.h"
3604 static char *EITConvertToUTF8( demux_t *p_demux,
3605 const unsigned char *psz_instring,
3609 demux_sys_t *p_sys = p_demux->p_sys;
3611 if( p_sys->arib.e_mode == ARIBMODE_ENABLED )
3613 if ( !p_sys->arib.p_instance )
3614 p_sys->arib.p_instance = arib_instance_new( p_demux );
3615 if ( !p_sys->arib.p_instance )
3617 arib_decoder_t *p_decoder = arib_get_decoder( p_sys->arib.p_instance );
3621 char *psz_outstring = NULL;
3624 i_out = i_length * 4;
3625 psz_outstring = (char*) calloc( i_out + 1, sizeof(char) );
3626 if( !psz_outstring )
3629 arib_initialize_decoder( p_decoder );
3630 i_out = arib_decode_buffer( p_decoder, psz_instring, i_length,
3631 psz_outstring, i_out );
3632 arib_finalize_decoder( p_decoder );
3634 return psz_outstring;
3639 /* Deal with no longer broken providers (no switch byte
3640 but sending ISO_8859-1 instead of ISO_6937) without
3641 removing them from the broken providers table
3642 (keep the entry for correctly handling recorded TS).
3644 b_broken = b_broken && i_length && *psz_instring > 0x20;
3647 return FromCharset( "ISO_8859-1", psz_instring, i_length );
3648 return vlc_from_EIT( psz_instring, i_length );
3651 static void SDTCallBack( demux_t *p_demux, dvbpsi_sdt_t *p_sdt )
3653 demux_sys_t *p_sys = p_demux->p_sys;
3654 ts_pid_t *sdt = &p_sys->pid[0x11];
3655 dvbpsi_sdt_service_t *p_srv;
3657 msg_Dbg( p_demux, "SDTCallBack called" );
3659 if( p_sys->es_creation != CREATE_ES ||
3660 !p_sdt->b_current_next ||
3661 p_sdt->i_version == sdt->u.p_psi->i_version )
3663 dvbpsi_sdt_delete( p_sdt );
3667 msg_Dbg( p_demux, "new SDT ts_id=%d version=%d current_next=%d "
3670 p_sdt->i_version, p_sdt->b_current_next,
3671 p_sdt->i_network_id );
3673 p_sys->b_broken_charset = false;
3675 for( p_srv = p_sdt->p_first_service; p_srv; p_srv = p_srv->p_next )
3678 dvbpsi_descriptor_t *p_dr;
3680 const char *psz_type = NULL;
3681 const char *psz_status = NULL;
3683 msg_Dbg( p_demux, " * service id=%d eit schedule=%d present=%d "
3684 "running=%d free_ca=%d",
3685 p_srv->i_service_id, p_srv->b_eit_schedule,
3686 p_srv->b_eit_present, p_srv->i_running_status,
3689 if( p_sys->vdr.i_service && p_srv->i_service_id != p_sys->vdr.i_service )
3691 msg_Dbg( p_demux, " * service id=%d skipped (not declared in vdr header)",
3692 p_sys->vdr.i_service );
3696 p_meta = vlc_meta_New();
3697 for( p_dr = p_srv->p_first_descriptor; p_dr; p_dr = p_dr->p_next )
3699 if( p_dr->i_tag == 0x48 )
3701 static const char *ppsz_type[17] = {
3703 "Digital television service",
3704 "Digital radio sound service",
3706 "NVOD reference service",
3707 "NVOD time-shifted service",
3710 "SECAM coded signal",
3713 "NTSC coded signal",
3714 "Data broadcast service",
3715 "Reserved for Common Interface Usage",
3716 "RCS Map (see EN 301 790 [35])",
3717 "RCS FLS (see EN 301 790 [35])",
3720 dvbpsi_service_dr_t *pD = dvbpsi_DecodeServiceDr( p_dr );
3724 /* Workarounds for broadcasters with broken EPG */
3726 if( p_sdt->i_network_id == 133 )
3727 p_sys->b_broken_charset = true; /* SKY DE & BetaDigital use ISO8859-1 */
3729 /* List of providers using ISO8859-1 */
3730 static const char ppsz_broken_providers[][8] = {
3731 "CSAT", /* CanalSat FR */
3732 "GR1", /* France televisions */
3734 "MR5", /* France 2/M6 HD */
3737 for( int i = 0; *ppsz_broken_providers[i]; i++ )
3739 const size_t i_length = strlen(ppsz_broken_providers[i]);
3740 if( pD->i_service_provider_name_length == i_length &&
3741 !strncmp( (char *)pD->i_service_provider_name, ppsz_broken_providers[i], i_length ) )
3742 p_sys->b_broken_charset = true;
3745 /* FIXME: Digital+ ES also uses ISO8859-1 */
3747 str1 = EITConvertToUTF8(p_demux,
3748 pD->i_service_provider_name,
3749 pD->i_service_provider_name_length,
3750 p_sys->b_broken_charset );
3751 str2 = EITConvertToUTF8(p_demux,
3753 pD->i_service_name_length,
3754 p_sys->b_broken_charset );
3756 msg_Dbg( p_demux, " - type=%d provider=%s name=%s",
3757 pD->i_service_type, str1, str2 );
3759 vlc_meta_SetTitle( p_meta, str2 );
3760 vlc_meta_SetPublisher( p_meta, str1 );
3761 if( pD->i_service_type >= 0x01 && pD->i_service_type <= 0x10 )
3762 psz_type = ppsz_type[pD->i_service_type];
3768 if( p_srv->i_running_status >= 0x01 && p_srv->i_running_status <= 0x04 )
3770 static const char *ppsz_status[5] = {
3773 "Starts in a few seconds",
3777 psz_status = ppsz_status[p_srv->i_running_status];
3781 vlc_meta_AddExtra( p_meta, "Type", psz_type );
3783 vlc_meta_AddExtra( p_meta, "Status", psz_status );
3785 es_out_Control( p_demux->out, ES_OUT_SET_GROUP_META,
3786 p_srv->i_service_id, p_meta );
3787 vlc_meta_Delete( p_meta );
3790 sdt->u.p_psi->i_version = p_sdt->i_version;
3791 dvbpsi_sdt_delete( p_sdt );
3794 /* i_year: year - 1900 i_month: 0-11 i_mday: 1-31 i_hour: 0-23 i_minute: 0-59 i_second: 0-59 */
3795 static int64_t vlc_timegm( int i_year, int i_month, int i_mday, int i_hour, int i_minute, int i_second )
3797 static const int pn_day[12+1] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
3801 i_month < 0 || i_month > 11 || i_mday < 1 || i_mday > 31 ||
3802 i_hour < 0 || i_hour > 23 || i_minute < 0 || i_minute > 59 || i_second < 0 || i_second > 59 )
3805 /* Count the number of days */
3806 i_day = 365 * (i_year-70) + pn_day[i_month] + i_mday - 1;
3807 #define LEAP(y) ( ((y)%4) == 0 && (((y)%100) != 0 || ((y)%400) == 0) ? 1 : 0)
3808 for( int i = 70; i < i_year; i++ )
3809 i_day += LEAP(1900+i);
3811 i_day += LEAP(1900+i_year);
3814 return ((24*i_day + i_hour)*60 + i_minute)*60 + i_second;
3817 static void EITDecodeMjd( int i_mjd, int *p_y, int *p_m, int *p_d )
3819 const int yp = (int)( ( (double)i_mjd - 15078.2)/365.25 );
3820 const int mp = (int)( ((double)i_mjd - 14956.1 - (int)(yp * 365.25)) / 30.6001 );
3821 const int c = ( mp == 14 || mp == 15 ) ? 1 : 0;
3823 *p_y = 1900 + yp + c*1;
3824 *p_m = mp - 1 - c*12;
3825 *p_d = i_mjd - 14956 - (int)(yp*365.25) - (int)(mp*30.6001);
3827 #define CVT_FROM_BCD(v) ((((v) >> 4)&0xf)*10 + ((v)&0xf))
3828 static int64_t EITConvertStartTime( uint64_t i_date )
3830 const int i_mjd = i_date >> 24;
3831 const int i_hour = CVT_FROM_BCD(i_date >> 16);
3832 const int i_minute = CVT_FROM_BCD(i_date >> 8);
3833 const int i_second = CVT_FROM_BCD(i_date );
3838 /* if all 40 bits are 1, the start is unknown */
3839 if( i_date == UINT64_C(0xffffffffff) )
3842 EITDecodeMjd( i_mjd, &i_year, &i_month, &i_day );
3843 return vlc_timegm( i_year - 1900, i_month - 1, i_day, i_hour, i_minute, i_second );
3845 static int EITConvertDuration( uint32_t i_duration )
3847 return CVT_FROM_BCD(i_duration >> 16) * 3600 +
3848 CVT_FROM_BCD(i_duration >> 8 ) * 60 +
3849 CVT_FROM_BCD(i_duration );
3853 static void TDTCallBack( demux_t *p_demux, dvbpsi_tot_t *p_tdt )
3855 demux_sys_t *p_sys = p_demux->p_sys;
3857 p_sys->i_tdt_delta = CLOCK_FREQ * EITConvertStartTime( p_tdt->i_utc_time )
3859 dvbpsi_tot_delete(p_tdt);
3863 static void EITCallBack( demux_t *p_demux,
3864 dvbpsi_eit_t *p_eit, bool b_current_following )
3866 demux_sys_t *p_sys = p_demux->p_sys;
3867 dvbpsi_eit_event_t *p_evt;
3870 msg_Dbg( p_demux, "EITCallBack called" );
3871 if( !p_eit->b_current_next )
3873 dvbpsi_eit_delete( p_eit );
3877 msg_Dbg( p_demux, "new EIT service_id=%d version=%d current_next=%d "
3878 "ts_id=%d network_id=%d segment_last_section_number=%d "
3881 p_eit->i_version, p_eit->b_current_next,
3882 p_eit->i_ts_id, p_eit->i_network_id,
3883 p_eit->i_segment_last_section_number, p_eit->i_last_table_id );
3885 p_epg = vlc_epg_New( NULL );
3886 for( p_evt = p_eit->p_first_event; p_evt; p_evt = p_evt->p_next )
3888 dvbpsi_descriptor_t *p_dr;
3889 char *psz_name = NULL;
3890 char *psz_text = NULL;
3891 char *psz_extra = strdup("");
3895 int64_t i_tot_time = 0;
3897 i_start = EITConvertStartTime( p_evt->i_start_time );
3898 i_duration = EITConvertDuration( p_evt->i_duration );
3900 if( p_sys->arib.e_mode == ARIBMODE_ENABLED )
3902 if( p_sys->i_tdt_delta == 0 )
3903 p_sys->i_tdt_delta = CLOCK_FREQ * (i_start + i_duration - 5) - mdate();
3905 i_tot_time = (mdate() + p_sys->i_tdt_delta) / CLOCK_FREQ;
3907 tzset(); // JST -> UTC
3908 i_start += timezone; // FIXME: what about DST?
3909 i_tot_time += timezone;
3911 if( p_evt->i_running_status == 0x00 &&
3912 (i_start - 5 < i_tot_time &&
3913 i_tot_time < i_start + i_duration + 5) )
3915 p_evt->i_running_status = 0x04;
3916 msg_Dbg( p_demux, " EIT running status 0x00 -> 0x04" );
3920 msg_Dbg( p_demux, " * event id=%d start_time:%d duration=%d "
3921 "running=%d free_ca=%d",
3922 p_evt->i_event_id, (int)i_start, (int)i_duration,
3923 p_evt->i_running_status, p_evt->b_free_ca );
3925 for( p_dr = p_evt->p_first_descriptor; p_dr; p_dr = p_dr->p_next )
3931 dvbpsi_short_event_dr_t *pE = dvbpsi_DecodeShortEventDr( p_dr );
3933 /* Only take first description, as we don't handle language-info
3935 if( pE && psz_name == NULL )
3937 psz_name = EITConvertToUTF8( p_demux,
3938 pE->i_event_name, pE->i_event_name_length,
3939 p_sys->b_broken_charset );
3941 psz_text = EITConvertToUTF8( p_demux,
3942 pE->i_text, pE->i_text_length,
3943 p_sys->b_broken_charset );
3944 msg_Dbg( p_demux, " - short event lang=%3.3s '%s' : '%s'",
3945 pE->i_iso_639_code, psz_name, psz_text );
3952 dvbpsi_extended_event_dr_t *pE = dvbpsi_DecodeExtendedEventDr( p_dr );
3955 msg_Dbg( p_demux, " - extended event lang=%3.3s [%d/%d]",
3957 pE->i_descriptor_number, pE->i_last_descriptor_number );
3959 if( pE->i_text_length > 0 )
3961 char *psz_text = EITConvertToUTF8( p_demux,
3962 pE->i_text, pE->i_text_length,
3963 p_sys->b_broken_charset );
3966 msg_Dbg( p_demux, " - text='%s'", psz_text );
3968 psz_extra = xrealloc( psz_extra,
3969 strlen(psz_extra) + strlen(psz_text) + 1 );
3970 strcat( psz_extra, psz_text );
3975 for( int i = 0; i < pE->i_entry_count; i++ )
3977 char *psz_dsc = EITConvertToUTF8( p_demux,
3978 pE->i_item_description[i],
3979 pE->i_item_description_length[i],
3980 p_sys->b_broken_charset );
3981 char *psz_itm = EITConvertToUTF8( p_demux,
3982 pE->i_item[i], pE->i_item_length[i],
3983 p_sys->b_broken_charset );
3985 if( psz_dsc && psz_itm )
3987 msg_Dbg( p_demux, " - desc='%s' item='%s'", psz_dsc, psz_itm );
3989 psz_extra = xrealloc( psz_extra,
3990 strlen(psz_extra) + strlen(psz_dsc) +
3991 strlen(psz_itm) + 3 + 1 );
3992 strcat( psz_extra, "(" );
3993 strcat( psz_extra, psz_dsc );
3994 strcat( psz_extra, " " );
3995 strcat( psz_extra, psz_itm );
3996 strcat( psz_extra, ")" );
4008 dvbpsi_parental_rating_dr_t *pR = dvbpsi_DecodeParentalRatingDr( p_dr );
4011 for ( int i = 0; i < pR->i_ratings_number; i++ )
4013 const dvbpsi_parental_rating_t *p_rating = & pR->p_parental_rating[ i ];
4014 if ( p_rating->i_rating > 0x00 && p_rating->i_rating <= 0x0F )
4016 if ( p_rating->i_rating + 3 > i_min_age )
4017 i_min_age = p_rating->i_rating + 3;
4018 msg_Dbg( p_demux, " - parental control set to %d years",
4027 msg_Dbg( p_demux, " - event unknown dr 0x%x(%d)", p_dr->i_tag, p_dr->i_tag );
4033 if( i_start > 0 && psz_name && psz_text)
4034 vlc_epg_AddEvent( p_epg, i_start, i_duration, psz_name, psz_text,
4035 *psz_extra ? psz_extra : NULL, i_min_age );
4037 /* Update "now playing" field */
4038 if( p_evt->i_running_status == 0x04 && i_start > 0 && psz_name && psz_text )
4039 vlc_epg_SetCurrent( p_epg, i_start );
4046 if( p_epg->i_event > 0 )
4048 if( b_current_following &&
4049 ( p_sys->programs.i_size == 0 ||
4050 p_sys->programs.p_elems[0] ==
4054 p_sys->i_dvb_length = 0;
4055 p_sys->i_dvb_start = 0;
4057 if( p_epg->p_current )
4059 p_sys->i_dvb_start = CLOCK_FREQ * p_epg->p_current->i_start;
4060 p_sys->i_dvb_length = CLOCK_FREQ * p_epg->p_current->i_duration;
4063 es_out_Control( p_demux->out, ES_OUT_SET_GROUP_EPG,
4067 vlc_epg_Delete( p_epg );
4069 dvbpsi_eit_delete( p_eit );
4071 static void EITCallBackCurrentFollowing( demux_t *p_demux, dvbpsi_eit_t *p_eit )
4073 EITCallBack( p_demux, p_eit, true );
4075 static void EITCallBackSchedule( demux_t *p_demux, dvbpsi_eit_t *p_eit )
4077 EITCallBack( p_demux, p_eit, false );
4080 static void PSINewTableCallBack( dvbpsi_t *h, uint8_t i_table_id,
4081 uint16_t i_extension, demux_t *p_demux )
4083 demux_sys_t *p_sys = p_demux->p_sys;
4086 msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
4087 i_table_id, i_table_id, i_extension, i_extension );
4089 if( p_sys->pid[0].u.p_pat->i_version != -1 && i_table_id == 0x42 )
4091 msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
4092 i_table_id, i_table_id, i_extension, i_extension );
4094 if( !dvbpsi_sdt_attach( h, i_table_id, i_extension, (dvbpsi_sdt_callback)SDTCallBack, p_demux ) )
4095 msg_Err( p_demux, "PSINewTableCallback: failed attaching SDTCallback" );
4097 else if( p_sys->pid[0x11].u.p_psi->i_version != -1 &&
4098 ( i_table_id == 0x4e || /* Current/Following */
4099 (i_table_id >= 0x50 && i_table_id <= 0x5f) ) ) /* Schedule */
4101 msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
4102 i_table_id, i_table_id, i_extension, i_extension );
4104 dvbpsi_eit_callback cb = i_table_id == 0x4e ?
4105 (dvbpsi_eit_callback)EITCallBackCurrentFollowing :
4106 (dvbpsi_eit_callback)EITCallBackSchedule;
4108 if( !dvbpsi_eit_attach( h, i_table_id, i_extension, cb, p_demux ) )
4109 msg_Err( p_demux, "PSINewTableCallback: failed attaching EITCallback" );
4111 else if( p_demux->p_sys->pid[0x11].u.p_psi->i_version != -1 &&
4112 (i_table_id == 0x70 /* TDT */ || i_table_id == 0x73 /* TOT */) )
4114 msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
4115 i_table_id, i_table_id, i_extension, i_extension );
4117 if( !dvbpsi_tot_attach( h, i_table_id, i_extension, (dvbpsi_tot_callback)TDTCallBack, p_demux ) )
4118 msg_Err( p_demux, "PSINewTableCallback: failed attaching TDTCallback" );
4122 /*****************************************************************************
4123 * PMT callback and helpers
4124 *****************************************************************************/
4125 static dvbpsi_descriptor_t *PMTEsFindDescriptor( const dvbpsi_pmt_es_t *p_es,
4128 dvbpsi_descriptor_t *p_dr = p_es->p_first_descriptor;;
4129 while( p_dr && ( p_dr->i_tag != i_tag ) )
4130 p_dr = p_dr->p_next;
4133 static bool PMTEsHasRegistration( demux_t *p_demux,
4134 const dvbpsi_pmt_es_t *p_es,
4135 const char *psz_tag )
4137 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x05 );
4141 if( p_dr->i_length < 4 )
4143 msg_Warn( p_demux, "invalid Registration Descriptor" );
4147 assert( strlen(psz_tag) == 4 );
4148 return !memcmp( p_dr->p_data, psz_tag, 4 );
4151 static bool PMTEsHasComponentTag( const dvbpsi_pmt_es_t *p_es,
4152 int i_component_tag )
4154 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x52 );
4157 dvbpsi_stream_identifier_dr_t *p_si = dvbpsi_DecodeStreamIdentifierDr( p_dr );
4161 return p_si->i_component_tag == i_component_tag;
4164 static void PMTSetupEsISO14496( demux_t *p_demux, ts_pes_es_t *p_es,
4165 const ts_pmt_t *p_pmt, const dvbpsi_pmt_es_t *p_dvbpsies )
4167 es_format_t *p_fmt = &p_es->fmt;
4169 /* MPEG-4 stream: search FMC_DESCRIPTOR (SL Packetized stream) */
4170 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x1f );
4172 if( p_dr && p_dr->i_length == 2 )
4174 const int i_es_id = ( p_dr->p_data[0] << 8 ) | p_dr->p_data[1];
4176 msg_Dbg( p_demux, "found FMC_descriptor declaring sl packetization on es_id=%d", i_es_id );
4178 p_es->p_mpeg4desc = NULL;
4180 for( int i = 0; i < ES_DESCRIPTOR_COUNT; i++ )
4182 iod_descriptor_t *iod = p_pmt->iod;
4183 if( iod->es_descr[i].i_es_id == i_es_id )
4185 if ( iod->es_descr[i].b_ok )
4186 p_es->p_mpeg4desc = &iod->es_descr[i];
4188 msg_Dbg( p_demux, "MPEG-4 descriptor not yet available on es_id=%d", i_es_id );
4193 if( !p_es->p_mpeg4desc )
4195 switch( p_dvbpsies->i_type )
4197 /* non fatal, set by packetizer */
4198 case 0x0f: /* ADTS */
4199 case 0x11: /* LOAS */
4200 msg_Info( p_demux, "MPEG-4 descriptor not found for pid 0x%x type 0x%x",
4201 p_dvbpsies->i_pid, p_dvbpsies->i_type );
4204 msg_Err( p_demux, "MPEG-4 descriptor not found for pid 0x%x type 0x%x",
4205 p_dvbpsies->i_pid, p_dvbpsies->i_type );
4211 const decoder_config_descriptor_t *dcd = &p_es->p_mpeg4desc->dec_descr;
4212 if( dcd->i_streamType == 0x04 ) /* VisualStream */
4214 p_fmt->i_cat = VIDEO_ES;
4215 switch( dcd->i_objectTypeIndication )
4217 case 0x0B: /* mpeg4 sub */
4218 p_fmt->i_cat = SPU_ES;
4219 p_fmt->i_codec = VLC_CODEC_SUBT;
4222 case 0x20: /* mpeg4 */
4223 p_fmt->i_codec = VLC_CODEC_MP4V;
4225 case 0x21: /* h264 */
4226 p_fmt->i_codec = VLC_CODEC_H264;
4233 case 0x65: /* mpeg2 */
4234 p_fmt->i_codec = VLC_CODEC_MPGV;
4236 case 0x6a: /* mpeg1 */
4237 p_fmt->i_codec = VLC_CODEC_MPGV;
4239 case 0x6c: /* mpeg1 */
4240 p_fmt->i_codec = VLC_CODEC_JPEG;
4243 p_fmt->i_cat = UNKNOWN_ES;
4247 else if( dcd->i_streamType == 0x05 ) /* AudioStream */
4249 p_fmt->i_cat = AUDIO_ES;
4250 switch( dcd->i_objectTypeIndication )
4252 case 0x40: /* mpeg4 */
4253 p_fmt->i_codec = VLC_CODEC_MP4A;
4257 case 0x68: /* mpeg2 aac */
4258 p_fmt->i_codec = VLC_CODEC_MP4A;
4260 case 0x69: /* mpeg2 */
4261 p_fmt->i_codec = VLC_CODEC_MPGA;
4263 case 0x6b: /* mpeg1 */
4264 p_fmt->i_codec = VLC_CODEC_MPGA;
4267 p_fmt->i_cat = UNKNOWN_ES;
4273 p_fmt->i_cat = UNKNOWN_ES;
4276 if( p_fmt->i_cat != UNKNOWN_ES )
4278 p_fmt->i_extra = __MIN(dcd->i_extra, INT32_MAX);
4279 if( p_fmt->i_extra > 0 )
4281 p_fmt->p_extra = malloc( p_fmt->i_extra );
4282 if( p_fmt->p_extra )
4283 memcpy( p_fmt->p_extra, dcd->p_extra, p_fmt->i_extra );
4296 } ts_teletext_page_t;
4298 static void PMTSetupEsTeletext( demux_t *p_demux, ts_pes_t *p_pes,
4299 const dvbpsi_pmt_es_t *p_dvbpsies )
4301 es_format_t *p_fmt = &p_pes->es.fmt;
4303 ts_teletext_page_t p_page[2 * 64 + 20];
4304 unsigned i_page = 0;
4306 /* Gather pages information */
4307 for( unsigned i_tag_idx = 0; i_tag_idx < 2; i_tag_idx++ )
4309 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, i_tag_idx == 0 ? 0x46 : 0x56 );
4313 dvbpsi_teletext_dr_t *p_sub = dvbpsi_DecodeTeletextDr( p_dr );
4317 for( int i = 0; i < p_sub->i_pages_number; i++ )
4319 const dvbpsi_teletextpage_t *p_src = &p_sub->p_pages[i];
4321 if( p_src->i_teletext_type >= 0x06 )
4324 assert( i_page < sizeof(p_page)/sizeof(*p_page) );
4326 ts_teletext_page_t *p_dst = &p_page[i_page++];
4328 p_dst->i_type = p_src->i_teletext_type;
4329 p_dst->i_magazine = p_src->i_teletext_magazine_number
4330 ? p_src->i_teletext_magazine_number : 8;
4331 p_dst->i_page = p_src->i_teletext_page_number;
4332 memcpy( p_dst->p_iso639, p_src->i_iso6392_language_code, 3 );
4336 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x59 );
4339 dvbpsi_subtitling_dr_t *p_sub = dvbpsi_DecodeSubtitlingDr( p_dr );
4340 for( int i = 0; p_sub && i < p_sub->i_subtitles_number; i++ )
4342 dvbpsi_subtitle_t *p_src = &p_sub->p_subtitle[i];
4344 if( p_src->i_subtitling_type < 0x01 || p_src->i_subtitling_type > 0x03 )
4347 assert( i_page < sizeof(p_page)/sizeof(*p_page) );
4349 ts_teletext_page_t *p_dst = &p_page[i_page++];
4351 switch( p_src->i_subtitling_type )
4354 p_dst->i_type = 0x02;
4357 p_dst->i_type = 0x03;
4360 /* FIXME check if it is the right split */
4361 p_dst->i_magazine = (p_src->i_composition_page_id >> 8)
4362 ? (p_src->i_composition_page_id >> 8) : 8;
4363 p_dst->i_page = p_src->i_composition_page_id & 0xff;
4364 memcpy( p_dst->p_iso639, p_src->i_iso6392_language_code, 3 );
4369 es_format_Init( p_fmt, SPU_ES, VLC_CODEC_TELETEXT );
4371 if( !p_demux->p_sys->b_split_es || i_page <= 0 )
4373 p_fmt->subs.teletext.i_magazine = -1;
4374 p_fmt->subs.teletext.i_page = 0;
4375 p_fmt->psz_description = strdup( vlc_gettext(ppsz_teletext_type[1]) );
4377 dvbpsi_descriptor_t *p_dr;
4378 p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x46 );
4380 p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x56 );
4382 if( !p_demux->p_sys->b_split_es && p_dr && p_dr->i_length > 0 )
4384 /* Descriptor pass-through */
4385 p_fmt->p_extra = malloc( p_dr->i_length );
4386 if( p_fmt->p_extra )
4388 p_fmt->i_extra = p_dr->i_length;
4389 memcpy( p_fmt->p_extra, p_dr->p_data, p_dr->i_length );
4395 for( unsigned i = 0; i < i_page; i++ )
4397 ts_pes_es_t *p_page_es;
4402 p_page_es = &p_pes->es;
4406 p_page_es = calloc( 1, sizeof(*p_page_es) );
4410 es_format_Copy( &p_page_es->fmt, p_fmt );
4411 free( p_page_es->fmt.psz_language );
4412 free( p_page_es->fmt.psz_description );
4413 p_page_es->fmt.psz_language = NULL;
4414 p_page_es->fmt.psz_description = NULL;
4416 ARRAY_APPEND( p_pes->extra_es, p_page_es );
4420 const ts_teletext_page_t *p = &p_page[i];
4421 p_page_es->fmt.i_priority = (p->i_type == 0x02 || p->i_type == 0x05) ?
4422 ES_PRIORITY_SELECTABLE_MIN : ES_PRIORITY_NOT_DEFAULTABLE;
4423 p_page_es->fmt.psz_language = strndup( p->p_iso639, 3 );
4424 p_page_es->fmt.psz_description = strdup(vlc_gettext(ppsz_teletext_type[p->i_type]));
4425 p_page_es->fmt.subs.teletext.i_magazine = p->i_magazine;
4426 p_page_es->fmt.subs.teletext.i_page = p->i_page;
4429 " * ttxt type=%s lan=%s page=%d%02x",
4430 p_page_es->fmt.psz_description,
4431 p_page_es->fmt.psz_language,
4432 p->i_magazine, p->i_page );
4436 static void PMTSetupEsDvbSubtitle( demux_t *p_demux, ts_pes_t *p_pes,
4437 const dvbpsi_pmt_es_t *p_dvbpsies )
4439 es_format_t *p_fmt = &p_pes->es.fmt;
4441 es_format_Init( p_fmt, SPU_ES, VLC_CODEC_DVBS );
4443 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x59 );
4445 dvbpsi_subtitling_dr_t *p_sub = dvbpsi_DecodeSubtitlingDr( p_dr );
4446 for( int i = 0; p_sub && i < p_sub->i_subtitles_number; i++ )
4448 const int i_type = p_sub->p_subtitle[i].i_subtitling_type;
4449 if( ( i_type >= 0x10 && i_type <= 0x14 ) ||
4450 ( i_type >= 0x20 && i_type <= 0x24 ) )
4454 if( !p_demux->p_sys->b_split_es || i_page <= 0 )
4456 p_fmt->subs.dvb.i_id = -1;
4457 p_fmt->psz_description = strdup( _("DVB subtitles") );
4459 if( !p_demux->p_sys->b_split_es && p_dr && p_dr->i_length > 0 )
4461 /* Descriptor pass-through */
4462 p_fmt->p_extra = malloc( p_dr->i_length );
4463 if( p_fmt->p_extra )
4465 p_fmt->i_extra = p_dr->i_length;
4466 memcpy( p_fmt->p_extra, p_dr->p_data, p_dr->i_length );
4472 for( int i = 0; i < p_sub->i_subtitles_number; i++ )
4474 ts_pes_es_t *p_subs_es;
4479 p_subs_es = &p_pes->es;
4483 p_subs_es = malloc( sizeof(*p_subs_es) );
4487 es_format_Copy( &p_subs_es->fmt, p_fmt );
4488 free( p_subs_es->fmt.psz_language );
4489 free( p_subs_es->fmt.psz_description );
4490 p_subs_es->fmt.psz_language = NULL;
4491 p_subs_es->fmt.psz_description = NULL;
4493 ARRAY_APPEND( p_pes->extra_es, p_subs_es );
4497 const dvbpsi_subtitle_t *p = &p_sub->p_subtitle[i];
4498 p_subs_es->fmt.psz_language = strndup( (char *)p->i_iso6392_language_code, 3 );
4499 switch( p->i_subtitling_type )
4501 case 0x10: /* unspec. */
4502 case 0x11: /* 4:3 */
4503 case 0x12: /* 16:9 */
4504 case 0x13: /* 2.21:1 */
4505 case 0x14: /* HD monitor */
4506 p_subs_es->fmt.psz_description = strdup( _("DVB subtitles") );
4508 case 0x20: /* Hearing impaired unspec. */
4509 case 0x21: /* h.i. 4:3 */
4510 case 0x22: /* h.i. 16:9 */
4511 case 0x23: /* h.i. 2.21:1 */
4512 case 0x24: /* h.i. HD monitor */
4513 p_subs_es->fmt.psz_description = strdup( _("DVB subtitles: hearing impaired") );
4520 p_subs_es->fmt.subs.dvb.i_id = ( p->i_composition_page_id << 0 ) |
4521 ( p->i_ancillary_page_id << 16 );
4526 static int vlc_ceil_log2( const unsigned int val )
4528 int n = 31 - clz(val);
4529 if ((1U << n) != val)
4535 static void OpusSetup(demux_t *demux, uint8_t *p, size_t len, es_format_t *p_fmt)
4539 /* default mapping */
4540 static const unsigned char map[8] = { 0, 1, 2, 3, 4, 5, 6, 7 };
4541 memcpy(h.stream_map, map, sizeof(map));
4545 int stream_count = 0;
4546 int ccc = p[1]; // channel_config_code
4550 mapping = channels > 2;
4553 channels = 2; // dual mono
4555 static const uint8_t p_csc[8] = { 0, 1, 1, 2, 2, 2, 3, 3 };
4556 csc = p_csc[channels - 1];
4557 stream_count = channels - csc;
4559 static const uint8_t map[6][7] = {
4568 memcpy(&h.stream_map[1], map[channels-3], channels - 1);
4569 } else if (ccc == 0x81) {
4571 goto explicit_config_too_short;
4578 bs_init(&s, &p[4], len - 4);
4581 int bits = vlc_ceil_log2(channels);
4582 if (s.i_left < bits)
4583 goto explicit_config_too_short;
4584 stream_count = bs_read(&s, bits) + 1;
4585 bits = vlc_ceil_log2(stream_count + 1);
4586 if (s.i_left < bits)
4587 goto explicit_config_too_short;
4588 csc = bs_read(&s, bits);
4590 int channel_bits = vlc_ceil_log2(stream_count + csc + 1);
4591 if (s.i_left < channels * channel_bits)
4592 goto explicit_config_too_short;
4594 unsigned char silence = (1U << (stream_count + csc + 1)) - 1;
4595 for (int i = 0; i < channels; i++) {
4596 unsigned char m = bs_read(&s, channel_bits);
4599 h.stream_map[i] = m;
4602 } else if (ccc >= 0x80 && ccc <= 0x88) {
4603 channels = ccc - 0x80;
4608 channels = 2; // dual mono
4611 stream_count = channels;
4613 msg_Err(demux, "Opus channel configuration 0x%.2x is reserved", ccc);
4617 msg_Err(demux, "Opus channel configuration 0x%.2x not supported yet", p[1]);
4621 opus_prepare_header(channels, 0, &h);
4623 h.input_sample_rate = 48000;
4625 h.nb_streams = channels - csc;
4626 h.channel_mapping = mapping;
4629 opus_write_header((uint8_t**)&p_fmt->p_extra, &p_fmt->i_extra, &h, NULL /* FIXME */);
4630 if (p_fmt->p_extra) {
4631 p_fmt->i_cat = AUDIO_ES;
4632 p_fmt->i_codec = VLC_CODEC_OPUS;
4633 p_fmt->audio.i_channels = h.channels;
4634 p_fmt->audio.i_rate = 48000;
4640 explicit_config_too_short:
4641 msg_Err(demux, "Opus descriptor too short");
4644 static void PMTSetupEs0x06( demux_t *p_demux, ts_pes_t *p_pes,
4645 const dvbpsi_pmt_es_t *p_dvbpsies )
4647 es_format_t *p_fmt = &p_pes->es.fmt;
4648 dvbpsi_descriptor_t *p_subs_dr = PMTEsFindDescriptor( p_dvbpsies, 0x59 );
4649 dvbpsi_descriptor_t *desc;
4651 if( PMTEsHasRegistration( p_demux, p_dvbpsies, "AC-3" ) ||
4652 PMTEsFindDescriptor( p_dvbpsies, 0x6a ) ||
4653 PMTEsFindDescriptor( p_dvbpsies, 0x81 ) )
4655 p_fmt->i_cat = AUDIO_ES;
4656 p_fmt->i_codec = VLC_CODEC_A52;
4658 else if( (desc = PMTEsFindDescriptor( p_dvbpsies, 0x7f ) ) && desc->i_length >= 2 &&
4659 PMTEsHasRegistration(p_demux, p_dvbpsies, "Opus"))
4661 OpusSetup(p_demux, desc->p_data, desc->i_length, p_fmt);
4663 else if( PMTEsFindDescriptor( p_dvbpsies, 0x7a ) )
4665 /* DVB with stream_type 0x06 (ETS EN 300 468) */
4666 p_fmt->i_cat = AUDIO_ES;
4667 p_fmt->i_codec = VLC_CODEC_EAC3;
4669 else if( PMTEsHasRegistration( p_demux, p_dvbpsies, "DTS1" ) ||
4670 PMTEsHasRegistration( p_demux, p_dvbpsies, "DTS2" ) ||
4671 PMTEsHasRegistration( p_demux, p_dvbpsies, "DTS3" ) ||
4672 PMTEsFindDescriptor( p_dvbpsies, 0x73 ) )
4674 /*registration descriptor(ETSI TS 101 154 Annex F)*/
4675 p_fmt->i_cat = AUDIO_ES;
4676 p_fmt->i_codec = VLC_CODEC_DTS;
4678 else if( PMTEsHasRegistration( p_demux, p_dvbpsies, "BSSD" ) && !p_subs_dr )
4680 /* BSSD is AES3 DATA, but could also be subtitles
4681 * we need to check for secondary descriptor then s*/
4682 p_fmt->i_cat = AUDIO_ES;
4683 p_fmt->b_packetized = true;
4684 p_fmt->i_codec = VLC_CODEC_302M;
4686 else if( PMTEsHasRegistration( p_demux, p_dvbpsies, "HEVC" ) )
4688 p_fmt->i_cat = VIDEO_ES;
4689 p_fmt->i_codec = VLC_CODEC_HEVC;
4691 else if ( p_demux->p_sys->arib.e_mode == ARIBMODE_ENABLED )
4693 /* Lookup our data component descriptor first ARIB STD B10 6.4 */
4694 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0xFD );
4695 /* and check that it maps to something ARIB STD B14 Table 5.1/5.2 */
4696 if ( p_dr && p_dr->i_length >= 2 )
4698 if( !memcmp( p_dr->p_data, "\x00\x08", 2 ) && (
4699 PMTEsHasComponentTag( p_dvbpsies, 0x30 ) ||
4700 PMTEsHasComponentTag( p_dvbpsies, 0x31 ) ||
4701 PMTEsHasComponentTag( p_dvbpsies, 0x32 ) ||
4702 PMTEsHasComponentTag( p_dvbpsies, 0x33 ) ||
4703 PMTEsHasComponentTag( p_dvbpsies, 0x34 ) ||
4704 PMTEsHasComponentTag( p_dvbpsies, 0x35 ) ||
4705 PMTEsHasComponentTag( p_dvbpsies, 0x36 ) ||
4706 PMTEsHasComponentTag( p_dvbpsies, 0x37 ) ) )
4708 es_format_Init( p_fmt, SPU_ES, VLC_CODEC_ARIB_A );
4709 p_fmt->psz_language = strndup ( "jpn", 3 );
4710 p_fmt->psz_description = strdup( _("ARIB subtitles") );
4712 else if( !memcmp( p_dr->p_data, "\x00\x12", 2 ) && (
4713 PMTEsHasComponentTag( p_dvbpsies, 0x87 ) ||
4714 PMTEsHasComponentTag( p_dvbpsies, 0x88 ) ) )
4716 es_format_Init( p_fmt, SPU_ES, VLC_CODEC_ARIB_C );
4717 p_fmt->psz_language = strndup ( "jpn", 3 );
4718 p_fmt->psz_description = strdup( _("ARIB subtitles") );
4724 /* Subtitle/Teletext/VBI fallbacks */
4725 dvbpsi_subtitling_dr_t *p_sub;
4726 if( p_subs_dr && ( p_sub = dvbpsi_DecodeSubtitlingDr( p_subs_dr ) ) )
4728 for( int i = 0; i < p_sub->i_subtitles_number; i++ )
4730 if( p_fmt->i_cat != UNKNOWN_ES )
4733 switch( p_sub->p_subtitle[i].i_subtitling_type )
4735 case 0x01: /* EBU Teletext subtitles */
4736 case 0x02: /* Associated EBU Teletext */
4737 case 0x03: /* VBI data */
4738 PMTSetupEsTeletext( p_demux, p_pes, p_dvbpsies );
4740 case 0x10: /* DVB Subtitle (normal) with no monitor AR critical */
4741 case 0x11: /* ... on 4:3 AR monitor */
4742 case 0x12: /* ... on 16:9 AR monitor */
4743 case 0x13: /* ... on 2.21:1 AR monitor */
4744 case 0x14: /* ... for display on a high definition monitor */
4745 case 0x20: /* DVB Subtitle (impaired) with no monitor AR critical */
4746 case 0x21: /* ... on 4:3 AR monitor */
4747 case 0x22: /* ... on 16:9 AR monitor */
4748 case 0x23: /* ... on 2.21:1 AR monitor */
4749 case 0x24: /* ... for display on a high definition monitor */
4750 PMTSetupEsDvbSubtitle( p_demux, p_pes, p_dvbpsies );
4753 msg_Err( p_demux, "Unrecognized DVB subtitle type (0x%x)",
4754 p_sub->p_subtitle[i].i_subtitling_type );
4760 if( p_fmt->i_cat == UNKNOWN_ES &&
4761 ( PMTEsFindDescriptor( p_dvbpsies, 0x45 ) || /* VBI Data descriptor */
4762 PMTEsFindDescriptor( p_dvbpsies, 0x46 ) || /* VBI Teletext descriptor */
4763 PMTEsFindDescriptor( p_dvbpsies, 0x56 ) ) ) /* EBU Teletext descriptor */
4766 PMTSetupEsTeletext( p_demux, p_pes, p_dvbpsies );
4770 /* FIXME is it useful ? */
4771 if( PMTEsFindDescriptor( p_dvbpsies, 0x52 ) )
4773 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x52 );
4774 dvbpsi_stream_identifier_dr_t *p_si = dvbpsi_DecodeStreamIdentifierDr( p_dr );
4776 msg_Dbg( p_demux, " * Stream Component Identifier: %d", p_si->i_component_tag );
4780 static void PMTSetupEs0xEA( demux_t *p_demux, ts_pes_es_t *p_es,
4781 const dvbpsi_pmt_es_t *p_dvbpsies )
4783 /* Registration Descriptor */
4784 if( !PMTEsHasRegistration( p_demux, p_dvbpsies, "VC-1" ) )
4786 msg_Err( p_demux, "Registration descriptor not found or invalid" );
4790 es_format_t *p_fmt = &p_es->fmt;
4792 /* registration descriptor for VC-1 (SMPTE rp227) */
4793 p_fmt->i_cat = VIDEO_ES;
4794 p_fmt->i_codec = VLC_CODEC_VC1;
4796 /* XXX With Simple and Main profile the SEQUENCE
4797 * header is modified: video width and height are
4798 * inserted just after the start code as 2 int16_t
4799 * The packetizer will take care of that. */
4802 static void PMTSetupEs0xD1( demux_t *p_demux, ts_pes_es_t *p_es,
4803 const dvbpsi_pmt_es_t *p_dvbpsies )
4805 /* Registration Descriptor */
4806 if( !PMTEsHasRegistration( p_demux, p_dvbpsies, "drac" ) )
4808 msg_Err( p_demux, "Registration descriptor not found or invalid" );
4812 es_format_t *p_fmt = &p_es->fmt;
4814 /* registration descriptor for Dirac
4815 * (backwards compatable with VC-2 (SMPTE Sxxxx:2008)) */
4816 p_fmt->i_cat = VIDEO_ES;
4817 p_fmt->i_codec = VLC_CODEC_DIRAC;
4820 static void PMTSetupEs0xA0( demux_t *p_demux, ts_pes_es_t *p_es,
4821 const dvbpsi_pmt_es_t *p_dvbpsies )
4823 /* MSCODEC sent by vlc */
4824 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0xa0 );
4825 if( !p_dr || p_dr->i_length < 10 )
4828 "private MSCODEC (vlc) without bih private descriptor" );
4832 es_format_t *p_fmt = &p_es->fmt;
4833 p_fmt->i_cat = VIDEO_ES;
4834 p_fmt->i_codec = VLC_FOURCC( p_dr->p_data[0], p_dr->p_data[1],
4835 p_dr->p_data[2], p_dr->p_data[3] );
4836 p_fmt->video.i_width = GetWBE( &p_dr->p_data[4] );
4837 p_fmt->video.i_height = GetWBE( &p_dr->p_data[6] );
4838 p_fmt->i_extra = GetWBE( &p_dr->p_data[8] );
4840 if( p_fmt->i_extra > 0 )
4842 p_fmt->p_extra = malloc( p_fmt->i_extra );
4843 if( p_fmt->p_extra )
4844 memcpy( p_fmt->p_extra, &p_dr->p_data[10],
4845 __MIN( p_fmt->i_extra, p_dr->i_length - 10 ) );
4849 /* For such stream we will gather them ourself and don't launch a
4851 * Yes it's ugly but it's the only way to have DIV3 working */
4852 p_fmt->b_packetized = true;
4855 static void PMTSetupEs0x83( const dvbpsi_pmt_t *p_pmt, ts_pes_es_t *p_es, int i_pid )
4857 /* WiDi broadcasts without registration on PMT 0x1, PCR 0x1000 and
4858 * with audio track pid being 0x1100..0x11FF */
4859 if ( p_pmt->i_program_number == 0x1 &&
4860 p_pmt->i_pcr_pid == 0x1000 &&
4861 ( i_pid >> 8 ) == 0x11 )
4863 /* Not enough ? might contain 0x83 private descriptor, 2 bytes 0x473F */
4864 es_format_Init( &p_es->fmt, AUDIO_ES, VLC_CODEC_WIDI_LPCM );
4867 es_format_Init( &p_es->fmt, AUDIO_ES, VLC_CODEC_DVD_LPCM );
4870 static bool PMTSetupEsHDMV( demux_t *p_demux, ts_pes_es_t *p_es,
4871 const dvbpsi_pmt_es_t *p_dvbpsies )
4873 es_format_t *p_fmt = &p_es->fmt;
4875 /* Blu-Ray mapping */
4876 switch( p_dvbpsies->i_type )
4879 p_fmt->i_cat = AUDIO_ES;
4880 p_fmt->i_codec = VLC_CODEC_BD_LPCM;
4883 p_fmt->i_cat = AUDIO_ES;
4884 p_fmt->i_codec = VLC_CODEC_A52;
4887 case 0x85: /* DTS-HD High resolution audio */
4888 case 0x86: /* DTS-HD Master audio */
4889 case 0xA2: /* Secondary DTS audio */
4890 p_fmt->i_cat = AUDIO_ES;
4891 p_fmt->i_codec = VLC_CODEC_DTS;
4894 case 0x83: /* TrueHD AC3 */
4895 p_fmt->i_cat = AUDIO_ES;
4896 p_fmt->i_codec = VLC_CODEC_TRUEHD;
4899 case 0x84: /* E-AC3 */
4900 case 0xA1: /* Secondary E-AC3 */
4901 p_fmt->i_cat = AUDIO_ES;
4902 p_fmt->i_codec = VLC_CODEC_EAC3;
4904 case 0x90: /* Presentation graphics */
4905 p_fmt->i_cat = SPU_ES;
4906 p_fmt->i_codec = VLC_CODEC_BD_PG;
4908 case 0x91: /* Interactive graphics */
4909 case 0x92: /* Subtitle */
4912 p_fmt->i_cat = VIDEO_ES;
4913 p_fmt->i_codec = VLC_CODEC_VC1;
4916 msg_Info( p_demux, "HDMV registration not implemented for pid 0x%x type 0x%x",
4917 p_dvbpsies->i_pid, p_dvbpsies->i_type );
4924 static bool PMTSetupEsRegistration( demux_t *p_demux, ts_pes_es_t *p_es,
4925 const dvbpsi_pmt_es_t *p_dvbpsies )
4931 vlc_fourcc_t i_codec;
4933 { "AC-3", AUDIO_ES, VLC_CODEC_A52 },
4934 { "DTS1", AUDIO_ES, VLC_CODEC_DTS },
4935 { "DTS2", AUDIO_ES, VLC_CODEC_DTS },
4936 { "DTS3", AUDIO_ES, VLC_CODEC_DTS },
4937 { "BSSD", AUDIO_ES, VLC_CODEC_302M },
4938 { "VC-1", VIDEO_ES, VLC_CODEC_VC1 },
4939 { "drac", VIDEO_ES, VLC_CODEC_DIRAC },
4940 { "", UNKNOWN_ES, 0 }
4942 es_format_t *p_fmt = &p_es->fmt;
4944 for( int i = 0; p_regs[i].i_cat != UNKNOWN_ES; i++ )
4946 if( PMTEsHasRegistration( p_demux, p_dvbpsies, p_regs[i].psz_tag ) )
4948 p_fmt->i_cat = p_regs[i].i_cat;
4949 p_fmt->i_codec = p_regs[i].i_codec;
4950 if (p_dvbpsies->i_type == 0x87)
4951 p_fmt->i_codec = VLC_CODEC_EAC3;
4958 static char *GetAudioTypeDesc(demux_t *p_demux, int type)
4960 static const char *audio_type[] = {
4962 N_("clean effects"),
4963 N_("hearing impaired"),
4964 N_("visual impaired commentary"),
4967 if (type < 0 || type > 3)
4968 msg_Dbg( p_demux, "unknown audio type: %d", type);
4970 return strdup(audio_type[type]);
4974 static void PMTParseEsIso639( demux_t *p_demux, ts_pes_es_t *p_es,
4975 const dvbpsi_pmt_es_t *p_dvbpsies )
4977 /* get language descriptor */
4978 dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x0a );
4983 dvbpsi_iso639_dr_t *p_decoded = dvbpsi_DecodeISO639Dr( p_dr );
4986 msg_Err( p_demux, "Failed to decode a ISO 639 descriptor" );
4990 #if defined(DR_0A_API_VER) && (DR_0A_API_VER >= 2)
4991 p_es->fmt.psz_language = malloc( 4 );
4992 if( p_es->fmt.psz_language )
4994 memcpy( p_es->fmt.psz_language, p_decoded->code[0].iso_639_code, 3 );
4995 p_es->fmt.psz_language[3] = 0;
4996 msg_Dbg( p_demux, "found language: %s", p_es->fmt.psz_language);
4998 int type = p_decoded->code[0].i_audio_type;
4999 p_es->fmt.psz_description = GetAudioTypeDesc(p_demux, type);
5001 p_es->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN + 1; // prioritize normal audio tracks
5003 p_es->fmt.i_extra_languages = p_decoded->i_code_count-1;
5004 if( p_es->fmt.i_extra_languages > 0 )
5005 p_es->fmt.p_extra_languages =
5006 malloc( sizeof(*p_es->fmt.p_extra_languages) *
5007 p_es->fmt.i_extra_languages );
5008 if( p_es->fmt.p_extra_languages )
5010 for( unsigned i = 0; i < p_es->fmt.i_extra_languages; i++ )
5012 p_es->fmt.p_extra_languages[i].psz_language = malloc(4);
5013 if( p_es->fmt.p_extra_languages[i].psz_language )
5015 memcpy( p_es->fmt.p_extra_languages[i].psz_language,
5016 p_decoded->code[i+1].iso_639_code, 3 );
5017 p_es->fmt.p_extra_languages[i].psz_language[3] = '\0';
5019 int type = p_decoded->code[i].i_audio_type;
5020 p_es->fmt.p_extra_languages[i].psz_description = GetAudioTypeDesc(p_demux, type);
5024 p_es->fmt.psz_language = malloc( 4 );
5025 if( p_es->fmt.psz_language )
5027 memcpy( p_es->fmt.psz_language,
5028 p_decoded->i_iso_639_code, 3 );
5029 p_es->fmt.psz_language[3] = 0;
5034 static inline void SetExtraESGroupAndID( demux_sys_t *p_sys, es_format_t *p_fmt,
5035 const es_format_t *p_parent_fmt )
5037 if ( p_sys->b_es_id_pid ) /* pid is 13 bits */
5038 p_fmt->i_id = (p_sys->i_next_extraid++ << 13) | p_parent_fmt->i_id;
5039 p_fmt->i_group = p_parent_fmt->i_group;
5042 static void AddAndCreateES( demux_t *p_demux, ts_pid_t *pid, bool b_create_delayed )
5044 demux_sys_t *p_sys = p_demux->p_sys;
5046 if( b_create_delayed )
5047 p_sys->es_creation = CREATE_ES;
5049 if( pid && p_sys->es_creation == CREATE_ES )
5051 /* FIXME: other owners / shared pid */
5052 pid->u.p_pes->es.id = es_out_Add( p_demux->out, &pid->u.p_pes->es.fmt );
5053 for( int i = 0; i < pid->u.p_pes->extra_es.i_size; i++ )
5055 es_format_t *p_fmt = &pid->u.p_pes->extra_es.p_elems[i]->fmt;
5056 SetExtraESGroupAndID( p_sys, p_fmt, &pid->u.p_pes->es.fmt );
5057 pid->u.p_pes->extra_es.p_elems[i]->id = es_out_Add( p_demux->out, p_fmt );
5059 p_sys->i_pmt_es += 1 + pid->u.p_pes->extra_es.i_size;
5061 /* Update the default program == first created ES group */
5062 if( p_sys->b_default_selection )
5064 p_sys->b_default_selection = false;
5065 assert(p_sys->programs.i_size == 1);
5066 if( p_sys->programs.p_elems[0] != pid->p_parent->u.p_pmt->i_number )
5067 p_sys->programs.p_elems[0] = pid->p_parent->u.p_pmt->i_number;
5068 msg_Dbg( p_demux, "Default program is %d", pid->p_parent->u.p_pmt->i_number );
5072 if( b_create_delayed )
5074 ts_pat_t *p_pat = p_sys->pid[0].u.p_pat;
5075 for( int i=0; i< p_pat->programs.i_size; i++ )
5077 ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
5078 for( int j=0; j<p_pmt->e_streams.i_size; j++ )
5080 ts_pid_t *pid = p_pmt->e_streams.p_elems[j];
5081 if( pid->u.p_pes->es.id )
5084 pid->u.p_pes->es.id = es_out_Add( p_demux->out, &pid->u.p_pes->es.fmt );
5085 for( int k = 0; k < pid->u.p_pes->extra_es.i_size; k++ )
5087 es_format_t *p_fmt = &pid->u.p_pes->extra_es.p_elems[k]->fmt;
5088 SetExtraESGroupAndID( p_sys, p_fmt, &pid->u.p_pes->es.fmt );
5089 pid->u.p_pes->extra_es.p_elems[k]->id = es_out_Add( p_demux->out, p_fmt );
5091 p_sys->i_pmt_es += 1 + pid->u.p_pes->extra_es.i_size;
5096 UpdatePESFilters( p_demux, p_sys->b_es_all );
5099 static void PMTCallBack( void *data, dvbpsi_pmt_t *p_dvbpsipmt )
5101 demux_t *p_demux = data;
5102 demux_sys_t *p_sys = p_demux->p_sys;
5104 ts_pid_t *pmtpid = NULL;
5105 ts_pmt_t *p_pmt = NULL;
5107 msg_Dbg( p_demux, "PMTCallBack called" );
5109 if (unlikely(p_sys->pid[0].type != TYPE_PAT))
5111 assert(p_sys->pid[0].type == TYPE_PAT);
5112 dvbpsi_pmt_delete(p_dvbpsipmt);
5115 const ts_pat_t *p_pat = p_sys->pid[0].u.p_pat;
5117 /* First find this PMT declared in PAT */
5118 for( int i = 0; !pmtpid && i < p_pat->programs.i_size; i++ )
5120 const int i_pmt_prgnumber = p_pat->programs.p_elems[i]->u.p_pmt->i_number;
5121 if( i_pmt_prgnumber != TS_USER_PMT_NUMBER &&
5122 i_pmt_prgnumber == p_dvbpsipmt->i_program_number )
5124 pmtpid = p_pat->programs.p_elems[i];
5125 assert(pmtpid->type == TYPE_PMT);
5126 p_pmt = pmtpid->u.p_pmt;
5130 if( pmtpid == NULL )
5132 msg_Warn( p_demux, "unreferenced program (broken stream)" );
5133 dvbpsi_pmt_delete(p_dvbpsipmt);
5137 pmtpid->i_flags |= FLAG_SEEN;
5139 if( p_pmt->i_version != -1 &&
5140 ( !p_dvbpsipmt->b_current_next || p_pmt->i_version == p_dvbpsipmt->i_version ) )
5142 dvbpsi_pmt_delete( p_dvbpsipmt );
5146 /* Save old es array */
5147 DECL_ARRAY(ts_pid_t *) old_es_rm;
5148 old_es_rm.i_alloc = p_pmt->e_streams.i_alloc;
5149 old_es_rm.i_size = p_pmt->e_streams.i_size;
5150 old_es_rm.p_elems = p_pmt->e_streams.p_elems;
5151 ARRAY_INIT(p_pmt->e_streams);
5155 IODFree( p_pmt->iod );
5159 msg_Dbg( p_demux, "new PMT program number=%d version=%d pid_pcr=%d",
5160 p_dvbpsipmt->i_program_number, p_dvbpsipmt->i_version, p_dvbpsipmt->i_pcr_pid );
5161 p_pmt->i_pid_pcr = p_dvbpsipmt->i_pcr_pid;
5162 p_pmt->i_version = p_dvbpsipmt->i_version;
5164 ValidateDVBMeta( p_demux, p_pmt->i_pid_pcr );
5166 if( ProgramIsSelected( p_sys, p_pmt->i_number ) )
5167 SetPIDFilter( p_sys, &p_sys->pid[p_pmt->i_pid_pcr], true ); /* Set demux filter */
5169 /* Parse PMT descriptors */
5170 ts_pmt_registration_type_t registration_type = TS_PMT_REGISTRATION_NONE;
5171 dvbpsi_descriptor_t *p_dr;
5173 /* First pass for standard detection */
5174 if ( p_sys->arib.e_mode == ARIBMODE_AUTO )
5176 int i_arib_flags = 0; /* Descriptors can be repeated */
5177 for( p_dr = p_dvbpsipmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
5183 dvbpsi_ca_dr_t *p_cadr = dvbpsi_DecodeCADr( p_dr );
5184 i_arib_flags |= (p_cadr->i_ca_system_id == 0x05);
5188 i_arib_flags |= 1 << 1;
5191 i_arib_flags |= 1 << 2;
5197 if ( i_arib_flags == 0x07 ) //0b111
5198 p_sys->arib.e_mode = ARIBMODE_ENABLED;
5201 for( p_dr = p_dvbpsipmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
5203 /* special descriptors handling */
5206 case 0x1d: /* We have found an IOD descriptor */
5207 msg_Dbg( p_demux, " * PMT descriptor : IOD (0x1d)" );
5208 p_pmt->iod = IODNew( p_dr->i_length, p_dr->p_data );
5212 msg_Dbg( p_demux, " * PMT descriptor : CA (0x9) SysID 0x%x",
5213 (p_dr->p_data[0] << 8) | p_dr->p_data[1] );
5216 case 0x5: /* Registration Descriptor */
5217 if( p_dr->i_length != 4 )
5219 msg_Warn( p_demux, " * PMT invalid Registration Descriptor" );
5223 msg_Dbg( p_demux, " * PMT descriptor : registration %4.4s", p_dr->p_data );
5224 if( !memcmp( p_dr->p_data, "HDMV", 4 ) || !memcmp( p_dr->p_data, "HDPR", 4 ) )
5225 registration_type = TS_PMT_REGISTRATION_HDMV; /* Blu-Ray */
5230 msg_Dbg( p_demux, " * PMT descriptor : Private Data (0x0f)" );
5234 msg_Dbg( p_demux, " * PMT descriptor : Digital copy control (0xC1)" );
5237 case 0x88: /* EACEM Simulcast HD Logical channels ordering */
5238 msg_Dbg( p_demux, " * descriptor : EACEM Simulcast HD" );
5239 /* TODO: apply visibility flags */
5243 msg_Dbg( p_demux, " * PMT descriptor : unknown (0x%x)", p_dr->i_tag );
5247 dvbpsi_pmt_es_t *p_dvbpsies;
5248 for( p_dvbpsies = p_dvbpsipmt->p_first_es; p_dvbpsies != NULL; p_dvbpsies = p_dvbpsies->p_next )
5250 bool b_reusing_pid = false;
5253 ts_pid_t *pespid = &p_sys->pid[p_dvbpsies->i_pid];
5254 if ( pespid->type == TYPE_PES && pespid->p_parent->u.p_pmt->i_number != p_pmt->i_number )
5256 msg_Warn( p_demux, " * PMT wants to get a share or pid %d (unsupported)", pespid->i_pid );
5260 /* Find out if the PID was already declared */
5261 for( int i = 0; i < old_es_rm.i_size; i++ )
5263 if( old_es_rm.p_elems[i]->i_pid == p_dvbpsies->i_pid )
5265 b_reusing_pid = true;
5269 ValidateDVBMeta( p_demux, p_dvbpsies->i_pid );
5271 char const * psz_typedesc = "";
5272 switch(p_dvbpsies->i_type)
5275 psz_typedesc = "ISO/IEC Reserved";
5278 psz_typedesc = "ISO/IEC 11172 Video";
5281 psz_typedesc = "ISO/IEC 13818-2 Video or ISO/IEC 11172-2 constrained parameter video stream";
5284 psz_typedesc = "ISO/IEC 11172 Audio";
5287 psz_typedesc = "ISO/IEC 13818-3 Audio";
5290 psz_typedesc = "ISO/IEC 13818-1 private_sections";
5293 psz_typedesc = "ISO/IEC 13818-1 PES packets containing private data";
5296 psz_typedesc = "ISO/IEC 13522 MHEG";
5299 psz_typedesc = "ISO/IEC 13818-1 Annex A DSM CC";
5302 psz_typedesc = "ITU-T Rec. H.222.1";
5305 psz_typedesc = "ISO/IEC 13818-6 type A";
5308 psz_typedesc = "ISO/IEC 13818-6 type B";
5311 psz_typedesc = "ISO/IEC 13818-6 type C";
5314 psz_typedesc = "ISO/IEC 13818-6 type D";
5317 psz_typedesc = "ISO/IEC 13818-1 auxiliary";
5320 if (p_dvbpsies->i_type >= 0x0F && p_dvbpsies->i_type <=0x7F)
5321 psz_typedesc = "ISO/IEC 13818-1 Reserved";
5323 psz_typedesc = "User Private";
5326 msg_Dbg( p_demux, " * pid=%d type=0x%x %s",
5327 p_dvbpsies->i_pid, p_dvbpsies->i_type, psz_typedesc );
5329 for( p_dr = p_dvbpsies->p_first_descriptor; p_dr != NULL;
5330 p_dr = p_dr->p_next )
5332 msg_Dbg( p_demux, " - descriptor tag 0x%x",
5336 if ( !PIDSetup( p_demux, TYPE_PES, pespid, pmtpid ) )
5338 msg_Warn( p_demux, " * pid=%d type=0x%x %s (skipped)",
5339 p_dvbpsies->i_pid, p_dvbpsies->i_type, psz_typedesc );
5346 p_pes = ts_pes_New( p_demux );
5352 p_pes = pespid->u.p_pes;
5356 ARRAY_APPEND( p_pmt->e_streams, pespid );
5358 PIDFillFormat( &p_pes->es.fmt, p_dvbpsies->i_type );
5360 pespid->i_flags |= SEEN(p_sys->pid[p_dvbpsies->i_pid]);
5362 bool b_registration_applied = false;
5363 if ( p_dvbpsies->i_type >= 0x80 ) /* non standard, extensions */
5365 if ( registration_type == TS_PMT_REGISTRATION_HDMV )
5367 if (( b_registration_applied = PMTSetupEsHDMV( p_demux, &p_pes->es, p_dvbpsies ) ))
5368 msg_Dbg( p_demux, " + HDMV registration applied to pid %d type 0x%x",
5369 p_dvbpsies->i_pid, p_dvbpsies->i_type );
5373 if (( b_registration_applied = PMTSetupEsRegistration( p_demux, &p_pes->es, p_dvbpsies ) ))
5374 msg_Dbg( p_demux, " + registration applied to pid %d type 0x%x",
5375 p_dvbpsies->i_pid, p_dvbpsies->i_type );
5379 if ( !b_registration_applied )
5381 switch( p_dvbpsies->i_type )
5384 /* Handle PES private data */
5385 PMTSetupEs0x06( p_demux, p_pes, p_dvbpsies );
5387 /* All other private or reserved types */
5392 PMTSetupEsISO14496( p_demux, &p_pes->es, p_pmt, p_dvbpsies );
5396 PMTSetupEs0x83( p_dvbpsipmt, &p_pes->es, p_dvbpsies->i_pid );
5399 PMTSetupEs0xA0( p_demux, &p_pes->es, p_dvbpsies );
5402 PMTSetupEs0xD1( p_demux, &p_pes->es, p_dvbpsies );
5405 PMTSetupEs0xEA( p_demux, &p_pes->es, p_dvbpsies );
5411 if( p_pes->es.fmt.i_cat == AUDIO_ES ||
5412 ( p_pes->es.fmt.i_cat == SPU_ES &&
5413 p_pes->es.fmt.i_codec != VLC_CODEC_DVBS &&
5414 p_pes->es.fmt.i_codec != VLC_CODEC_TELETEXT ) )
5416 PMTParseEsIso639( p_demux, &p_pes->es, p_dvbpsies );
5419 switch( p_pes->es.fmt.i_codec )
5421 case VLC_CODEC_SCTE_27:
5422 p_pes->data_type = TS_ES_DATA_TABLE_SECTION;
5425 //pid->es->data_type = TS_ES_DATA_PES;
5429 /* Set Groups / ID */
5430 p_pes->es.fmt.i_group = p_dvbpsipmt->i_program_number;
5431 if( p_sys->b_es_id_pid )
5432 p_pes->es.fmt.i_id = p_dvbpsies->i_pid;
5434 if( p_pes->es.fmt.i_cat == UNKNOWN_ES )
5436 msg_Dbg( p_demux, " => pid %d content is *unknown*",
5437 p_dvbpsies->i_pid );
5438 p_pes->es.fmt.psz_description = strdup( psz_typedesc );
5442 msg_Dbg( p_demux, " => pid %d has now es fcc=%4.4s",
5443 p_dvbpsies->i_pid, (char*)&p_pes->es.fmt.i_codec );
5445 /* Check if we can avoid restarting the ES */
5448 /* p_pes points to a tmp pes */
5449 if( pespid->u.p_pes->es.fmt.i_codec != p_pes->es.fmt.i_codec ||
5450 pespid->u.p_pes->es.fmt.i_extra != p_pes->es.fmt.i_extra ||
5451 pespid->u.p_pes->es.fmt.i_extra != 0 ||
5452 pespid->u.p_pes->extra_es.i_size != p_pes->extra_es.i_size ||
5453 !( ( !pespid->u.p_pes->es.fmt.psz_language &&
5454 !p_pes->es.fmt.psz_language ) ||
5455 ( pespid->u.p_pes->es.fmt.psz_language &&
5456 p_pes->es.fmt.psz_language &&
5457 !strcmp( pespid->u.p_pes->es.fmt.psz_language,
5458 p_pes->es.fmt.psz_language ) ) ) )
5460 /* Differs, swap then */
5461 ts_pes_t *e = pespid->u.p_pes;
5462 pespid->u.p_pes = p_pes;
5465 /* p_pes still tmp, but now contains old config */
5466 pespid->u.p_pes->es.id = p_pes->es.id;
5467 if( pespid->u.p_pes->es.id )
5469 p_pes->es.id = NULL;
5470 es_out_Control( p_demux->out, ES_OUT_SET_ES_FMT,
5471 pespid->u.p_pes->es.id, pespid->u.p_pes->es.fmt );
5474 for( int i=0; i<pespid->u.p_pes->extra_es.i_size &&
5475 i<p_pes->extra_es.i_size; i++ )
5477 pespid->u.p_pes->extra_es.p_elems[i]->id = p_pes->extra_es.p_elems[i]->id;
5478 if( pespid->u.p_pes->extra_es.p_elems[i]->id )
5480 es_out_Control( p_demux->out, ES_OUT_SET_ES_FMT,
5481 pespid->u.p_pes->extra_es.p_elems[i]->id,
5482 pespid->u.p_pes->extra_es.p_elems[i]->fmt );
5483 p_pes->extra_es.p_elems[i]->id = NULL;
5488 ts_pes_Del( p_demux, p_pes ); // delete temp
5492 AddAndCreateES( p_demux, pespid, false );
5496 p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x09 );
5497 if( p_dr && p_dr->i_length >= 2 )
5499 msg_Dbg( p_demux, " * PMT descriptor : CA (0x9) SysID 0x%x",
5500 (p_dr->p_data[0] << 8) | p_dr->p_data[1] );
5504 /* Set CAM descrambling */
5505 if( !ProgramIsSelected( p_sys, p_pmt->i_number ) )
5507 dvbpsi_pmt_delete( p_dvbpsipmt );
5509 else if( stream_Control( p_sys->stream, STREAM_SET_PRIVATE_ID_CA,
5510 p_dvbpsipmt ) != VLC_SUCCESS )
5512 if ( p_sys->arib.e_mode == ARIBMODE_ENABLED && !p_sys->arib.b25stream )
5514 p_sys->arib.b25stream = stream_FilterNew( p_demux->s, "aribcam" );
5515 p_sys->stream = ( p_sys->arib.b25stream ) ? p_sys->arib.b25stream : p_demux->s;
5516 if (!p_sys->arib.b25stream)
5517 dvbpsi_pmt_delete( p_dvbpsipmt );
5518 } else dvbpsi_pmt_delete( p_dvbpsipmt );
5521 /* Decref or clean now unused es */
5522 for( int i = 0; i < old_es_rm.i_size; i++ )
5523 PIDRelease( p_demux, old_es_rm.p_elems[i] );
5524 ARRAY_RESET( old_es_rm );
5526 UpdatePESFilters( p_demux, p_sys->b_es_all );
5528 if( !p_sys->b_trust_pcr )
5530 int i_cand = FindPCRCandidate( p_pmt );
5531 p_pmt->i_pid_pcr = i_cand;
5532 p_pmt->pcr.b_disable = true;
5533 msg_Warn( p_demux, "PCR not trusted for program %d, set up workaround using pid %d",
5534 p_pmt->i_number, i_cand );
5537 /* Probe Boundaries */
5538 if( p_sys->b_canfastseek && p_pmt->i_last_dts == -1 )
5540 p_pmt->i_last_dts = 0;
5541 ProbeStart( p_demux, p_pmt->i_number );
5542 ProbeEnd( p_demux, p_pmt->i_number );
5546 static int PATCheck( demux_t *p_demux, dvbpsi_pat_t *p_pat )
5548 /* Some Dreambox streams have all PMT set to same pid */
5549 int i_prev_pid = -1;
5550 for( dvbpsi_pat_program_t * p_program = p_pat->p_first_program;
5552 p_program = p_program->p_next )
5554 if( p_program->i_pid == i_prev_pid )
5556 msg_Warn( p_demux, "PAT check failed: duplicate program pid %d", i_prev_pid );
5557 return VLC_EGENERIC;
5559 i_prev_pid = p_program->i_pid;
5564 static void PATCallBack( void *data, dvbpsi_pat_t *p_dvbpsipat )
5566 demux_t *p_demux = data;
5567 demux_sys_t *p_sys = p_demux->p_sys;
5568 dvbpsi_pat_program_t *p_program;
5569 ts_pid_t *patpid = &p_sys->pid[0];
5570 ts_pat_t *p_pat = p_sys->pid[0].u.p_pat;
5572 patpid->i_flags |= FLAG_SEEN;
5574 msg_Dbg( p_demux, "PATCallBack called" );
5576 if(unlikely( p_sys->pid[0].type != TYPE_PAT ))
5578 msg_Warn( p_demux, "PATCallBack called on invalid pid" );
5582 if( ( p_pat->i_version != -1 &&
5583 ( !p_dvbpsipat->b_current_next ||
5584 p_dvbpsipat->i_version == p_pat->i_version ) ) ||
5585 ( p_pat->i_ts_id != -1 && p_dvbpsipat->i_ts_id != p_pat->i_ts_id ) ||
5586 p_sys->b_user_pmt || PATCheck( p_demux, p_dvbpsipat ) )
5588 dvbpsi_pat_delete( p_dvbpsipat );
5592 msg_Dbg( p_demux, "new PAT ts_id=%d version=%d current_next=%d",
5593 p_dvbpsipat->i_ts_id, p_dvbpsipat->i_version, p_dvbpsipat->b_current_next );
5595 /* Save old programs array */
5596 DECL_ARRAY(ts_pid_t *) old_pmt_rm;
5597 old_pmt_rm.i_alloc = p_pat->programs.i_alloc;
5598 old_pmt_rm.i_size = p_pat->programs.i_size;
5599 old_pmt_rm.p_elems = p_pat->programs.p_elems;
5600 ARRAY_INIT(p_pat->programs);
5602 /* now create programs */
5603 for( p_program = p_dvbpsipat->p_first_program; p_program != NULL;
5604 p_program = p_program->p_next )
5606 msg_Dbg( p_demux, " * number=%d pid=%d", p_program->i_number,
5608 if( p_program->i_number == 0 )
5611 ts_pid_t *pmtpid = &p_sys->pid[p_program->i_pid];
5613 ValidateDVBMeta( p_demux, p_program->i_pid );
5615 /* create or temporary incref pid */
5616 if( !PIDSetup( p_demux, TYPE_PMT, pmtpid, patpid ) )
5618 msg_Warn( p_demux, " * number=%d pid=%d (ignored)", p_program->i_number,
5623 pmtpid->u.p_pmt->i_number = p_program->i_number;
5625 if( !dvbpsi_pmt_attach( pmtpid->u.p_pmt->handle, p_program->i_number, PMTCallBack, p_demux ) )
5626 msg_Err( p_demux, "PATCallback failed attaching PMTCallback to program %d",
5627 p_program->i_number );
5629 ARRAY_APPEND( p_pat->programs, pmtpid );
5631 /* Now select PID at access level */
5632 if( p_sys->programs.i_size == 0 ||
5633 ProgramIsSelected( p_sys, p_program->i_number ) )
5635 if( p_sys->programs.i_size == 0 )
5637 msg_Dbg( p_demux, "temporary receiving program %d", p_program->i_number );
5638 p_sys->b_default_selection = true;
5639 ARRAY_APPEND( p_sys->programs, p_program->i_number );
5642 if( SetPIDFilter( p_sys, pmtpid, true ) )
5643 p_sys->b_access_control = false;
5644 else if ( p_sys->es_creation == DELAY_ES )
5645 p_sys->es_creation = CREATE_ES;
5648 p_pat->i_version = p_dvbpsipat->i_version;
5649 p_pat->i_ts_id = p_dvbpsipat->i_ts_id;
5651 for(int i=0; i<old_pmt_rm.i_size; i++)
5653 /* decref current or release now unreferenced */
5654 PIDRelease( p_demux, old_pmt_rm.p_elems[i] );
5656 ARRAY_RESET(old_pmt_rm);
5658 dvbpsi_pat_delete( p_dvbpsipat );
5661 static inline bool handle_Init( demux_t *p_demux, dvbpsi_t **handle )
5663 *handle = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG );
5666 (*handle)->p_sys = (void *) p_demux;
5670 static ts_pat_t *ts_pat_New( demux_t *p_demux )
5672 ts_pat_t *pat = malloc( sizeof( ts_pat_t ) );
5676 if( !handle_Init( p_demux, &pat->handle ) )
5682 pat->i_version = -1;
5684 ARRAY_INIT( pat->programs );
5689 static void ts_pat_Del( demux_t *p_demux, ts_pat_t *pat )
5691 if( dvbpsi_decoder_present( pat->handle ) )
5692 dvbpsi_pat_detach( pat->handle );
5693 dvbpsi_delete( pat->handle );
5694 for( int i=0; i<pat->programs.i_size; i++ )
5695 PIDRelease( p_demux, pat->programs.p_elems[i] );
5696 ARRAY_RESET( pat->programs );
5700 static ts_pmt_t *ts_pmt_New( demux_t *p_demux )
5702 ts_pmt_t *pmt = malloc( sizeof( ts_pmt_t ) );
5706 if( !handle_Init( p_demux, &pmt->handle ) )
5712 ARRAY_INIT( pmt->e_streams );
5714 pmt->i_version = -1;
5716 pmt->i_pid_pcr = 0x1FFF;
5719 pmt->i_last_dts = -1;
5721 pmt->pcr.i_current = -1;
5722 pmt->pcr.i_first = -1;
5723 pmt->pcr.b_disable = false;
5724 pmt->pcr.i_first_dts = VLC_TS_INVALID;
5725 pmt->pcr.i_pcroffset = -1;
5727 pmt->pcr.b_fix_done = false;
5732 static void ts_pmt_Del( demux_t *p_demux, ts_pmt_t *pmt )
5734 if( dvbpsi_decoder_present( pmt->handle ) )
5735 dvbpsi_pmt_detach( pmt->handle );
5736 dvbpsi_delete( pmt->handle );
5737 for( int i=0; i<pmt->e_streams.i_size; i++ )
5738 PIDRelease( p_demux, pmt->e_streams.p_elems[i] );
5739 ARRAY_RESET( pmt->e_streams );
5741 IODFree( pmt->iod );
5742 if( pmt->i_number > -1 )
5743 es_out_Control( p_demux->out, ES_OUT_DEL_GROUP, pmt->i_number );
5747 static ts_pes_t *ts_pes_New( demux_t *p_demux )
5749 VLC_UNUSED(p_demux);
5750 ts_pes_t *pes = malloc( sizeof( ts_pes_t ) );
5755 pes->es.p_mpeg4desc = NULL;
5756 es_format_Init( &pes->es.fmt, UNKNOWN_ES, 0 );
5757 ARRAY_INIT( pes->extra_es );
5758 pes->data_type = TS_ES_DATA_PES;
5759 pes->i_data_size = 0;
5760 pes->i_data_gathered = 0;
5762 pes->pp_last = &pes->p_data;
5763 pes->p_prepcr_outqueue = NULL;
5768 static void ts_pes_Del( demux_t *p_demux, ts_pes_t *pes )
5772 es_out_Del( p_demux->out, pes->es.id );
5773 p_demux->p_sys->i_pmt_es--;
5777 block_ChainRelease( pes->p_data );
5779 if( pes->p_prepcr_outqueue )
5780 block_ChainRelease( pes->p_prepcr_outqueue );
5782 es_format_Clean( &pes->es.fmt );
5783 free( pes->es.p_mpeg4desc );
5785 for( int i = 0; i < pes->extra_es.i_size; i++ )
5787 if( pes->extra_es.p_elems[i]->id )
5789 es_out_Del( p_demux->out, pes->extra_es.p_elems[i]->id );
5790 p_demux->p_sys->i_pmt_es--;
5792 es_format_Clean( &pes->extra_es.p_elems[i]->fmt );
5793 free( pes->extra_es.p_elems[i] );
5795 ARRAY_RESET( pes->extra_es );
5800 static ts_psi_t *ts_psi_New( demux_t *p_demux )
5802 ts_psi_t *psi = malloc( sizeof( ts_psi_t ) );
5806 if( !handle_Init( p_demux, &psi->handle ) )
5812 psi->i_version = -1;
5817 static void ts_psi_Del( demux_t *p_demux, ts_psi_t *psi )
5819 VLC_UNUSED(p_demux);
5820 if( dvbpsi_decoder_present( psi->handle ) )
5821 dvbpsi_DetachDemux( psi->handle );
5822 dvbpsi_delete( psi->handle );