ez-ffmpeg 0.16.0

A safe and ergonomic Rust interface for FFmpeg integration, designed for ease of use.
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
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
//! Code emitter: [`LoweredJob`] -> a complete, compile-ready Rust program.
//!
//! The emitter consumes the SAME lowered plan the runtime path applies to
//! the builder (`LoweredJob::into_context`) — field for field, in the same
//! order — so generated code and in-process execution cannot drift. Every
//! emitted call exists in the crate's public API; a checked-in emitted
//! program is compiled as a real example (`examples/cli_emitted_transcode.rs`)
//! and pinned byte-for-byte by a unit test below (only the header's
//! crate-version stamp is masked, so a version bump alone never repins).

use super::lower::LoweredJob;
use super::manifest::{ShapeStatus, DIALECT, MANIFEST_REVISION};

/// Renders the program. `command` is the original argv (for the header
/// comment); `status` decides between the verified header and the
/// unverified-scaffolding banner.
pub(crate) fn emit(job: &LoweredJob, command: &[String], status: &ShapeStatus) -> String {
    let plain_input = job.input.format.is_none()
        && job.input.start_time_us.is_none()
        && job.input.recording_time_us.is_none()
        && job.input.stop_time_us.is_none();

    let mut out = String::new();
    header(
        &mut out,
        command,
        status,
        plain_input,
        job.output.video_filter.is_some(),
    );

    // Recognized no-op globals: named instead of silently swallowed.
    for noop in &job.noops {
        match &noop.value {
            Some(value) => out.push_str(&format!(
                "// {} {}: not applicable in-process (no-op)\n",
                noop.flag,
                comment_text(value)
            )),
            None => out.push_str(&format!(
                "// {}: not applicable in-process (no-op)\n",
                noop.flag
            )),
        }
    }
    if !job.noops.is_empty() {
        out.push('\n');
    }

    out.push_str("fn main() -> Result<(), Box<dyn std::error::Error>> {\n");
    out.push_str("    FfmpegContext::builder()\n");

    if plain_input {
        line(&mut out, 2, &format!(".input({})", lit(&job.input.url)));
    } else {
        line(&mut out, 2, ".input(");
        line(
            &mut out,
            3,
            &format!("Input::from({})", lit(&job.input.url)),
        );
        if let Some(format) = &job.input.format {
            line(
                &mut out,
                4,
                &format!(
                    ".set_format({}) // -f {}",
                    lit(format),
                    comment_text(format)
                ),
            );
        }
        if let Some(us) = job.input.start_time_us {
            line(
                &mut out,
                4,
                &format!(
                    ".set_start_time_us({}) // -ss (input side, seconds -> microseconds)",
                    num(us)
                ),
            );
        }
        if let Some(us) = job.input.recording_time_us {
            line(
                &mut out,
                4,
                &format!(".set_recording_time_us({}) // -t (input side)", num(us)),
            );
        }
        if let Some(us) = job.input.stop_time_us {
            line(
                &mut out,
                4,
                &format!(".set_stop_time_us({}) // -to (input side)", num(us)),
            );
        }
        line(&mut out, 2, ")");
    }

    line(&mut out, 2, ".output(");
    line(
        &mut out,
        3,
        &format!("Output::from({})", lit(&job.output.url)),
    );
    let o = &job.output;
    if let Some(format) = &o.format {
        line(
            &mut out,
            4,
            &format!(
                ".set_format({}) // -f {}",
                lit(format),
                comment_text(format)
            ),
        );
    }
    // Output-side trims come right here — before the disable/codec calls —
    // because that is where `LoweredJob::into_context` applies them; the
    // emitted call order mirrors the runtime apply order setter for setter.
    if let Some(us) = o.start_time_us {
        line(
            &mut out,
            4,
            &format!(
                ".set_start_time_us({}) // -ss (output side: decode, then discard)",
                num(us)
            ),
        );
    }
    if let Some(us) = o.recording_time_us {
        line(
            &mut out,
            4,
            &format!(".set_recording_time_us({}) // -t", num(us)),
        );
    }
    if let Some(us) = o.stop_time_us {
        line(
            &mut out,
            4,
            &format!(".set_stop_time_us({}) // -to", num(us)),
        );
    }
    if o.video_disable {
        line(&mut out, 4, ".disable_video() // -vn");
    }
    if o.audio_disable {
        line(&mut out, 4, ".disable_audio() // -an");
    }
    if let Some(codec) = &o.video_codec {
        line(
            &mut out,
            4,
            &format!(
                ".set_video_codec({}) // -c:v {}",
                lit(codec),
                comment_text(codec)
            ),
        );
    }
    if let Some(codec) = &o.audio_codec {
        line(
            &mut out,
            4,
            &format!(
                ".set_audio_codec({}) // -c:a {}",
                lit(codec),
                comment_text(codec)
            ),
        );
    }
    if let Some(bitrate) = &o.video_bitrate {
        line(
            &mut out,
            4,
            &format!(
                ".set_video_bitrate({}) // -b:v {}",
                lit(bitrate),
                comment_text(bitrate)
            ),
        );
    }
    if let Some(bitrate) = &o.audio_bitrate {
        line(
            &mut out,
            4,
            &format!(
                ".set_audio_bitrate({}) // -b:a {}",
                lit(bitrate),
                comment_text(bitrate)
            ),
        );
    }
    for (key, value) in &o.video_codec_opts {
        line(
            &mut out,
            4,
            &format!(
                ".set_video_codec_opt({}, {}) // -{} {}",
                lit(key),
                lit(value),
                comment_text(key),
                comment_text(value)
            ),
        );
    }
    for (key, value) in &o.format_opts {
        line(
            &mut out,
            4,
            &format!(
                ".set_format_opt({}, {}) // -{} {}",
                lit(key),
                lit(value),
                comment_text(key),
                comment_text(value)
            ),
        );
    }
    if let Some(pix_fmt) = &o.pix_fmt {
        line(
            &mut out,
            4,
            &format!(
                ".set_pix_fmt({}) // -pix_fmt {}",
                lit(pix_fmt),
                comment_text(pix_fmt)
            ),
        );
    }
    if let Some(rate) = o.audio_sample_rate {
        line(
            &mut out,
            4,
            &format!(".set_audio_sample_rate({rate}) // -ar {rate}"),
        );
    }
    if let Some(channels) = o.audio_channels {
        line(
            &mut out,
            4,
            &format!(".set_audio_channels({channels}) // -ac {channels}"),
        );
    }
    if let Some(frames) = o.max_video_frames {
        line(
            &mut out,
            4,
            &format!(".set_max_video_frames({frames}) // -frames:v {frames} (image2 update mode is applied automatically)"),
        );
    }
    if let Some(filter) = &o.video_filter {
        line(
            &mut out,
            4,
            &format!(
                ".set_video_filter({}) // -vf {}",
                lit(filter),
                comment_text(filter)
            ),
        );
    }
    for (map, copy) in &o.stream_maps {
        if *copy {
            line(
                &mut out,
                4,
                &format!(
                    ".add_stream_map_with_copy({}) // -map {} + copy",
                    lit(map),
                    comment_text(map)
                ),
            );
        } else {
            line(
                &mut out,
                4,
                &format!(
                    ".add_stream_map({}) // -map {}",
                    lit(map),
                    comment_text(map)
                ),
            );
        }
    }
    line(&mut out, 2, ")");
    line(&mut out, 2, ".build()?");
    line(&mut out, 2, ".start()?");
    line(&mut out, 2, ".wait()?;");
    out.push_str("    Ok(())\n}\n");
    out
}

fn header(
    out: &mut String,
    command: &[String],
    status: &ShapeStatus,
    plain_input: bool,
    vf_precondition: bool,
) {
    out.push_str("// Generated from an ffmpeg command by the ez-ffmpeg CLI-compat emitter.\n");
    out.push_str(&format!(
        "// command: ffmpeg {}
",
        comment_text(&requote(command))
    ));
    out.push_str(&format!(
        "// dialect: {DIALECT}; manifest: r{MANIFEST_REVISION}; crate: ez-ffmpeg {}; cargo features: none required\n",
        env!("CARGO_PKG_VERSION")
    ));
    match status {
        ShapeStatus::Verified(id) => {
            match super::manifest::shape(id) {
                Some(shape) => out.push_str(&format!(
                    "// status: verified shape {id} ({}) — verified by the manifest-driven \
                     semantic golden suite (oracle: {:?}) against the ffmpeg CLI; canonical \
                     emission compile-pinned as examples/{}.rs\n",
                    shape.summary, shape.oracle, shape.emitted_example
                )),
                None => out.push_str(&format!(
                    "// status: verified shape {id} — backed by a semantic golden against the ffmpeg CLI\n"
                )),
            }
        }
        ShapeStatus::Unverified(id) => {
            let entry = super::manifest::unverified_entry(id);
            let summary = entry.map(|e| e.summary).unwrap_or("unverified");
            out.push_str(&format!(
                "// status: UNVERIFIED SCAFFOLDING — manifest entry {id} ({summary}).\n\
                 // This shape has no semantic golden. The code below compiles against the\n\
                 // ez-ffmpeg builder API, but its behavior has NOT been checked against the\n\
                 // ffmpeg CLI and must not be treated as a faithful translation. Review every\n\
                 // call before use; in-process execution (from_cli / from_cli_args) refuses\n\
                 // this shape.\n"
            ));
        }
        ShapeStatus::Unmatched => {
            unreachable!("emit is never invoked for unmatched shapes (emit_from_tokens rejects)")
        }
    }
    if vf_precondition {
        out.push_str(
            "// precondition: -vf requires the input to contain exactly ONE video stream;\n\
             // in-process execution enforces this after probing (see from_cli_args), and\n\
             // this generated code inherits the same assumption.\n",
        );
    }
    out.push('\n');
    // Import exactly what the program uses: a plain `.input("url")` never
    // names the Input type, and the emitted file must compile warning-free.
    if plain_input {
        out.push_str("use ez_ffmpeg::{FfmpegContext, Output};\n\n");
    } else {
        out.push_str("use ez_ffmpeg::{FfmpegContext, Input, Output};\n\n");
    }
}

/// One indented builder line.
fn line(out: &mut String, level: usize, text: &str) {
    for _ in 0..level {
        out.push_str("    ");
    }
    out.push_str(text);
    out.push('\n');
}

/// A Rust string literal for `s`. `{:?}` escapes quotes, backslashes and
/// control characters and passes unicode through — exactly a valid literal.
fn lit(s: &str) -> String {
    format!("{s:?}")
}

/// User text rendered inside a generated `//` comment. Control characters
/// (newlines above all) are escape-rendered so no token can break out of the
/// comment and inject source — a quoted newline in an argv token must never
/// become a real newline in generated code. U+2028/U+2029 (LINE/PARAGRAPH
/// SEPARATOR) are not Unicode controls and rustc itself only ends `//`
/// comments at `\n`, but JavaScript-family tooling and some editors treat
/// them as line terminators — they are escaped on the same principle,
/// matching the `{:?}` treatment string literals already get.
fn comment_text(s: &str) -> String {
    s.chars()
        .flat_map(|c| {
            if c.is_control() || c == '\u{2028}' || c == '\u{2029}' {
                c.escape_debug().collect::<Vec<_>>()
            } else {
                vec![c]
            }
        })
        .collect()
}

/// Microsecond literals with `_` thousands separators, matching the crate's
/// documented `10_000_000` style.
fn num(us: i64) -> String {
    let digits = us.to_string();
    let mut grouped = String::new();
    for (i, ch) in digits.chars().enumerate() {
        if i > 0 && (digits.len() - i).is_multiple_of(3) {
            grouped.push('_');
        }
        grouped.push(ch);
    }
    grouped
}

/// Reassembles the argv into a copy-pasteable POSIX command line: tokens with
/// whitespace or quoting characters are single-quoted (embedded single quotes
/// via the `'\''` idiom).
fn requote(command: &[String]) -> String {
    command
        .iter()
        .map(|token| {
            let simple = !token.is_empty()
                && token.chars().all(|c| {
                    c.is_ascii_alphanumeric()
                        || matches!(c, '-' | '_' | '.' | '/' | ':' | '=' | '+' | '%' | ',' | '@')
                });
            if simple {
                token.clone()
            } else {
                format!("'{}'", token.replace('\'', r"'\''"))
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

#[cfg(test)]
mod tests {
    use super::super::{parse::parse, tokenize::tokenize};
    use super::*;
    use crate::core::cli::lower::lower;
    use crate::core::cli::manifest::classify;

    fn emit_cmd(cmd: &str) -> String {
        let args = tokenize(cmd).unwrap();
        let ir = parse(&args).unwrap_or_else(|e| panic!("{cmd} should parse: {e}"));
        let status = classify(&ir);
        emit(&lower(&ir), &args, &status)
    }

    #[test]
    fn num_groups_digits() {
        assert_eq!(num(0), "0");
        assert_eq!(num(500), "500");
        assert_eq!(num(10_000_000), "10_000_000");
        assert_eq!(num(2_500_000), "2_500_000");
        assert_eq!(num(100), "100");
        assert_eq!(num(1000), "1_000");
    }

    #[test]
    fn lit_escapes_quotes_and_keeps_unicode() {
        assert_eq!(lit(r#"a"b"#), r#""a\"b""#);
        assert_eq!(lit("视频.mp4"), "\"视频.mp4\"");
    }

    #[test]
    fn comment_text_escapes_controls_and_unicode_line_separators() {
        assert_eq!(comment_text("a\nb\0c"), r"a\nb\0c");
        // U+2028/U+2029 are category Zl/Zp, not controls, and must still be
        // escape-rendered: some tooling treats them as line terminators.
        assert_eq!(comment_text("a\u{2028}b\u{2029}c"), r"a\u{2028}b\u{2029}c");
        // Ordinary unicode passes through untouched.
        assert_eq!(comment_text("视频 ok"), "视频 ok");
    }

    #[test]
    fn requote_quotes_tokens_with_spaces() {
        let args = vec!["-i".to_string(), "my movie.mp4".to_string()];
        assert_eq!(requote(&args), "-i 'my movie.mp4'");
    }

    #[test]
    fn verified_emit_carries_dialect_and_shape() {
        let code =
            emit_cmd("ffmpeg -i in.mkv -c:v libx264 -crf 23 -preset fast -c:a aac -y out.mp4");
        assert!(code.contains("// status: verified shape V1"));
        assert!(code.contains("dialect: ffmpeg 7.1 command line"));
        assert!(code.contains("manifest: r4"));
        assert!(code.contains(".set_video_codec(\"libx264\") // -c:v libx264"));
        assert!(code.contains(".set_video_codec_opt(\"crf\", \"23\") // -crf 23"));
        assert!(code.contains(".set_video_codec_opt(\"preset\", \"fast\") // -preset fast"));
        assert!(code.contains(".set_audio_codec(\"aac\") // -c:a aac"));
        assert!(!code.contains("UNVERIFIED"));
    }

    #[test]
    fn clip_emit_scopes_trims_correctly() {
        let code =
            emit_cmd("ffmpeg -ss 10 -i in.mp4 -t 20 -c:v libx264 -crf 23 -c:a aac -y clip.mp4");
        assert!(code.contains("Input::from(\"in.mp4\")"));
        assert!(code.contains(".set_start_time_us(10_000_000) // -ss (input side"));
        assert!(code.contains(".set_recording_time_us(20_000_000) // -t"));
        // The output must NOT carry the input's -ss.
        assert!(!code.contains("// -ss (output side"));
    }

    #[test]
    fn thumbnail_emit_uses_generic_path() {
        let code = emit_cmd("ffmpeg -ss 5 -i in.mp4 -an -c:v mjpeg -frames:v 1 -y thumb.jpg");
        assert!(code.contains(".disable_audio() // -an"));
        assert!(code.contains(".set_video_codec(\"mjpeg\")"));
        assert!(code.contains(".set_max_video_frames(1)"));
        assert!(code.contains("image2 update mode is applied automatically"));
    }

    #[test]
    fn scale_emit_uses_per_output_filter() {
        let code = emit_cmd(
            "ffmpeg -i in.mp4 -vf scale=1280:-2 -c:v libx264 -crf 23 -preset fast -c:a aac -y scaled.mp4",
        );
        assert!(code.contains(".set_video_filter(\"scale=1280:-2\") // -vf scale=1280:-2"));
    }

    #[test]
    fn hls_emit_maps_every_muxer_option() {
        let code = emit_cmd(
            "ffmpeg -i in.mp4 -c:v libx264 -crf 23 -c:a aac -f hls -hls_time 6 -hls_playlist_type vod -hls_list_size 0 -hls_segment_filename 'seg_%03d.ts' -y out.m3u8",
        );
        assert!(code.contains(".set_format(\"hls\") // -f hls"));
        assert!(code.contains(".set_format_opt(\"hls_time\", \"6\")"));
        assert!(code.contains(".set_format_opt(\"hls_playlist_type\", \"vod\")"));
        assert!(code.contains(".set_format_opt(\"hls_list_size\", \"0\")"));
        assert!(code.contains(".set_format_opt(\"hls_segment_filename\", \"seg_%03d.ts\")"));
    }

    #[test]
    fn audio_extract_emit() {
        let code = emit_cmd("ffmpeg -i in.mp4 -vn -c:a aac -b:a 192k -y out.m4a");
        assert!(code.contains(".disable_video() // -vn"));
        assert!(code.contains(".set_audio_bitrate(\"192k\") // -b:a 192k"));
    }

    #[test]
    fn unverified_emit_carries_the_scaffolding_banner() {
        // Parses (all tokens classify) but matches no golden-backed shape.
        let code = emit_cmd("ffmpeg -i in.mp4 -c:v mpeg4 -y out.avi");
        assert!(code.contains("UNVERIFIED SCAFFOLDING"));
        // The banner cites the manifest entry that admitted the shape.
        assert!(code.contains("manifest entry U16 (video-codec-only transcode)"));
        assert!(code.contains("refuses"));
        // The scaffolding must never claim equivalence.
        assert!(!code.to_lowercase().contains("equivalent"));
    }

    #[test]
    fn emitted_code_quotes_paths_with_spaces_and_unicode() {
        let code = emit_cmd("ffmpeg -i '我的 视频.mp4' -c:v mpeg4 -y '导出 v1.avi'");
        assert!(code.contains(".input(\"我的 视频.mp4\")"));
        assert!(code.contains("Output::from(\"导出 v1.avi\")"));
        assert!(code.contains("// command: ffmpeg -i '我的 视频.mp4'"));
    }

    /// Replaces the header's crate-version stamp with a placeholder so the
    /// emission pins survive version bumps without repinning the examples.
    /// Deliberately strict: the marker must appear exactly once and the
    /// stamp must LOOK like a version (leading digit, then the semver
    /// charset), so the mask can never swallow non-version drift.
    fn mask_crate_version(code: &str) -> String {
        const MARKER: &str = "crate: ez-ffmpeg ";
        assert_eq!(
            code.matches(MARKER).count(),
            1,
            "expected exactly one crate-version stamp:\n{code}"
        );
        let (head, rest) = code.split_once(MARKER).unwrap();
        let stamp_len = rest
            .bytes()
            .take_while(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'+'))
            .count();
        // The stamp is an ASCII prefix, so `stamp_len` is a char boundary.
        let (stamp, tail) = rest.split_at(stamp_len);
        assert!(
            stamp.as_bytes().first().is_some_and(u8::is_ascii_digit),
            "crate-version stamp is not a version: {rest:?}"
        );
        format!("{head}{MARKER}<crate version>{tail}")
    }

    #[test]
    fn mask_crate_version_masks_only_the_version_stamp() {
        let header = "// dialect: d; manifest: r4; crate: ez-ffmpeg 0.15.0-rc.1+meta; \
                      cargo features: none required\n";
        assert_eq!(
            mask_crate_version(header),
            "// dialect: d; manifest: r4; crate: ez-ffmpeg <crate version>; \
             cargo features: none required\n"
        );
    }

    #[test]
    #[should_panic(expected = "not a version")]
    fn mask_crate_version_rejects_a_non_version_stamp() {
        mask_crate_version("crate: ez-ffmpeg vandalized; cargo features: none required");
    }

    #[test]
    fn every_verified_shape_emission_is_pinned_and_compiled() {
        // Each examples/cli_emitted_* file is the EXACT emission of its
        // shape's canonical argv, checked in and built by cargo (examples
        // compile as real targets), so every emitted call is proven against
        // the real crate API byte for byte, the header's crate-version stamp
        // aside — and the golden runner executes these same binaries as its
        // third lane.
        use crate::core::cli::manifest::VERIFIED_SHAPES;
        for shape in VERIFIED_SHAPES {
            let code = crate::core::cli::emit_rust_code_from_args(shape.canonical_argv)
                .unwrap_or_else(|e| panic!("emit of {} canonical argv failed: {e}", shape.id));
            let pinned = match shape.emitted_example {
                "cli_emitted_transcode" => {
                    include_str!("../../../examples/cli_emitted_transcode.rs")
                }
                "cli_emitted_clip" => include_str!("../../../examples/cli_emitted_clip.rs"),
                "cli_emitted_audio_extract" => {
                    include_str!("../../../examples/cli_emitted_audio_extract.rs")
                }
                "cli_emitted_thumbnail" => {
                    include_str!("../../../examples/cli_emitted_thumbnail.rs")
                }
                "cli_emitted_scale" => include_str!("../../../examples/cli_emitted_scale.rs"),
                "cli_emitted_hls" => include_str!("../../../examples/cli_emitted_hls.rs"),
                other => panic!("shape {} names an unpinned example {other}", shape.id),
            };
            // The emitter writes `\n`; `include_str!` embeds the example as
            // checked out, which is CRLF under Windows autocrlf. Normalize
            // the pinned side so the comparison is about content, not the
            // checkout's line-ending policy.
            let pinned = pinned.replace("\r\n", "\n");
            // The header stamps the version of the crate that emitted the
            // file; a plain version bump must not repin all six examples.
            // Exactly that stamp is masked on BOTH sides — every other byte
            // still has to match.
            assert_eq!(
                mask_crate_version(&code),
                mask_crate_version(&pinned),
                "examples/{}.rs drifted from the emitter; regenerate it",
                shape.emitted_example
            );
        }
    }

    /// The emitted OUTPUT builder calls must appear in exactly the order
    /// `LoweredJob::into_context` applies them — the facade documents the
    /// generated program and the runtime path as "same builder calls, same
    /// values, same order". U11 (output-side seek transcode) is the
    /// discriminating shape: its output trims must be emitted BEFORE the
    /// codec calls, where the runtime applies them, not appended after the
    /// maps. The setters commute, so this is a source-fidelity pin, not a
    /// behavior test.
    #[test]
    fn emitted_output_calls_follow_the_runtime_apply_order() {
        let code = emit_cmd(
            "ffmpeg -i in.mp4 -ss 3 -t 4 -c:v libx264 -crf 23 -preset fast -c:a aac -y out.mp4",
        );
        let runtime_order = [
            ".set_start_time_us(3_000_000)",
            ".set_recording_time_us(4_000_000)",
            ".set_video_codec(\"libx264\")",
            ".set_audio_codec(\"aac\")",
            ".set_video_codec_opt(\"crf\", \"23\")",
            ".set_video_codec_opt(\"preset\", \"fast\")",
        ];
        let mut previous: Option<(usize, &str)> = None;
        for call in runtime_order {
            let at = code
                .find(call)
                .unwrap_or_else(|| panic!("emitted code lost {call}:\n{code}"));
            if let Some((prev_at, prev_call)) = previous {
                assert!(
                    at > prev_at,
                    "emitted {call} before {prev_call}, diverging from the runtime apply \
                     order:\n{code}"
                );
            }
            previous = Some((at, call));
        }
    }

    #[test]
    fn faststart_remux_emit_is_unverified_with_explicit_copies() {
        let code =
            emit_cmd("ffmpeg -i in.mp4 -c:v copy -c:a copy -movflags +faststart -y faststart.mp4");
        assert!(code.contains("UNVERIFIED SCAFFOLDING"));
        assert!(code.contains(".set_video_codec(\"copy\") // -c:v copy"));
        assert!(code.contains(".set_audio_codec(\"copy\") // -c:a copy"));
        assert!(code.contains(".set_format_opt(\"movflags\", \"+faststart\")"));
    }
}