transmux 0.27.2

Any-to-any media container muxing hub: demux TS, fMP4/CMAF, MPEG-PS, WebM, FLV, or RTMP into one neutral IR and mux to CMAF/fMP4, progressive MP4, TS, DASH, low-latency DASH, HLS, low-latency HLS, Smooth Streaming, or RTMP. CENC/CBCS encrypt+decrypt, SSAI splice, RTP/RTCP, and an fMP4/CMAF conformance validator; parses codec config headers only, samples stay opaque. no_std + alloc, except the XML manifest paths (DASH/Smooth/PlayReady), which need the std feature.
Documentation
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
//! `transmux` CLI front-end gate (issue #482).
//!
//! Exercises the CLI core ([`transmux::cli`]) that wires the existing demux
//! spokes through the hub IR into the existing mux spokes. Every test **bites**:
//!
//! 1. **TS → CMAF, validator-gated**: a real `.ts` fixture through `run_bytes`
//!    to CMAF, then split into init + media and run the crate's own
//!    `validate_init_segment` / `validate_media_segment`; assert **zero**
//!    `Severity::Error`. A broken pipeline fails validation.
//! 2. **MP4 → HLS**: a fragmented mp4 through `run_bytes` to HLS; assert a valid
//!    `#EXTM3U` playlist (with `#EXT-X-TARGETDURATION`) and that every referenced
//!    `.m4s` segment validates as a CMAF init+media with no errors.
//! 3. **Autodetect bites**: the detector returns the correct container for TS,
//!    MP4, WebM, and PS fixtures, and `Err` on garbage. A detector that always
//!    picks one fails.
//! 4. **Format selection bites**: the same TS input with `-f ts` vs `-f cmaf`
//!    produces structurally different leading bytes (TS `0x47` vs an ISO-BMFF
//!    box), so a mux that ignored the format flag fails.
//! 5. **clap parsing**: `Args::try_parse_from` accepts representative argv and
//!    the command builds (`--help`/`--version` wire up) without panic.
//! 6. **Real DVB multiplex bites (media plane step-2 fix wave 1)**: a real
//!    multi-program DVB capture (`m6-single.ts`, carrying DVB subtitle/DSM-CC
//!    `CodecConfig::Data` tracks alongside real audio/video) through
//!    `run_bytes` to CMAF must succeed, not error on the opaque tracks — the
//!    CLI filters them (with a stderr warning) rather than failing on
//!    ordinary real-world input.

#![cfg(feature = "cli")]

use std::path::PathBuf;

use transmux::cli::{Args, Container, Opts, Output, OutputFormat, detect_container, run_bytes};
use transmux::{Severity, validate_init_segment, validate_media_segment};

fn fixtures() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../fixtures")
}

fn read(rel: &str) -> Vec<u8> {
    let p = fixtures().join(rel);
    std::fs::read(&p).unwrap_or_else(|e| panic!("read fixture {}: {e}", p.display()))
}

/// Split a self-contained CMAF artifact (`ftyp` + `moov` + `styp` + `moof` +
/// `mdat`) at the first `styp` box into `(init, media)`.
fn split_cmaf(bytes: &[u8]) -> (&[u8], &[u8]) {
    let mut off = 0usize;
    while off + 8 <= bytes.len() {
        let size = u32::from_be_bytes([bytes[off], bytes[off + 1], bytes[off + 2], bytes[off + 3]])
            as usize;
        let ty = &bytes[off + 4..off + 8];
        if ty == b"styp" {
            return (&bytes[..off], &bytes[off..]);
        }
        if size < 8 || off + size > bytes.len() {
            break;
        }
        off += size;
    }
    panic!("no styp box found — CMAF media segment missing");
}

fn errors(issues: &[transmux::ConformanceIssue]) -> Vec<String> {
    issues
        .iter()
        .filter(|i| i.severity == Severity::Error)
        .map(|i| format!("{}: {}", i.code, i.message))
        .collect()
}

// --------------------------------------------------------------------------
// 1. TS → CMAF, validator-gated
// --------------------------------------------------------------------------

#[test]
fn ts_to_cmaf_validates_clean() {
    let ts = read("ts/h264_aac.ts");
    let opts = Opts {
        format: OutputFormat::Cmaf,
        ..Opts::default()
    };
    let out = run_bytes(&ts, &opts).expect("TS → CMAF must succeed");
    let cmaf = match out {
        Output::Bytes(b) => b,
        _ => panic!("CMAF output must be Bytes"),
    };
    // A real fMP4: leading box is `ftyp`.
    assert_eq!(&cmaf[4..8], b"ftyp", "CMAF must open with an ftyp box");

    let (init, media) = split_cmaf(&cmaf);
    let init_errs = errors(&validate_init_segment(init));
    let media_errs = errors(&validate_media_segment(media));
    assert!(
        init_errs.is_empty(),
        "init segment has validator errors: {init_errs:?}"
    );
    assert!(
        media_errs.is_empty(),
        "media segment has validator errors: {media_errs:?}"
    );
}

// --------------------------------------------------------------------------
// 2. MP4 → HLS
// --------------------------------------------------------------------------

#[test]
fn mp4_to_hls_playlist_and_segments() {
    let mp4 = read("mp4/frag/h264_high.frag.mp4");
    let opts = Opts {
        format: OutputFormat::Hls,
        segment_duration: 4,
        ..Opts::default()
    };
    let out = run_bytes(&mp4, &opts).expect("MP4 → HLS must succeed");
    let (text, segments) = match out {
        Output::Manifest { text, segments } => (text, segments),
        _ => panic!("HLS output must be a Manifest"),
    };
    assert!(
        text.starts_with("#EXTM3U"),
        "playlist must start with #EXTM3U"
    );
    assert!(
        text.contains("#EXT-X-TARGETDURATION"),
        "playlist must carry #EXT-X-TARGETDURATION"
    );
    assert!(
        !segments.is_empty(),
        "playlist must reference at least one segment"
    );
    // Every referenced file must be named in the playlist (the segments by URI,
    // the init by the `#EXT-X-MAP` URI). The init file is the Media
    // Initialization Section; each segment is a media-only
    // `styp`+`moof`+`mdat` (an `#EXT-X-MAP` init is shared, not repeated).
    let init_bytes = segments
        .iter()
        .find(|(n, _)| n == "init.mp4")
        .map(|(_, b)| b.clone())
        .expect("init.mp4 written beside the segments");
    assert!(
        errors(&validate_init_segment(&init_bytes)).is_empty(),
        "init.mp4 has errors"
    );
    for (name, bytes) in &segments {
        assert!(
            text.contains(name.as_str()),
            "playlist must reference {name}"
        );
        if name == "init.mp4" {
            continue;
        }
        assert_eq!(&bytes[4..8], b"styp", "segment {name} must begin with styp");
        assert!(
            !bytes.windows(4).take(4096).any(|w| w == b"moov"),
            "segment {name} must not repeat the moov the #EXT-X-MAP names"
        );
        assert!(
            errors(&validate_media_segment(bytes)).is_empty(),
            "segment {name} media has errors"
        );
    }
}

// --------------------------------------------------------------------------
// 3. Autodetect bites
// --------------------------------------------------------------------------

#[test]
fn autodetect_recognises_each_container() {
    assert_eq!(
        detect_container(&read("ts/h264_aac.ts")).unwrap(),
        Container::MpegTs
    );
    assert_eq!(
        detect_container(&read("mp4/frag/h264_high.frag.mp4")).unwrap(),
        Container::Mp4
    );
    assert_eq!(
        detect_container(&read("webm/vp9_opus.webm")).unwrap(),
        Container::WebM
    );
    assert_eq!(
        detect_container(&read("ps/h264_ac3.ps")).unwrap(),
        Container::MpegPs
    );
    // Garbage must not be mistaken for any container.
    assert!(detect_container(&[0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x11, 0x22, 0x33, 0x44]).is_err());
    assert!(detect_container(&[]).is_err());
}

/// M2TS (192-byte packets: a 4-byte timecode prefix before each 188-byte packet)
/// and a capture that starts mid-packet are both real TS streams the old
/// fixed-offset check (`0x47` at 0 and at 188) missed. `container-probe`'s
/// stride×phase lattice finds them (issue #960 / audit r05-W29).
#[test]
fn autodetect_finds_m2ts_and_mid_packet_captures() {
    let ts = read("ts/h264_aac.ts");
    assert_eq!(detect_container(&ts).unwrap(), Container::MpegTs);

    // M2TS: prepend a 4-byte timestamp before *every* 188-byte packet.
    let mut m2ts = Vec::with_capacity(ts.len() / 188 * 192);
    for pkt in ts.chunks_exact(188) {
        m2ts.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]);
        m2ts.extend_from_slice(pkt);
    }
    assert_eq!(
        detect_container(&m2ts).unwrap(),
        Container::MpegTs,
        "a 192-byte-stride M2TS capture must be recognised (the old check missed it)"
    );

    // A capture that starts part-way into a packet: drop the first 100 bytes.
    let mid = &ts[100..];
    assert_eq!(
        detect_container(mid).unwrap(),
        Container::MpegTs,
        "a mid-packet capture must be recognised"
    );
}

// --------------------------------------------------------------------------
// 4. Format selection bites
// --------------------------------------------------------------------------

#[test]
fn format_selection_changes_output_shape() {
    let ts = read("ts/h264_aac.ts");

    let cmaf = match run_bytes(
        &ts,
        &Opts {
            format: OutputFormat::Cmaf,
            ..Opts::default()
        },
    )
    .expect("TS → CMAF")
    {
        Output::Bytes(b) => b,
        _ => panic!("CMAF must be Bytes"),
    };
    let ts_out = match run_bytes(
        &ts,
        &Opts {
            format: OutputFormat::Ts,
            ..Opts::default()
        },
    )
    .expect("TS → TS")
    {
        Output::Bytes(b) => b,
        _ => panic!("TS must be Bytes"),
    };

    // CMAF: first bytes are an ISO-BMFF box (size then `ftyp`), byte 0 is 0x00.
    assert_eq!(&cmaf[4..8], b"ftyp", "CMAF must lead with ftyp box");
    assert_ne!(cmaf[0], 0x47, "CMAF must not start with the TS sync byte");
    // TS: first byte is the 0x47 sync byte, whole 188-byte packets.
    assert_eq!(ts_out[0], 0x47, "TS output must start with the sync byte");
    assert_eq!(
        ts_out.len() % 188,
        0,
        "TS output must be whole 188-byte packets"
    );
    // The two outputs are genuinely different container shapes.
    assert_ne!(
        cmaf[0], ts_out[0],
        "the two formats must differ at the leading byte"
    );
}

// --------------------------------------------------------------------------
// 6. Real DVB multiplex bites (media plane step-2 fix wave 1)
// --------------------------------------------------------------------------

#[test]
fn real_dvb_multiplex_to_cmaf_does_not_fail_on_opaque_data_tracks() {
    // `m6-single.ts` is a real broadcast excerpt (see `dvb-si`'s fixture
    // provenance) carrying DVB subtitle/DSM-CC/private-section PIDs that
    // classify as opaque `CodecConfig::Data`, alongside real audio/video —
    // exactly what CmafMux rejected unfiltered before this fix, which made
    // the shipped CLI fail on every such real multiplex. `run_bytes` must
    // filter and succeed, not propagate `Error::UnmuxableDataTrack`.
    let ts = read("ts/m6-single.ts");
    let opts = Opts {
        format: OutputFormat::Cmaf,
        ..Opts::default()
    };
    let out = run_bytes(&ts, &opts)
        .expect("CLI must not fail on a real DVB multiplex with opaque Data tracks");
    let cmaf = match out {
        Output::Bytes(b) => b,
        _ => panic!("CMAF output must be Bytes"),
    };
    assert_eq!(&cmaf[4..8], b"ftyp", "CMAF must open with an ftyp box");

    let (init, media) = split_cmaf(&cmaf);
    let init_errs = errors(&validate_init_segment(init));
    let media_errs = errors(&validate_media_segment(media));
    assert!(
        init_errs.is_empty(),
        "init segment has validator errors: {init_errs:?}"
    );
    assert!(
        media_errs.is_empty(),
        "media segment has validator errors: {media_errs:?}"
    );
}

// --------------------------------------------------------------------------
// 5. clap parsing
// --------------------------------------------------------------------------

#[test]
fn args_parse_representative_argv() {
    use clap::{CommandFactory, Parser};

    // Positional input + named output + format + segment-duration.
    let a = Args::try_parse_from([
        "transmux",
        "in.ts",
        "-o",
        "out.m3u8",
        "-f",
        "hls",
        "--segment-duration",
        "4",
    ])
    .expect("representative argv must parse");
    assert_eq!(a.output, PathBuf::from("out.m3u8"));
    assert_eq!(a.segment_duration, 4);

    // `-i/--input` form + track selection.
    let b = Args::try_parse_from([
        "transmux", "-i", "in.mp4", "-o", "out.cmaf", "--tracks", "1,2",
    ])
    .expect("-i form must parse");
    assert_eq!(b.tracks, vec![1, 2]);

    // Missing both input and output must be an error, not a panic.
    assert!(Args::try_parse_from(["transmux"]).is_err());

    // The command builds (so --help/--version are wired) without panic.
    Args::command().debug_assert();
}

// --------------------------------------------------------------------------
// 6. Debug of `Args` never prints key hex (adversarial review finding on the
//    W8/W-CSA-4 wave). The `CliError::BadKey` redaction path is exercised by
//    a unit test inside `src/cli.rs` (it needs the private `parse_key`).
// --------------------------------------------------------------------------

#[cfg(feature = "cenc")]
#[test]
fn args_debug_redacts_key_hex_but_keeps_the_kid() {
    use clap::Parser;

    let kid_hex = "0102030405060708090a0b0c0d0e0f10";
    let key_hex = "aabbccddeeff00112233445566778899";
    let spec = format!("{kid_hex}:{key_hex}");

    let a = Args::try_parse_from(["transmux", "in.mp4", "-o", "out.cmaf", "--key", &spec])
        .expect("well-formed --key must parse");
    let out = format!("{a:?}");

    assert!(
        !out.contains(key_hex),
        "Debug of Args must not contain the key half: {out}"
    );
    assert!(
        out.contains(kid_hex),
        "the KID half is not secret and should still appear: {out}"
    );
}

// --------------------------------------------------------------------------
// 5. --segment-duration is honoured, and DASH media segments carry no moov
//    (audit r05-W29)
// --------------------------------------------------------------------------

/// The MPD's `SegmentTemplate@duration` must equal `--segment-duration`, and
/// every media segment it addresses must exist and be a `styp`+`moof`+`mdat`
/// file with no `moov` (ISO/IEC 23009-1 §6.3.4.2).
#[test]
fn dash_honours_segment_duration_and_omits_moov() {
    let ts = read("ts/h264_aac.ts");
    let out = run_bytes(
        &ts,
        &Opts {
            format: OutputFormat::Dash,
            segment_duration: 2,
            ..Opts::default()
        },
    )
    .expect("TS → DASH");

    let (text, files) = match out {
        Output::Manifest { text, segments } => (text, segments),
        _ => panic!("DASH must be a Manifest"),
    };

    // The video SegmentTemplate's duration is 2 s at 90000 ticks/s.
    assert!(
        text.contains("timescale=\"90000\" duration=\"180000\""),
        "SegmentTemplate@duration must be the 2 s segment target: {text}"
    );

    // One init per track, and at least a second media segment (proving the
    // file was actually split, not emitted whole).
    let names: Vec<&str> = files.iter().map(|(n, _)| n.as_str()).collect();
    assert!(names.contains(&"init-stream1.m4s"), "video init: {names:?}");
    assert!(
        names.contains(&"chunk-stream1-2.m4s"),
        "a second video media segment must exist: {names:?}"
    );

    // No media segment may contain a `moov` box.
    for (name, bytes) in &files {
        if !name.starts_with("chunk-stream") {
            continue;
        }
        let has_moov = bytes.windows(4).take(4096).any(|w| w == b"moov");
        assert!(
            !has_moov,
            "media segment {name} must not contain a moov (ISO/IEC 23009-1 §6.3.4.2)"
        );
        // It must begin with styp, then moof, then mdat.
        assert_eq!(&bytes[4..8], b"styp", "{name} must begin with styp");
    }
}

/// The CMAF-HLS playlist must list one segment per `--segment-duration` slice
/// (not one whole-file blob), each with an `#EXT-X-MAP`, and the init file it
/// names must be written alongside.
#[test]
fn hls_honours_segment_duration_and_writes_init() {
    let ts = read("ts/h264_aac.ts");
    let out = run_bytes(
        &ts,
        &Opts {
            format: OutputFormat::Hls,
            segment_duration: 2,
            ..Opts::default()
        },
    )
    .expect("TS → HLS");

    let (text, files) = match out {
        Output::Manifest { text, segments } => (text, segments),
        _ => panic!("HLS must be a Manifest"),
    };

    let extinf = text.matches("#EXTINF:").count();
    assert!(
        extinf >= 2,
        "one #EXTINF per segment (>1 for a multi-second input): {text}"
    );
    assert!(text.contains("#EXT-X-MAP:URI=\"init.mp4\""), "{text}");
    assert!(text.ends_with("#EXT-X-ENDLIST\n"), "VOD playlist: {text}");

    let names: Vec<&str> = files.iter().map(|(n, _)| n.as_str()).collect();
    assert!(names.contains(&"init.mp4"), "init file written: {names:?}");
    assert_eq!(
        extinf,
        names.iter().filter(|n| n.starts_with("seg")).count(),
        "one file per #EXTINF"
    );
}