direct_play_nice 0.1.0-beta.3

CLI program that converts video files to direct-play-compatible formats.
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
#![cfg(feature = "ffmpeg-cli-tests")]

//! Integration test: converts an input with bitmap subtitles
//! and verifies the output is Chromecast direct‑play compatible with
//! text subs (MOV_TEXT) and intact timing. We prefer PGS, but fall back
//! to other bitmap subtitle codecs if the encoder isn't available in the
//! local ffmpeg build.

use assert_cmd::prelude::*;
use predicates::str;
use std::env;
use std::ffi::CString;
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Command;
use tempfile::TempDir;

use rsmpeg::avformat::AVFormatContextInput;
use rsmpeg::ffi;

fn ensure_ffmpeg_present() {
    let out = Command::new("ffmpeg").arg("-version").output();
    match out {
        Ok(o) if o.status.success() => (),
        _ => panic!("ffmpeg CLI not found. Install ffmpeg and ensure it is on PATH."),
    }
}

fn mk_subs_file(path: &Path) {
    let mut f = File::create(path).expect("create srt");
    writeln!(
        f,
        "1\n00:00:00,000 --> 00:00:00,800\nhello bitmap\n\n2\n00:00:01,000 --> 00:00:01,600\nsecond line\n"
    )
    .unwrap();
}

fn mk_subs_file_with_text(path: &Path, first: &str, second: &str) {
    let mut f = File::create(path).expect("create srt");
    writeln!(
        f,
        "1\n00:00:00,000 --> 00:00:00,800\n{}\n\n2\n00:00:01,000 --> 00:00:01,600\n{}\n",
        first, second
    )
    .unwrap();
}

fn gen_problem_input_with_bitmap_subs(tmp: &TempDir) -> (PathBuf, u64, bool) {
    let dir = tmp.path();
    let video = dir.join("v.mkv");
    let audio = dir.join("a.mp2");
    let subs = dir.join("subs.srt");
    let input = dir.join("input_bitmap.mkv");
    let mut used_text_subs = false;

    mk_subs_file(&subs);

    // Tiny source: 2s MPEG4 yuv420p
    let status_v = Command::new("ffmpeg")
        .args([
            "-y",
            "-f",
            "lavfi",
            "-i",
            "testsrc=size=160x120:rate=25:duration=2",
            "-pix_fmt",
            "yuv420p",
            "-c:v",
            "mpeg4",
            &video.to_string_lossy(),
        ])
        .status()
        .expect("run ffmpeg video");
    assert!(status_v.success(), "ffmpeg video generation failed");

    let status_a = Command::new("ffmpeg")
        .args([
            "-y",
            "-f",
            "lavfi",
            "-i",
            "sine=frequency=1000:sample_rate=44100:duration=2",
            "-c:a",
            "mp2",
            &audio.to_string_lossy(),
        ])
        .status()
        .expect("run ffmpeg audio");
    assert!(status_a.success(), "ffmpeg audio generation failed");

    // Mux subtitles by encoding SRT -> bitmap codec if available; otherwise
    // fall back to a text codec (ASS) to keep the test portable. The CLI
    // still exercises subtitle transcoding to MOV_TEXT either way.
    let candidates = ["hdmv_pgs_subtitle", "dvdsub", "dvb_subtitle"];
    let mut ok = false;
    for codec in candidates {
        let status_mux = Command::new("ffmpeg")
            .args([
                "-y",
                "-i",
                &video.to_string_lossy(),
                "-i",
                &audio.to_string_lossy(),
                "-i",
                &subs.to_string_lossy(),
                "-c:v",
                "copy",
                "-c:a",
                "copy",
                "-c:s",
                codec,
                "-map",
                "0:v:0",
                "-map",
                "1:a:0",
                "-map",
                "2:0",
                &input.to_string_lossy(),
            ])
            .status()
            .expect("run ffmpeg mux bitmap subs");
        if status_mux.success() {
            ok = true;
            break;
        }
    }
    if !ok {
        // Final fallback: encode as text subs using ASS inside MKV.
        // This keeps the test runnable on platforms where text->bitmap is unsupported
        // or bitmap encoders are unavailable.
        let status_text = Command::new("ffmpeg")
            .args([
                "-y",
                "-i",
                &video.to_string_lossy(),
                "-i",
                &audio.to_string_lossy(),
                "-i",
                &subs.to_string_lossy(),
                "-c:v",
                "copy",
                "-c:a",
                "copy",
                "-c:s",
                "ass",
                "-map",
                "0:v:0",
                "-map",
                "1:a:0",
                "-map",
                "2:0",
                &input.to_string_lossy(),
            ])
            .status()
            .expect("run ffmpeg mux text subs");
        assert!(
            status_text.success(),
            "ffmpeg mux with bitmap and text subtitle encoders failed"
        );
        used_text_subs = true;
    }

    let input_cstr = CString::new(input.to_string_lossy().to_string()).unwrap();
    let ictx = AVFormatContextInput::open(input_cstr.as_c_str()).unwrap();
    let dur_ms = (ictx.duration / 1000).max(0) as u64;
    (input, dur_ms, used_text_subs)
}

fn gen_multi_stream_bitmap_input(tmp: &TempDir) -> Option<PathBuf> {
    let dir = tmp.path();
    let video = dir.join("v_multi.mkv");
    let audio = dir.join("a_multi.mp2");
    let subs_eng = dir.join("subs_eng.srt");
    let subs_spa = dir.join("subs_spa.srt");
    let input = dir.join("input_multi_bitmap.mkv");

    mk_subs_file_with_text(&subs_eng, "hello world", "second english line");
    mk_subs_file_with_text(&subs_spa, "hola mundo", "segunda linea");

    let status_v = Command::new("ffmpeg")
        .args([
            "-y",
            "-f",
            "lavfi",
            "-i",
            "testsrc=size=160x120:rate=25:duration=2",
            "-pix_fmt",
            "yuv420p",
            "-c:v",
            "mpeg4",
            &video.to_string_lossy(),
        ])
        .status()
        .expect("run ffmpeg video");
    assert!(status_v.success(), "ffmpeg video generation failed");

    let status_a = Command::new("ffmpeg")
        .args([
            "-y",
            "-f",
            "lavfi",
            "-i",
            "sine=frequency=1000:sample_rate=44100:duration=2",
            "-c:a",
            "mp2",
            &audio.to_string_lossy(),
        ])
        .status()
        .expect("run ffmpeg audio");
    assert!(status_a.success(), "ffmpeg audio generation failed");

    let candidates = ["hdmv_pgs_subtitle", "dvdsub", "dvb_subtitle"];
    for codec in candidates {
        let status_mux = Command::new("ffmpeg")
            .args([
                "-y",
                "-i",
                &video.to_string_lossy(),
                "-i",
                &audio.to_string_lossy(),
                "-i",
                &subs_eng.to_string_lossy(),
                "-i",
                &subs_spa.to_string_lossy(),
                "-c:v",
                "copy",
                "-c:a",
                "copy",
                "-c:s",
                codec,
                "-metadata:s:s:0",
                "language=eng",
                "-metadata:s:s:1",
                "language=spa",
                "-map",
                "0:v:0",
                "-map",
                "1:a:0",
                "-map",
                "2:0",
                "-map",
                "3:0",
                &input.to_string_lossy(),
            ])
            .status()
            .expect("run ffmpeg mux bitmap subs");
        if status_mux.success() {
            return Some(input);
        }
    }

    None
}

fn is_bitmap_subtitle_codec(codec_id: ffi::AVCodecID) -> bool {
    matches!(
        codec_id,
        ffi::AV_CODEC_ID_HDMV_PGS_SUBTITLE
            | ffi::AV_CODEC_ID_DVD_SUBTITLE
            | ffi::AV_CODEC_ID_DVB_SUBTITLE
            | ffi::AV_CODEC_ID_XSUB
    )
}

fn count_bitmap_subtitle_streams(path: &Path) -> Result<usize, Box<dyn std::error::Error>> {
    let path_cstr = CString::new(path.to_string_lossy().to_string())?;
    let ictx = AVFormatContextInput::open(path_cstr.as_c_str())?;
    Ok(ictx
        .streams()
        .iter()
        .filter(|st| {
            let cp = st.codecpar();
            cp.codec_type == ffi::AVMEDIA_TYPE_SUBTITLE && is_bitmap_subtitle_codec(cp.codec_id)
        })
        .count())
}

fn count_mov_text_streams(path: &Path) -> Result<usize, Box<dyn std::error::Error>> {
    let path_cstr = CString::new(path.to_string_lossy().to_string())?;
    let ictx = AVFormatContextInput::open(path_cstr.as_c_str())?;
    Ok(ictx
        .streams()
        .iter()
        .filter(|st| {
            let cp = st.codecpar();
            cp.codec_type == ffi::AVMEDIA_TYPE_SUBTITLE && cp.codec_id == ffi::AV_CODEC_ID_MOV_TEXT
        })
        .count())
}

fn probe_duration_ms(path: &Path) -> u64 {
    let path_cstr = CString::new(path.to_string_lossy().to_string()).unwrap();
    let ictx = AVFormatContextInput::open(path_cstr.as_c_str()).unwrap();
    (ictx.duration / 1000).max(0) as u64
}

#[test]
fn cli_converts_bitmap_subs_to_mov_text_and_direct_play() -> Result<(), Box<dyn std::error::Error>>
{
    ensure_ffmpeg_present();

    let tmp = TempDir::new()?;
    let (input, in_dur_ms, used_text_subs) = gen_problem_input_with_bitmap_subs(&tmp);
    let output = tmp.path().join("out_bitmap.mp4");

    // Run the CLI for all Chromecast models
    let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("direct_play_nice"));
    cmd.arg("-s")
        .arg("chromecast_1st_gen,chromecast_2nd_gen,chromecast_ultra")
        .arg(&input)
        .arg(&output);
    cmd.assert().success().stdout(str::is_empty());

    assert!(output.exists(), "output file was not created");

    // Validate via rsmpeg
    let output_cstr = CString::new(output.to_string_lossy().to_string()).unwrap();
    let octx = AVFormatContextInput::open(output_cstr.as_c_str())?;

    let mut saw_v = false;
    let mut saw_a = false;
    let mut saw_s = false;
    let mut width = 0i32;
    let mut height = 0i32;
    let mut fps_num = 0i32;
    let mut fps_den = 1i32;
    let mut level = 0i32;
    let mut pix_fmt = -1i32;

    for st in octx.streams() {
        let par = st.codecpar();
        match par.codec_type {
            t if t == ffi::AVMEDIA_TYPE_VIDEO => {
                saw_v = true;
                assert_eq!(par.codec_id, ffi::AV_CODEC_ID_H264, "video must be H.264");
                width = par.width;
                height = par.height;
                level = par.level;
                pix_fmt = par.format;
                let rate = st.avg_frame_rate;
                fps_num = rate.num;
                fps_den = rate.den;
            }
            t if t == ffi::AVMEDIA_TYPE_AUDIO => {
                saw_a = true;
                assert_eq!(par.codec_id, ffi::AV_CODEC_ID_AAC, "audio must be AAC");
            }
            t if t == ffi::AVMEDIA_TYPE_SUBTITLE => {
                saw_s = true;
                assert_eq!(
                    par.codec_id,
                    ffi::AV_CODEC_ID_MOV_TEXT,
                    "subs must be MOV_TEXT"
                );
            }
            _ => {}
        }
    }

    assert!(
        saw_v && saw_a && saw_s,
        "missing one or more required streams"
    );

    assert!(
        width as u32 <= 1920 && height as u32 <= 1080,
        "resolution too high"
    );
    assert!(level <= 41, "H.264 level too high: {}", level);
    assert_eq!(pix_fmt, ffi::AV_PIX_FMT_YUV420P, "pix fmt must be yuv420p");
    if fps_den != 0 {
        let fps = (fps_num as f64) / (fps_den as f64);
        assert!(fps <= 30.01, "fps too high: {}", fps);
    }

    let out_dur_ms = probe_duration_ms(&output);
    let diff = out_dur_ms.abs_diff(in_dur_ms);
    if !used_text_subs {
        assert!(
            diff <= 200,
            "duration drift too large: in={}ms out={}ms",
            in_dur_ms,
            out_dur_ms
        );
    } else {
        // When we fall back to ASS (text) in the source file, some FFmpeg builds
        // report container duration with significant jitter. We still require the
        // output to be within a reasonable multiple of the input length.
        assert!(
            out_dur_ms <= in_dur_ms.saturating_add(120_000),
            "duration drift too large (text fallback): in={}ms out={}ms",
            in_dur_ms,
            out_dur_ms
        );
    }

    Ok(())
}

#[test]
fn cli_ai_ocr_processes_all_bitmap_subtitle_streams() -> Result<(), Box<dyn std::error::Error>> {
    ensure_ffmpeg_present();

    if env::var("DPN_OCR_AI_E2E").ok().as_deref() != Some("1") {
        eprintln!("Skipping AI all-stream OCR test (set DPN_OCR_AI_E2E=1 to enable).");
        return Ok(());
    }

    let tmp = TempDir::new()?;
    let Some(input) = gen_multi_stream_bitmap_input(&tmp) else {
        eprintln!("No bitmap subtitle encoder available; skipping AI all-stream OCR test.");
        return Ok(());
    };
    let output = tmp.path().join("out_ai_all_streams.mp4");

    let input_bitmap_count = count_bitmap_subtitle_streams(&input)?;
    assert!(
        input_bitmap_count >= 2,
        "expected at least two bitmap subtitle streams, got {}",
        input_bitmap_count
    );

    let run = Command::new(assert_cmd::cargo::cargo_bin!("direct_play_nice"))
        .env("DPN_OCR_FORCE_CPU", "1")
        .env("DPN_OCR_SKIP_CLS", "1")
        .arg("--sub-mode")
        .arg("force")
        .arg("--ocr-engine")
        .arg("pp-ocr-v3")
        .arg("--skip-codec-check")
        .arg(&input)
        .arg(&output)
        .output()?;

    assert!(
        run.status.success(),
        "AI OCR run failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&run.stdout),
        String::from_utf8_lossy(&run.stderr)
    );

    let output_sub_count = count_mov_text_streams(&output)?;
    assert_eq!(
        output_sub_count, input_bitmap_count,
        "expected all bitmap subtitle streams to be OCR-converted ({}), got {}",
        input_bitmap_count, output_sub_count
    );

    Ok(())
}

#[test]
fn cli_ai_ocr_gpu_processes_all_bitmap_subtitle_streams() -> Result<(), Box<dyn std::error::Error>>
{
    ensure_ffmpeg_present();

    if env::var("DPN_OCR_GPU_E2E").ok().as_deref() != Some("1") {
        eprintln!("Skipping GPU OCR test (set DPN_OCR_GPU_E2E=1 to enable).");
        return Ok(());
    }

    let tmp = TempDir::new()?;
    let Some(input) = gen_multi_stream_bitmap_input(&tmp) else {
        eprintln!("No bitmap subtitle encoder available; skipping GPU OCR test.");
        return Ok(());
    };
    let output = tmp.path().join("out_ai_gpu_all_streams.mp4");

    let input_bitmap_count = count_bitmap_subtitle_streams(&input)?;
    assert!(
        input_bitmap_count >= 2,
        "expected at least two bitmap subtitle streams, got {}",
        input_bitmap_count
    );

    let run = Command::new(assert_cmd::cargo::cargo_bin!("direct_play_nice"))
        .env("DPN_OCR_REQUIRE_GPU", "1")
        .env("DPN_OCR_SKIP_CLS", "1")
        .arg("--sub-mode")
        .arg("force")
        .arg("--ocr-engine")
        .arg("auto")
        .arg("--skip-codec-check")
        .arg(&input)
        .arg(&output)
        .output()?;

    assert!(
        run.status.success(),
        "GPU OCR run failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&run.stdout),
        String::from_utf8_lossy(&run.stderr)
    );

    let output_sub_count = count_mov_text_streams(&output)?;
    assert_eq!(
        output_sub_count, input_bitmap_count,
        "expected all bitmap subtitle streams to be OCR-converted ({}), got {}",
        input_bitmap_count, output_sub_count
    );

    Ok(())
}