Repository navigation
Expand file tree
/
Copy pathrecover.rs
More file actions
667 lines (622 loc) · 25.5 KB
/
Copy pathrecover.rs
File metadata and controls
667 lines (622 loc) · 25.5 KB
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
//! A Screen capture writes `unfinished.json` beside its video and audio before its bundle is built
//! and removes it once `scrawl.json` is there: the target, ink, clicks and window log that only
//! lived in memory. If the build dies with the process (#58: transcription crashed on CPUs without
//! AVX-512), the next launch runs `scrawl recover` in a child process, which builds the bundle
//! from those files in place. Each bundle gets one try (`.recovering`), so a crash that happens
//! again can't take every launch down with it.
//!
//! Captures from before the journal (0.3.10 on Windows crashed the same way) left only
//! `recording.mp4` and `audio.wav`. Once those have sat untouched for `ORPHAN_SETTLE` they are
//! rebuilt too, from the video and audio alone: the whole frame, no ink or clicks, keyframes from
//! scene changes and the transcript. A streamed capture's `audio.wav` never exists without a
//! journal: its audio waits under `audio.wav.partial` while it records and until its build writes
//! `unfinished.json`, and a crash while recording or queued is cleaned up by retention, not
//! recovered. A journal whose `audio.wav` is still missing adopts the partial instead.
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use crate::log::scrawl_log;
use crate::model::{
CaptureMode, InteractionEvent, RgbaFrame, Stroke, TargetFrame, TargetInfo, TranscriptData,
};
use crate::windows::{CursorSample, WindowSnapshot};
pub const UNFINISHED: &str = "unfinished.json";
pub const RECOVERING: &str = ".recovering";
/// A journal younger than this may belong to a build still running in another process.
const SETTLE: Duration = Duration::from_secs(15);
/// Video and audio without a journal are left alone until nothing in the bundle changed for this
/// long.
const ORPHAN_SETTLE: Duration = Duration::from_secs(10 * 60);
const VIDEO: &str = "recording.mp4";
const AUDIO: &str = "audio.wav";
/// Where a capture streams its audio while it records. `audio.wav` appears (by rename) only once
/// its build writes `unfinished.json`, so a capture still recording or waiting to be written never
/// looks like an orphan owed a rebuild.
pub const PARTIAL_AUDIO: &str = "audio.wav.partial";
/// The movie starts this much after the audio at most (measured: 50–500 ms).
const MAX_VIDEO_OFFSET_MS: u64 = 1_000;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Unfinished {
pub target: TargetInfo,
pub duration_ms: u64,
#[serde(default)]
pub video: Option<String>,
#[serde(default)]
pub video_offset_ms: u64,
#[serde(default)]
pub strokes: Vec<Stroke>,
#[serde(default)]
pub events: Vec<InteractionEvent>,
#[serde(default)]
pub note: Option<String>,
#[serde(default)]
pub windows: Vec<WindowSnapshot>,
#[serde(default)]
pub cursor: Vec<CursorSample>,
}
pub fn write(bundle_dir: &Path, unfinished: &Unfinished) {
let written = serde_json::to_vec(unfinished)
.map_err(anyhow::Error::from)
.and_then(|bytes| Ok(std::fs::write(bundle_dir.join(UNFINISHED), bytes)?));
if let Err(error) = written {
scrawl_log(format!("recover: could not write {UNFINISHED}: {error:#}"));
}
}
pub fn finished(bundle_dir: &Path) {
let _ = std::fs::remove_file(bundle_dir.join(UNFINISHED));
let _ = std::fs::remove_file(bundle_dir.join(RECOVERING));
}
pub fn read(bundle_dir: &Path) -> Result<Unfinished> {
let path = bundle_dir.join(UNFINISHED);
serde_json::from_slice(
&std::fs::read(&path).with_context(|| format!("Could not read {}", path.display()))?,
)
.with_context(|| format!("Invalid {}", path.display()))
}
/// A bundle with a Screen capture's video and audio and no journal: its build never ran. A phone
/// recording's (`timeline.json`) is left to the phone, which sends it again. A capture still
/// recording has `audio.wav.partial`, not `audio.wav`, so it is never one of these.
fn orphaned(dir: &Path) -> bool {
dir.join(VIDEO).is_file()
&& dir.join(AUDIO).is_file()
&& !dir.join(UNFINISHED).exists()
&& !dir.join("timeline.json").exists()
}
/// Whether `dir` has a whole manifest. Builds publish it last and atomically; an empty or
/// partial one (left by builds that wrote it in place) doesn't count.
fn built(dir: &Path) -> bool {
std::fs::read(dir.join("scrawl.json")).is_ok_and(|bytes| {
serde_json::from_slice::<serde_json::Value>(&bytes).is_ok_and(|value| value.is_object())
})
}
/// Whether a build is still owed to `dir`: nothing built it and it hasn't been tried.
pub fn owed(dir: &Path) -> bool {
!dir.join(RECOVERING).exists()
&& (dir.join(UNFINISHED).is_file() || orphaned(dir))
&& !built(dir)
}
fn untouched_for(path: &Path, now: SystemTime, age: Duration) -> bool {
std::fs::metadata(path)
.and_then(|m| m.modified())
.is_ok_and(|at| now.duration_since(at).is_ok_and(|ago| ago >= age))
}
/// Bundles in `captures` whose build never finished and hasn't been retried.
pub fn pending(captures: &Path, now: SystemTime) -> Vec<PathBuf> {
let Ok(entries) = std::fs::read_dir(captures) else {
return Vec::new();
};
let mut dirs: Vec<PathBuf> = entries
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|dir| {
dir.extension().is_some_and(|ext| ext == "scrawl")
&& owed(dir)
&& if orphaned(dir) {
[dir.clone(), dir.join(VIDEO), dir.join(AUDIO)]
.iter()
.all(|path| untouched_for(path, now, ORPHAN_SETTLE))
} else {
untouched_for(&dir.join(UNFINISHED), now, SETTLE)
}
})
.collect();
dirs.sort();
dirs
}
/// What an orphaned bundle's build would have been given: its whole video as a Screen capture.
pub fn orphan_recipe(video: &crate::helper::Probe, audio_ms: Option<u64>) -> Unfinished {
// The audio runs from the start of the capture, the movie from its first frame.
let offset = audio_ms
.map_or(0, |audio| audio.saturating_sub(video.duration_ms))
.min(MAX_VIDEO_OFFSET_MS);
Unfinished {
target: TargetInfo {
mode: CaptureMode::Display,
app: None,
bundle_id: None,
window_title: None,
window_id: None,
display_id: 0,
frame: TargetFrame {
x: 0.0,
y: 0.0,
width: f64::from(video.width.max(1)),
height: f64::from(video.height.max(1)),
scale: 1.0,
},
},
duration_ms: audio_ms.unwrap_or(0).max(offset + video.duration_ms),
video: Some(VIDEO.into()),
video_offset_ms: offset,
strokes: Vec::new(),
events: Vec::new(),
note: None,
windows: Vec::new(),
cursor: Vec::new(),
}
}
/// The steps that read media, swapped out in tests.
#[derive(Clone, Copy)]
pub struct Media {
pub probe: fn(&Path) -> Result<crate::helper::Probe>,
pub frames: fn(&Path, crate::helper::FrameTimes, u32) -> Result<Vec<RgbaFrame>>,
pub transcribe: fn(Option<&Path>, Option<&crate::audio::RecordedAudio>) -> TranscriptData,
}
impl Media {
pub const SYSTEM: Media = Media {
probe: crate::helper::probe,
frames: crate::helper::frames,
transcribe: crate::transcribe::transcribe,
};
}
/// Builds one bundle in place from its journal, or from its video and audio alone, and marks it
/// tried first so a crash here isn't repeated at every launch.
pub fn rebuild(dir: &Path, media: &Media) -> Result<String> {
anyhow::ensure!(
!built(dir),
"{} is already built; `scrawl reprocess` rebuilds it into a new bundle",
dir.display()
);
let _ = std::fs::write(dir.join(RECOVERING), "");
scrawl_log(format!("recover: rebuilding {}", dir.display()));
let result = if dir.join(UNFINISHED).is_file() {
read(dir).and_then(|unfinished| {
crate::pipeline::rebuild_screen_bundle_with(dir, unfinished, None, media)
})
} else if orphaned(dir) {
let probe = (media.probe)(&dir.join(VIDEO));
let audio_ms = std::fs::read(dir.join(AUDIO))
.ok()
.and_then(|wav| crate::audio::recorded_audio_from_wav(wav).ok())
.map(|audio| audio.duration_ms());
probe.and_then(|probe| {
crate::pipeline::rebuild_screen_bundle_with(
dir,
orphan_recipe(&probe, audio_ms),
Some(None),
media,
)
})
} else {
Err(anyhow::anyhow!(
"{} has neither {UNFINISHED} nor {VIDEO} and {AUDIO}",
dir.display()
))
};
match &result {
Ok(_) => {
finished(dir);
scrawl_log(format!("recover: rebuilt {}", dir.display()));
}
Err(error) => scrawl_log(format!(
"recover: could not rebuild {}: {error:#}",
dir.display()
)),
}
result
}
/// At launch: rebuilds unfinished bundles in a child process, so a crash there leaves the app up.
pub fn start() {
let captures = crate::handoff::default_captures_dir();
if pending(&captures, SystemTime::now()).is_empty() {
return;
}
let _ = std::thread::Builder::new()
.name("scrawl-recover".into())
.spawn(move || {
let Ok(exe) = std::env::current_exe() else {
return;
};
let mut command = std::process::Command::new(exe);
command
.arg("recover")
.arg("--captures")
.arg(&captures)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
#[cfg(target_os = "windows")]
{
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
command.creation_flags(CREATE_NO_WINDOW);
}
match command.status() {
Ok(status) => scrawl_log(format!("recover: finished ({status})")),
Err(error) => scrawl_log(format!("recover: could not start: {error}")),
}
});
}
/// `scrawl recover`: rebuilds each pending bundle once, in place.
pub fn run(captures: &Path) -> Vec<(PathBuf, Result<String>)> {
pending(captures, SystemTime::now())
.into_iter()
.map(|dir| {
let result = rebuild(&dir, &Media::SYSTEM);
(dir, result)
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn temp_dir(name: &str) -> PathBuf {
let dir =
std::env::temp_dir().join(format!("scrawl-recover-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn unfinished() -> Unfinished {
serde_json::from_value(serde_json::json!({
"target": {
"mode": "display",
"displayId": 1,
"frame": { "x": 0.0, "y": 0.0, "width": 1440.0, "height": 900.0, "scale": 2.0 },
},
"durationMs": 4200,
"video": "recording.mp4",
}))
.unwrap()
}
#[test]
fn a_bundle_without_its_manifest_is_rebuilt_once_after_it_settles() {
let captures = temp_dir("pending");
let bundle = |name: &str| {
let dir = captures.join(name);
std::fs::create_dir_all(&dir).unwrap();
write(&dir, &unfinished());
dir
};
let crashed = bundle("a.scrawl");
let built = bundle("b.scrawl");
std::fs::write(built.join("scrawl.json"), "{}").unwrap();
let tried = bundle("c.scrawl");
std::fs::write(tried.join(RECOVERING), "").unwrap();
std::fs::create_dir_all(captures.join("d.scrawl")).unwrap();
let now = SystemTime::now();
assert!(pending(&captures, now).is_empty(), "still settling");
let later = now + SETTLE + Duration::from_secs(1);
assert_eq!(pending(&captures, later), vec![crashed.clone()]);
assert_eq!(read(&crashed).unwrap(), unfinished());
finished(&crashed);
assert!(pending(&captures, later).is_empty());
}
const W: u32 = 320;
const H: u32 = 192;
const MOVIE_MS: u64 = 3_000;
/// Grey for the first half, blue for the second: one scene change at 1.5 s.
fn colour_at(ms: u64) -> [u8; 3] {
if ms < MOVIE_MS / 2 {
[200, 200, 200]
} else {
[30, 60, 220]
}
}
/// What a 0.3.10 capture left: its video and audio, nothing else.
fn orphan(captures: &Path, name: &str) -> PathBuf {
let dir = captures.join(name);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join(VIDEO), b"movie").unwrap();
let tone: Vec<f32> = (0..16_000 * 3 + 1_600)
.map(|i| (i as f32 * 0.05).sin() * 0.2)
.collect();
let wav = crate::audio::encode_wav_16k(&tone).unwrap();
std::fs::write(dir.join(AUDIO), wav).unwrap();
dir
}
fn fake_probe(_: &Path) -> Result<crate::helper::Probe> {
Ok(serde_json::from_value(serde_json::json!({
"durationMs": MOVIE_MS, "width": W, "height": H,
}))?)
}
fn fake_frames(
_: &Path,
times: crate::helper::FrameTimes,
max_edge: u32,
) -> Result<Vec<RgbaFrame>> {
let times: Vec<u64> = match times {
crate::helper::FrameTimes::Every(step) => {
(0..MOVIE_MS).step_by(step as usize).collect()
}
crate::helper::FrameTimes::At(at) => at.to_vec(),
};
let (w, h) = if max_edge == 0 || max_edge >= W {
(W, H)
} else {
(max_edge, H * max_edge / W)
};
Ok(times
.into_iter()
.map(|t| {
let [r, g, b] = colour_at(t.min(MOVIE_MS - 1));
RgbaFrame::new(t, w, h, [r, g, b, 255].repeat((w * h) as usize))
})
.collect())
}
fn fake_transcript(
_: Option<&Path>,
_: Option<&crate::audio::RecordedAudio>,
) -> TranscriptData {
TranscriptData {
source: "test".into(),
text: "The login page. Now the settings are blue.".into(),
segments: vec![
crate::model::TranscriptSegment {
t0: 100,
t1: 1_200,
text: "The login page.".into(),
},
crate::model::TranscriptSegment {
t0: 1_600,
t1: 2_900,
text: "Now the settings are blue.".into(),
},
],
..Default::default()
}
}
const FAKE: Media = Media {
probe: fake_probe,
frames: fake_frames,
transcribe: fake_transcript,
};
fn assert_rebuilt(dir: &Path) -> crate::model::ScrawlBundle {
let bundle: crate::model::ScrawlBundle =
serde_json::from_slice(&std::fs::read(dir.join("scrawl.json")).unwrap()).unwrap();
assert!(!bundle.keyframes.is_empty());
for keyframe in &bundle.keyframes {
assert!(dir.join(&keyframe.file).is_file(), "{}", keyframe.file);
}
assert!(dir.join(&bundle.contact_sheet).is_file());
assert!(dir.join("summary.md").is_file());
assert_eq!(bundle.video.as_deref(), Some(VIDEO));
assert_eq!(bundle.audio.as_deref(), Some(AUDIO));
assert_eq!(bundle.target.mode, CaptureMode::Display);
assert_eq!(
(bundle.target.frame.width, bundle.target.frame.height),
(f64::from(W), f64::from(H))
);
assert!(bundle.autocrop.is_none(), "the whole frame, not a crop");
assert!(bundle.strokes.is_empty() && bundle.events.is_empty());
assert!(!dir.join(RECOVERING).exists() && !dir.join(UNFINISHED).exists());
assert!(!owed(dir));
bundle
}
#[test]
fn recover_picks_up_old_video_and_audio_without_a_journal_but_never_a_live_capture() {
let captures = temp_dir("orphans");
let lost = orphan(&captures, "a.scrawl");
// Recording now: the movie grows and the audio streams to its partial.
let live = captures.join("b.scrawl");
std::fs::create_dir_all(&live).unwrap();
std::fs::write(live.join(VIDEO), b"movie").unwrap();
std::fs::write(live.join(PARTIAL_AUDIO), b"half a wav").unwrap();
let built = orphan(&captures, "c.scrawl");
std::fs::write(built.join("scrawl.json"), "{}").unwrap();
let tried = orphan(&captures, "d.scrawl");
std::fs::write(tried.join(RECOVERING), "").unwrap();
// Since 0.3.11 the journal follows the audio, and the journal decides.
let journaled = orphan(&captures, "e.scrawl");
write(&journaled, &unfinished());
let phone = orphan(&captures, "f.scrawl");
std::fs::write(phone.join("timeline.json"), "{}").unwrap();
let now = SystemTime::now();
assert_eq!(
pending(&captures, now + SETTLE * 2),
vec![journaled.clone()]
);
let later = now + ORPHAN_SETTLE + Duration::from_secs(1);
assert_eq!(pending(&captures, later), vec![lost.clone(), journaled]);
assert!(owed(&lost) && !owed(&live) && !owed(&built) && !owed(&tried) && !owed(&phone));
}
#[test]
fn a_capture_that_has_not_been_journaled_is_never_owed_a_rebuild() {
let captures = temp_dir("streaming");
let dir = captures.join("live.scrawl");
std::fs::create_dir_all(&dir).unwrap();
// Recording, or stopped and waiting for its build: the movie and the
// audio under its partial name, and no journal.
std::fs::write(dir.join(VIDEO), b"movie").unwrap();
std::fs::write(dir.join(PARTIAL_AUDIO), b"half a wav").unwrap();
assert!(
!owed(&dir),
"a movie and a partial WAV are a capture that has not stopped its build"
);
assert!(
pending(&captures, SystemTime::now() + ORPHAN_SETTLE * 2).is_empty(),
"never rebuilt, however long it settles"
);
// A build publishes `audio.wav` only after journaling the capture: a
// movie with a finished audio and no journal is the recovery case.
let mut audio = crate::audio::RecordedAudio::on_disk(
&dir.join(PARTIAL_AUDIO),
16_000,
16_000,
0,
Vec::new(),
);
assert!(audio.publish_audio(&dir));
assert!(
owed(&dir),
"audio.wav without a journal is exactly what recovery rebuilds"
);
}
#[test]
fn a_journaled_capture_adopts_its_streamed_audio() {
let captures = temp_dir("adopt");
let dir = captures.join("streamed.scrawl");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join(VIDEO), b"movie").unwrap();
let tone: Vec<f32> = (0..16_000 * 3 + 1_600)
.map(|i| (i as f32 * 0.05).sin() * 0.2)
.collect();
std::fs::write(
dir.join(PARTIAL_AUDIO),
crate::audio::encode_wav_16k(&tone).unwrap(),
)
.unwrap();
write(&dir, &unfinished());
// The build died after journaling, before the audio's final name.
rebuild(&dir, &FAKE).unwrap();
let bundle: crate::model::ScrawlBundle =
serde_json::from_slice(&std::fs::read(dir.join("scrawl.json")).unwrap()).unwrap();
assert_eq!(bundle.audio.as_deref(), Some(AUDIO));
assert!(dir.join(AUDIO).is_file());
assert!(
!dir.join(PARTIAL_AUDIO).exists(),
"the journal adopted the streamed audio"
);
assert!(!dir.join(UNFINISHED).exists());
}
#[test]
fn recover_rebuilds_a_bundle_from_its_video_and_audio_alone() {
let captures = temp_dir("rebuild");
let dir = orphan(&captures, "lost.scrawl");
rebuild(&dir, &FAKE).unwrap();
let bundle = assert_rebuilt(&dir);
assert!(
bundle.keyframes.iter().any(|k| k.t >= MOVIE_MS / 2),
"the scene change gets a keyframe: {:?}",
bundle.keyframes.iter().map(|k| k.t).collect::<Vec<_>>()
);
assert!(bundle.transcript.text.contains("settings are blue"));
// The audio is 3.1 s, the movie 3 s: it started 100 ms in.
assert_eq!((bundle.duration_ms, bundle.video_offset_ms), (3_100, 100));
assert!(
rebuild(&dir, &FAKE).is_err(),
"built bundles are left alone"
);
}
/// A macOS movie's final frame is held to the recording's stop, a little past the end of the
/// capture: the rebuilt bundle has no frame after its end, and the movie stays on its offset.
#[test]
fn a_movie_held_past_the_capture_s_end_gives_no_frames_after_it() {
let captures = temp_dir("held");
let dir = orphan(&captures, "held.scrawl");
let mut journal = unfinished();
(journal.duration_ms, journal.video_offset_ms) = (2_000, 200);
write(&dir, &journal);
rebuild(&dir, &FAKE).unwrap();
let bundle: crate::model::ScrawlBundle =
serde_json::from_slice(&std::fs::read(dir.join("scrawl.json")).unwrap()).unwrap();
let times: Vec<u64> = bundle.keyframes.iter().map(|k| k.t).collect();
assert_eq!((bundle.duration_ms, bundle.video_offset_ms), (2_000, 200));
assert!(times.iter().all(|&t| t <= 2_000), "{times:?}");
assert!(
times.iter().any(|&t| t >= 1_700),
"the scene change 1.5 s into the movie is 1.7 s into the capture: {times:?}"
);
}
/// A build that stops before its last file leaves no manifest, so it is still owed; so is a
/// bundle whose manifest an older build left empty or cut short.
#[test]
fn a_build_that_stops_early_or_a_partial_manifest_is_still_owed() {
let captures = temp_dir("early");
let dir = orphan(&captures, "early.scrawl");
write(&dir, &unfinished());
std::fs::create_dir_all(dir.join("summary.md")).unwrap();
assert!(
crate::pipeline::rebuild_screen_bundle_with(&dir, unfinished(), Some(None), &FAKE)
.is_err()
);
assert!(!dir.join("scrawl.json").exists(), "no manifest yet");
assert!(dir.join(UNFINISHED).is_file());
assert!(owed(&dir));
std::fs::remove_dir_all(dir.join("summary.md")).unwrap();
for partial in ["", "{\"version\": 1, \"id\""] {
std::fs::write(dir.join("scrawl.json"), partial).unwrap();
assert!(owed(&dir), "{partial:?}");
}
// Rebuilt from the video and audio alone, as `assert_rebuilt` expects.
std::fs::remove_file(dir.join(UNFINISHED)).unwrap();
assert!(owed(&dir));
rebuild(&dir, &FAKE).unwrap();
assert_rebuilt(&dir);
}
#[test]
fn recover_tries_an_orphan_once_and_retries_only_when_asked() {
let captures = temp_dir("once");
let dir = orphan(&captures, "broken.scrawl");
fn no_probe(_: &Path) -> Result<crate::helper::Probe> {
anyhow::bail!("unreadable movie")
}
let broken = Media {
probe: no_probe,
..FAKE
};
assert!(rebuild(&dir, &broken).is_err());
assert!(dir.join(RECOVERING).exists() && !owed(&dir));
let later = SystemTime::now() + ORPHAN_SETTLE * 2;
assert!(pending(&captures, later).is_empty());
rebuild(&dir, &FAKE).unwrap();
assert_rebuilt(&dir);
}
/// A real movie through the platform's decoder: Media Foundation on Windows, AVFoundation
/// via `scrawl-helper` on a Mac (with ffmpeg on the PATH to make the movie).
#[test]
fn recover_rebuilds_a_real_movie() {
let captures = temp_dir("real");
let dir = orphan(&captures, "real.scrawl");
let frames: Vec<(u64, [u8; 3])> = (0..MOVIE_MS)
.step_by(100)
.map(|t| (t, colour_at(t)))
.collect();
let video = dir.join(VIDEO);
let _ = std::fs::remove_file(&video);
#[cfg(target_os = "windows")]
crate::win::media::write_test_movie(&video, W, H, &frames).unwrap();
#[cfg(not(target_os = "windows"))]
{
let _ = &frames;
let made = std::process::Command::new("ffmpeg")
.args(["-v", "error", "-f", "lavfi", "-i"])
.arg(format!(
"color=c=0xc8c8c8:s={W}x{H}:d=1.5:r=10[a];color=c=0x1e3cdc:s={W}x{H}:d=1.5:r=10[b];[a][b]concat=n=2:v=1"
))
.args(["-c:v", "libx264", "-pix_fmt", "yuv420p"])
.arg(&video)
.status()
.is_ok_and(|status| status.success());
if !made || crate::helper::path().is_err() {
eprintln!("skipped: needs ffmpeg and scrawl-helper");
return;
}
}
let media = Media {
transcribe: fake_transcript,
..Media::SYSTEM
};
rebuild(&dir, &media).unwrap();
let bundle = assert_rebuilt(&dir);
let png = std::fs::read(dir.join(&bundle.keyframes.last().unwrap().file)).unwrap();
let last = crate::render::decode_png(std::io::Cursor::new(png)).unwrap();
let i = ((last.height - 4) * last.width + last.width / 2) as usize * 4;
let (r, b) = (last.rgba[i], last.rgba[i + 2]);
assert!(
b > r + 80,
"the last keyframe shows the blue scene: {r} {b}"
);
}
}