1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
pub mod pat;
pub mod pmt;
use packet;
use hexdump;
use mpegts_crc;
pub trait SectionProcessor {
type Context;
fn start_section<'a>(&mut self, ctx: &mut Self::Context, header: &SectionCommonHeader, section_data: &'a[u8]);
fn continue_section<'a>(&mut self, ctx: &mut Self::Context, section_data: &'a[u8]);
fn reset(&mut self);
}
#[derive(Debug,PartialEq)]
pub enum CurrentNext {
Current,
Next,
}
impl CurrentNext {
fn from(v: u8) -> CurrentNext {
match v {
0 => CurrentNext::Next,
1 => CurrentNext::Current,
_ => panic!("invalid current_next_indicator value {}", v),
}
}
}
#[derive(Debug)]
pub struct TableSyntaxHeader<'buf> {
buf: &'buf[u8],
}
impl<'buf> TableSyntaxHeader<'buf> {
pub const SIZE: usize = 5;
pub fn new(buf: &'buf[u8]) -> TableSyntaxHeader {
assert!(buf.len() >= Self::SIZE);
TableSyntaxHeader {
buf
}
}
pub fn id(&self) -> u16 {
u16::from(self.buf[0]) << 8 | u16::from(self.buf[1])
}
pub fn version(&self) -> u8 {
(self.buf[2] >> 1) & 0b0001_1111
}
pub fn current_next_indicator(&self) -> CurrentNext {
CurrentNext::from(self.buf[2] & 1)
}
pub fn section_number(&self) -> u8 {
self.buf[3]
}
pub fn last_section_number(&self) -> u8 {
self.buf[4]
}
}
pub struct CrcCheckWholeSectionSyntaxPayloadParser<P>
where
P: WholeSectionSyntaxPayloadParser
{
inner: P,
}
impl<P> CrcCheckWholeSectionSyntaxPayloadParser<P>
where
P: WholeSectionSyntaxPayloadParser
{
pub fn new(inner: P) -> CrcCheckWholeSectionSyntaxPayloadParser<P> {
CrcCheckWholeSectionSyntaxPayloadParser {
inner,
}
}
}
impl<P> WholeSectionSyntaxPayloadParser for CrcCheckWholeSectionSyntaxPayloadParser<P>
where
P: WholeSectionSyntaxPayloadParser
{
type Context = P::Context;
fn section<'a>(&mut self, ctx: &mut Self::Context, header: &SectionCommonHeader, table_syntax_header: &TableSyntaxHeader, data: &'a [u8]) {
assert!(header.section_syntax_indicator);
if !cfg!(fuzz) && mpegts_crc::sum32(data) != 0 {
println!(
"section crc check failed for table_id {}",
header.table_id,
);
hexdump::hexdump(data);
return;
}
self.inner.section(ctx, header, table_syntax_header, data);
}
}
pub trait WholeSectionSyntaxPayloadParser {
type Context;
fn section<'a>(&mut self, &mut Self::Context, header: &SectionCommonHeader, table_syntax_header: &TableSyntaxHeader, data: &'a [u8]);
}
enum BufferSectionState {
Buffering(usize),
Complete,
}
pub struct BufferSectionSyntaxParser<P>
where
P: WholeSectionSyntaxPayloadParser
{
buf: Vec<u8>,
state: BufferSectionState,
parser: P,
}
impl<P> BufferSectionSyntaxParser<P>
where
P: WholeSectionSyntaxPayloadParser
{
pub fn new(parser: P) -> BufferSectionSyntaxParser<P> {
BufferSectionSyntaxParser {
buf: vec!(),
state: BufferSectionState::Complete,
parser,
}
}
}
impl<P> SectionSyntaxPayloadParser for BufferSectionSyntaxParser<P>
where
P: WholeSectionSyntaxPayloadParser
{
type Context = P::Context;
fn start_syntax_section<'a>(&mut self, ctx: &mut Self::Context, header: &SectionCommonHeader, table_syntax_header: &TableSyntaxHeader, data: &'a [u8]) {
let section_length_with_header = header.section_length + SectionCommonHeader::SIZE;
if section_length_with_header <= data.len() {
self.state = BufferSectionState::Complete;
self.parser.section(ctx, header, table_syntax_header, &data[..section_length_with_header])
} else {
self.buf.clear();
self.buf.extend_from_slice(data);
let to_read = section_length_with_header - data.len();
self.state = BufferSectionState::Buffering(to_read);
}
}
fn continue_syntax_section<'a>(&mut self, ctx: &mut Self::Context, data: &'a [u8]) {
match self.state {
BufferSectionState::Complete => {
println!("attempt to add extra data when section already complete");
},
BufferSectionState::Buffering(remaining) => {
let new_remaining = if data.len() > remaining {
0
} else {
remaining - data.len()
};
if new_remaining == 0 {
self.buf.extend_from_slice(&data[..remaining]);
self.state = BufferSectionState::Complete;
let header = SectionCommonHeader::new(&self.buf[..SectionCommonHeader::SIZE]);
let table_syntax_header = TableSyntaxHeader::new(&self.buf[SectionCommonHeader::SIZE..]);
self.parser.section(ctx, &header, &table_syntax_header, &self.buf[..]);
} else {
self.buf.extend_from_slice(data);
self.state = BufferSectionState::Buffering(new_remaining);
}
}
}
}
fn reset(&mut self) {
self.buf.clear();
self.state = BufferSectionState::Complete;
}
}
pub struct DedupSectionSyntaxPayloadParser<SSPP>
where
SSPP: SectionSyntaxPayloadParser
{
inner: SSPP,
last_version: Option<u8>,
ignore_rest: bool,
}
impl<SSPP> DedupSectionSyntaxPayloadParser<SSPP>
where
SSPP: SectionSyntaxPayloadParser
{
pub fn new(inner: SSPP) -> DedupSectionSyntaxPayloadParser<SSPP> {
DedupSectionSyntaxPayloadParser {
inner,
last_version: None,
ignore_rest: false,
}
}
}
impl<SSPP> SectionSyntaxPayloadParser for DedupSectionSyntaxPayloadParser<SSPP>
where
SSPP: SectionSyntaxPayloadParser
{
type Context = SSPP::Context;
fn start_syntax_section<'a>(&mut self, ctx: &mut Self::Context, header: &SectionCommonHeader, table_syntax_header: &TableSyntaxHeader, data: &'a [u8]) {
if let Some(last) = self.last_version {
if last == table_syntax_header.version() {
self.ignore_rest = true;
return;
}
}
self.ignore_rest = false;
self.last_version = Some(table_syntax_header.version());
self.inner.start_syntax_section(ctx, header, table_syntax_header, data);
}
fn continue_syntax_section<'a>(&mut self, ctx: &mut Self::Context, data: &'a [u8]) {
if !self.ignore_rest {
self.inner.continue_syntax_section(ctx, data)
}
}
fn reset(&mut self) {
self.inner.reset();
self.last_version = None;
self.ignore_rest = false;
}
}
pub trait SectionSyntaxPayloadParser {
type Context;
fn start_syntax_section<'a>(&mut self,
ctx: &mut Self::Context,
header: &SectionCommonHeader,
table_syntax_header: &TableSyntaxHeader, data: &'a [u8]);
fn continue_syntax_section<'a>(&mut self, ctx: &mut Self::Context, data: &'a [u8]);
fn reset(&mut self);
}
pub struct SectionSyntaxSectionProcessor<SP>
where
SP: SectionSyntaxPayloadParser
{
payload_parser: SP,
ignore_rest: bool,
}
impl<SP> SectionSyntaxSectionProcessor<SP>
where
SP: SectionSyntaxPayloadParser
{
const SECTION_LIMIT: usize = 1021;
pub fn new(payload_parser: SP) -> SectionSyntaxSectionProcessor<SP> {
SectionSyntaxSectionProcessor {
payload_parser,
ignore_rest: false,
}
}
}
impl<SP> SectionProcessor for SectionSyntaxSectionProcessor<SP>
where
SP: SectionSyntaxPayloadParser
{
type Context = SP::Context;
fn start_section<'a>(&mut self, ctx: &mut Self::Context, header: &SectionCommonHeader, data: &'a [u8]) {
if !header.section_syntax_indicator {
println!(
"SectionSyntaxSectionProcessor requires that section_syntax_indicator be set in the section header"
);
self.ignore_rest = true;
return;
}
if data.len() < SectionCommonHeader::SIZE + TableSyntaxHeader::SIZE {
println!("SectionSyntaxSectionProcessor data {} too short for header {} (TODO: implement buffering)", data.len(), SectionCommonHeader::SIZE + TableSyntaxHeader::SIZE);
self.ignore_rest = true;
return;
}
if header.section_length > Self::SECTION_LIMIT {
println!("SectionSyntaxSectionProcessor section_length={} is too large (limit {})", header.section_length, Self::SECTION_LIMIT);
self.ignore_rest = true;
return;
}
self.ignore_rest = false;
let table_syntax_header = TableSyntaxHeader::new(&data[SectionCommonHeader::SIZE..]);
self.payload_parser.start_syntax_section(ctx, header, &table_syntax_header, data)
}
fn continue_section<'a>(&mut self, ctx: &mut Self::Context, data: &'a [u8]) {
if !self.ignore_rest {
self.payload_parser.continue_syntax_section(ctx, data)
}
}
fn reset(&mut self) {
self.payload_parser.reset()
}
}
#[derive(Debug)]
pub struct SectionCommonHeader {
pub table_id: u8,
pub section_syntax_indicator: bool,
pub private_indicator: bool,
pub section_length: usize,
}
impl SectionCommonHeader {
pub const SIZE: usize = 3;
pub fn new(buf: &[u8]) -> SectionCommonHeader {
assert_eq!(buf.len(), Self::SIZE);
SectionCommonHeader {
table_id: buf[0],
section_syntax_indicator: buf[1] & 0b1000_0000 != 0,
private_indicator: buf[1] & 0b0100_0000 != 0,
section_length: ((u16::from(buf[1] & 0b0000_1111) << 8) | u16::from(buf[2])) as usize,
}
}
}
pub struct SectionPacketConsumer<P>
where
P: SectionProcessor,
{
parser: P,
}
impl<P, Ctx> SectionPacketConsumer<P>
where
P: SectionProcessor<Context=Ctx>,
{
pub fn new(parser: P) -> SectionPacketConsumer<P> {
SectionPacketConsumer {
parser,
}
}
pub fn consume(&mut self, ctx: &mut Ctx, pk: &packet::Packet) {
match pk.payload() {
Some(pk_buf) => {
if pk.payload_unit_start_indicator() {
let pointer = pk_buf[0] as usize;
let section_data = &pk_buf[1..];
if pointer > 0 {
if pointer >= section_data.len() {
println!("PSI pointer beyond end of packet payload");
self.parser.reset();
return;
}
let remainder = §ion_data[..pointer];
self.parser.continue_section(ctx, remainder);
}
let next_sect = §ion_data[pointer..];
if next_sect.len() < SectionCommonHeader::SIZE {
println!("TODO: not enough bytes to read section header - implement buffering");
self.parser.reset();
return;
}
let header = SectionCommonHeader::new(&next_sect[..SectionCommonHeader::SIZE]);
self.parser.start_section(ctx, &header, next_sect);
} else {
self.parser.continue_section(ctx, pk_buf);
}
}
None => {
println!("no payload present in PSI packet");
}
}
}
}
#[cfg(test)]
mod test {
use super::*;
use packet::Packet;
use demultiplex;
use std::rc::Rc;
use std::cell::RefCell;
packet_filter_switch!{
NullFilterSwitch<NullDemuxContext> {
Pat: demultiplex::PatPacketFilter<NullDemuxContext>,
Pmt: demultiplex::PmtPacketFilter<NullDemuxContext>,
Nul: demultiplex::NullPacketFilter<NullDemuxContext>,
}
}
demux_context!(NullDemuxContext, NullStreamConstructor);
pub struct NullStreamConstructor;
impl demultiplex::StreamConstructor for NullStreamConstructor {
type F = NullFilterSwitch;
fn construct(&mut self, req: demultiplex::FilterRequest) -> Self::F {
match req {
demultiplex::FilterRequest::ByPid(0) => NullFilterSwitch::Pat(demultiplex::PatPacketFilter::default()),
demultiplex::FilterRequest::ByPid(_) => NullFilterSwitch::Nul(demultiplex::NullPacketFilter::default()),
demultiplex::FilterRequest::ByStream(_stype, _pmt_section, _stream_info) => NullFilterSwitch::Nul(demultiplex::NullPacketFilter::default()),
demultiplex::FilterRequest::Pmt{pid, program_number} => NullFilterSwitch::Pmt(demultiplex::PmtPacketFilter::new(pid, program_number)),
demultiplex::FilterRequest::Nit{..} => NullFilterSwitch::Nul(demultiplex::NullPacketFilter::default()),
}
}
}
struct NullSectionProcessor;
impl SectionProcessor for NullSectionProcessor {
type Context = NullDemuxContext;
fn start_section<'a>(&mut self, _ctx: &mut Self::Context, _header: &SectionCommonHeader, _section_data: &'a [u8]) { }
fn continue_section<'a>(&mut self, _ctx: &mut Self::Context, _section_data: &'a [u8]) { }
fn reset(&mut self) { }
}
#[test]
fn continuation_outside_section() {
let mut buf = [0u8; 188];
buf[0] = 0x47;
buf[3] |= 0b00010000; let pk = Packet::new(&buf[..]);
let mut psi_buf = SectionPacketConsumer::new(NullSectionProcessor);
let mut ctx = NullDemuxContext::new(NullStreamConstructor);
psi_buf.consume(&mut ctx, &pk);
}
#[test]
fn small_section() {
let mut buf = [0u8; 188];
buf[0] = 0x47;
buf[1] |= 0b01000000; buf[3] |= 0b00010000; buf[7] = 3; let pk = Packet::new(&buf[..]);
let mut psi_buf = SectionPacketConsumer::new(NullSectionProcessor);
let mut ctx = NullDemuxContext::new(NullStreamConstructor);
psi_buf.consume(&mut ctx, &pk);
}
#[test]
fn section_spanning_packets() {
let state = Rc::new(RefCell::new(false));
struct MockSectParse {
state: Rc<RefCell<bool>>,
};
impl WholeSectionSyntaxPayloadParser for MockSectParse {
type Context = ();
fn section<'a>(&mut self, _: &mut Self::Context, _header: &SectionCommonHeader, _table_syntax_header: &TableSyntaxHeader, _data: &[u8]) {
*self.state.borrow_mut() = true;
}
}
let mut p = BufferSectionSyntaxParser::new(CrcCheckWholeSectionSyntaxPayloadParser::new(MockSectParse { state: state.clone() }));
let ctx = &mut ();
{
let sect = hex!("
42f13040 84e90000 233aff44 40ff8026
480d1900 0a424243 2054574f 20484473
0c66702e 6262632e 636f2e75 6b5f0400
00233a7e 01f744c4 ff802148 09190006
49545620 4844730b 7777772e 6974762e
636f6d5f 04000023 3a7e01f7 4500ff80
2c480f19 000c4368 616e6e65 6c203420
48447310 7777772e 6368616e 6e656c34
2e636f6d 5f040000 233a7e01 f74484ff
8026480d 19000a42 4243204f 4e452048
44730c66 702e6262 632e636f 2e756b5f
04000023 3a7e01");
let common_header = SectionCommonHeader::new(§[..SectionCommonHeader::SIZE]);
let table_header = TableSyntaxHeader::new(§[SectionCommonHeader::SIZE..]);
p.start_syntax_section(ctx, &common_header, &table_header, §[..]);
}
{
let sect = hex!("
f746c0ff 8023480a 19000743 42424320
4844730c 66702e62 62632e63 6f2e756b
5f040000 233a7e01 f74f80ff 801e480a
16000746 696c6d34 2b317310 7777772e
6368616e 6e656c34 2e636f6d 4540ff80
27480f19 000c4368 616e6e65 6c203520
4844730b 7777772e 66697665 2e74765f
04000023 3a7e01f7 f28b26c4 ffffffff
ffffffff ffffffff ffffffff ffffffff
ffffffff ffffffff ffffffff ffffffff
ffffffff ffffffff ffffffff ffffffff
ffffffff ffffffff");
p.continue_syntax_section(ctx, §[..]);
}
assert!(*state.borrow());
}
}