Skip to main content

iter_packets/
iter_packets.rs

1//! Walk a TS file using the `iter_packets` helper, printing typed field accessors.
2//!
3//! Demonstrates the [`ScramblingControl`] and [`AdaptationFieldControl`] typed enums
4//! and the `iter_packets` bulk-walk helper introduced in `mpeg-ts` 0.2.0.
5//!
6//! Run with:
7//!   cargo run -p mpeg-ts --example iter_packets
8//!   cargo run -p mpeg-ts --example iter_packets -- path/to/stream.ts
9
10use std::collections::HashMap;
11use std::env;
12use std::fs;
13
14use mpeg_ts::ts::{iter_packets, ScramblingControl};
15
16fn main() {
17    let path = env::args()
18        .nth(1)
19        .unwrap_or_else(|| "mpeg-ts/tests/fixtures/m6-single.ts".to_string());
20
21    let buf = fs::read(&path).unwrap_or_else(|e| {
22        eprintln!("error: cannot read {path}: {e}");
23        std::process::exit(1);
24    });
25
26    let mut total = 0u64;
27    let mut scrambled = 0u64;
28    let mut pid_counts: HashMap<u16, u64> = HashMap::new();
29
30    for pkt in iter_packets(&buf) {
31        total += 1;
32        let hdr = &pkt.header;
33        *pid_counts.entry(hdr.pid).or_insert(0) += 1;
34
35        let sc = hdr.scrambling_control();
36        let afc = hdr.adaptation_field_control();
37
38        if sc != ScramblingControl::NotScrambled {
39            scrambled += 1;
40        }
41
42        if total <= 5 || hdr.pusi {
43            println!(
44                "pkt {:>6}: pid=0x{:04X} cc={:2} scrambling={} afc={}",
45                total, hdr.pid, hdr.continuity_counter, sc, afc,
46            );
47        }
48    }
49
50    let clear = total - scrambled;
51    println!("\n--- summary ---");
52    println!("total packets : {total}");
53    println!("clear packets : {clear}");
54    println!("scrambled pkts: {scrambled}");
55    println!("distinct PIDs : {}", pid_counts.len());
56
57    if total == 0 {
58        eprintln!("warning: no packets found in {path}");
59        std::process::exit(1);
60    }
61}