Repository navigation
Expand file tree
/
Copy pathpipeline.rs
More file actions
1365 lines (1314 loc) · 49 KB
/
Copy pathpipeline.rs
File metadata and controls
1365 lines (1314 loc) · 49 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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result};
use crate::audio::{self, RecordedAudio};
use crate::autocrop;
use crate::capture;
use crate::handoff;
use crate::helper;
use crate::keyframes::select_keyframes;
use crate::model::{
self, CaptureMode, DeviceInfo, InteractionEvent, Mark, RgbaFrame, SCALE, ScrawlBundle, Shape,
Stroke, TargetFrame, TargetInfo, TranscriptData, TranscriptSegment, WordTiming,
keyframe_budget,
};
use crate::recover;
use crate::render::{self, render_synthetic_demo_frame};
use crate::sketch::{marks_of, summary_markdown};
use crate::speech_model;
use crate::transcribe;
use crate::windows;
pub fn now_epoch_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64
}
pub fn make_bundle_id() -> String {
use std::sync::atomic::{AtomicU64, Ordering};
// Two IDs in the same millisecond (parallel tests, overlapping ingests) must still differ.
static COUNT: AtomicU64 = AtomicU64::new(0);
let ms = now_epoch_ms();
let pid = std::process::id();
match COUNT.fetch_add(1, Ordering::Relaxed) {
0 => format!("scrawl-{ms}-{pid:x}"),
n => format!("scrawl-{ms}-{pid:x}-{n}"),
}
}
/// Matches full-resolution decoded frames back to selected keyframes by timestamp (within 250ms),
/// so a single frame decode failure only leaves that one keyframe at candidate resolution.
fn merge_full_keyframes(
selected: Vec<(model::Keyframe, RgbaFrame)>,
full: Vec<RgbaFrame>,
) -> (Vec<(model::Keyframe, RgbaFrame)>, usize) {
let mut pool: Vec<Option<RgbaFrame>> = full.into_iter().map(Some).collect();
let mut matched = 0;
let merged = selected
.into_iter()
.map(|(key, fallback)| {
let best = pool
.iter()
.enumerate()
.filter_map(|(idx, f)| f.as_ref().map(|frame| (idx, frame.t_ms.abs_diff(key.t))))
.filter(|&(_, diff)| diff <= 250)
.min_by_key(|&(_, diff)| diff)
.map(|(idx, _)| idx);
if let Some(idx) = best
&& let Some(mut full_frame) = pool[idx].take()
{
full_frame.t_ms = key.t;
matched += 1;
(key, full_frame)
} else {
(key, fallback)
}
})
.collect();
(merged, matched)
}
/// Per-stage timing breakdown logged on every finish (`finish timings: ...`).
#[derive(Clone, Copy, Debug, Default)]
pub struct StageTimings {
pub started_at: Option<std::time::Instant>,
pub stop_ms: Option<u64>,
pub audio_ms: Option<u64>,
pub candidates_ms: Option<u64>,
pub transcribe_ms: Option<u64>,
}
/// Pre-rendered keyframe visuals and encoded PNGs computed while transcription is running.
pub struct PreparedVisuals {
pub keyframes: Vec<model::Keyframe>,
pub autocrop: Option<model::AutocropInfo>,
pub contact_sheet_png: Vec<u8>,
pub frame_pngs: Vec<(String, Vec<u8>)>,
pub full_sheet_png: Option<Vec<u8>>,
pub full_frame_pngs: Vec<(String, Vec<u8>)>,
}
#[allow(clippy::too_many_arguments)]
pub fn prepare_visuals(
selected: Vec<(model::Keyframe, RgbaFrame)>,
baseline: Option<&RgbaFrame>,
crop_settings: Option<&autocrop::Settings>,
target: &TargetInfo,
duration_ms: u64,
strokes: &[Stroke],
marks: &[Mark],
events: &[InteractionEvent],
activity: &windows::ActivityLog,
) -> Option<PreparedVisuals> {
if selected.is_empty() {
return None;
}
let (mut annotated_frames, mut cropped) = autocrop::annotate_and_crop(
selected,
baseline,
crop_settings,
target,
duration_ms,
strokes,
marks,
events,
&activity.windows,
&activity.cursor,
);
let keyframes: Vec<model::Keyframe> =
annotated_frames.iter().map(|(kf, _)| kf.clone()).collect();
let (full_sheet, contact_sheet) = std::thread::scope(|scope| {
let full_handle = cropped.as_ref().map(|(_, full)| {
scope.spawn(|| render::render_contact_sheet_for_duration(duration_ms, full))
});
let sheet = render::render_contact_sheet_for_duration(duration_ms, &annotated_frames);
(full_handle.and_then(|h| h.join().ok()), sheet)
});
render::stamp_keyframe_badges(&mut annotated_frames);
if let Some((_, full)) = &mut cropped {
render::stamp_keyframe_badges(full);
}
let contact_sheet_png = render::encode_png(&contact_sheet).ok()?;
let frame_pngs: Vec<(String, Vec<u8>)> = std::thread::scope(|scope| {
let workers: Vec<_> = annotated_frames
.iter()
.map(|(kf, frame)| {
scope.spawn(move || render::encode_png(frame).ok().map(|b| (kf.file.clone(), b)))
})
.collect();
workers
.into_iter()
.map(|w| w.join().ok().flatten())
.collect::<Option<Vec<_>>>()
})?;
let (autocrop, full_sheet_png, full_frame_pngs) = match (cropped, full_sheet) {
(Some((info, full)), Some(sheet)) => {
let sheet_png = render::encode_png(&sheet).ok()?;
let full_pngs: Vec<(String, Vec<u8>)> = std::thread::scope(|scope| {
let workers: Vec<_> = full
.iter()
.map(|(kf, frame)| {
scope.spawn(move || {
let name = std::path::Path::new(&kf.file)
.file_name()
.and_then(|n| n.to_str())?
.to_owned();
render::encode_png(frame).ok().map(|b| (name, b))
})
})
.collect();
workers
.into_iter()
.map(|w| w.join().ok().flatten())
.collect::<Option<Vec<_>>>()
})?;
(Some(info), Some(sheet_png), full_pngs)
}
_ => (None, None, Vec::new()),
};
Some(PreparedVisuals {
keyframes,
autocrop,
contact_sheet_png,
frame_pngs,
full_sheet_png,
full_frame_pngs,
})
}
/// What a source other than this Mac's screen adds to a bundle.
#[derive(Default)]
pub struct SourceExtras {
pub source: Option<String>,
pub device: Option<DeviceInfo>,
/// What the recorded app said about itself: values at the start, their changes, and screens.
pub context: std::collections::BTreeMap<String, String>,
pub context_changes: Vec<model::ContextChange>,
pub screens: Vec<model::ScreenSpan>,
/// Screen mode's window and cursor log.
pub activity: windows::ActivityLog,
/// Time-only markers (ms); each becomes a `Flag` mark with keyframe priority.
pub flags: Vec<u64>,
/// When the video starts on the bundle's clock (ms).
pub video_offset_ms: u64,
/// Screen-capture auto-crop: `None` follows the config, `Some(None)` is off.
pub autocrop: Option<Option<autocrop::Settings>>,
/// Whether the `agentContext` summary format is enabled (`None` reads `handoff::engine_config()`).
pub agent_context: Option<bool>,
/// Why there is no picture of the screen (`ScreenRecording::no_screen`).
pub no_screen: Option<String>,
/// Where the capture's audio stops on the bundle's clock (ms), when Hex had to stop
/// keeping it (a streamed capture's disk guard, or a failed write).
pub audio_stopped_at_ms: Option<u64>,
/// Decodes the chosen keyframes again at full quality, for sources that select on small
/// candidate frames (phone movies).
pub full_frames: Option<FullFrames>,
pub prepared: Option<PreparedVisuals>,
pub timings: StageTimings,
}
/// Decodes frames at these times at full quality.
pub type FullFrames = Box<dyn Fn(&[u64]) -> Result<Vec<RgbaFrame>>>;
/// Keyframes at native size from a Mac screen recording, whose clock starts `offset_ms` into the
/// capture. Each frame comes back stamped with the capture time it was asked for.
pub fn movie_keyframes(movie: PathBuf, offset_ms: u64) -> FullFrames {
movie_keyframes_with_cache(movie, offset_ms, Vec::new())
}
fn movie_keyframes_with_cache(
movie: PathBuf,
offset_ms: u64,
predecoded: Vec<RgbaFrame>,
) -> FullFrames {
let cache = std::sync::Mutex::new(predecoded);
Box::new(move |times: &[u64]| {
let mut pool = cache
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let mut out = Vec::with_capacity(times.len());
let mut missing = Vec::new();
for &t in times {
if let Some(idx) = pool.iter().position(|f| f.t_ms == t) {
out.push(pool.swap_remove(idx));
} else {
missing.push(t);
}
}
drop(pool);
if !missing.is_empty() {
out.extend(movie_frames_at(&movie, &missing, offset_ms, 0)?);
}
Ok(out)
})
}
/// Frames of a movie whose clock starts `offset_ms` into the bundle's, at bundle times.
pub fn movie_frames_at(
movie: &Path,
times: &[u64],
offset_ms: u64,
max_edge: u32,
) -> Result<Vec<RgbaFrame>> {
movie_frames_at_with(helper::frames, movie, times, offset_ms, max_edge)
}
fn movie_frames_at_with(
decode: fn(&Path, helper::FrameTimes, u32) -> Result<Vec<RgbaFrame>>,
movie: &Path,
times: &[u64],
offset_ms: u64,
max_edge: u32,
) -> Result<Vec<RgbaFrame>> {
let at: Vec<u64> = times.iter().map(|t| t.saturating_sub(offset_ms)).collect();
let mut frames = decode(movie, helper::FrameTimes::At(&at), max_edge)?;
// The helper stamps each frame with the time it was asked for, clamped to the movie (the
// last keyframe can fall just past its end); map it back to the bundle time.
for frame in &mut frames {
if let Some(i) = (0..at.len()).min_by_key(|&i| at[i].abs_diff(frame.t_ms)) {
frame.t_ms = times[i];
}
}
Ok(frames)
}
/// Core pipeline that turns raw frames, strokes, events, and audio/transcript into a complete `.scrawl` bundle on disk.
#[allow(clippy::too_many_arguments)]
///
/// The recording's candidate frames are small; the keyframes are decoded again from its video at
/// full size, falling back to the candidates if that fails.
pub fn finalize_capture_bundle(
bundle_dir: &Path,
target: TargetInfo,
recording: capture::ScreenRecording,
strokes: Vec<Stroke>,
events: Vec<InteractionEvent>,
recorded_audio: Option<RecordedAudio>,
note: Option<String>,
activity: windows::ActivityLog,
) -> Result<(PathBuf, ScrawlBundle, String)> {
finalize_capture_bundle_with(
bundle_dir,
target,
recording,
strokes,
events,
recorded_audio,
note,
activity,
None,
)
}
#[allow(clippy::too_many_arguments)]
pub fn finalize_capture_bundle_with(
bundle_dir: &Path,
target: TargetInfo,
recording: capture::ScreenRecording,
strokes: Vec<Stroke>,
events: Vec<InteractionEvent>,
recorded_audio: Option<RecordedAudio>,
note: Option<String>,
activity: windows::ActivityLog,
transcriber: Option<&dyn transcribe::Transcriber>,
) -> Result<(PathBuf, ScrawlBundle, String)> {
finalize_capture_bundle_with_flags(
bundle_dir,
target,
recording,
strokes,
events,
Vec::new(),
recorded_audio,
note,
activity,
transcriber,
)
}
#[allow(clippy::too_many_arguments)]
pub fn finalize_capture_bundle_with_flags(
bundle_dir: &Path,
target: TargetInfo,
recording: capture::ScreenRecording,
strokes: Vec<Stroke>,
events: Vec<InteractionEvent>,
flags: Vec<u64>,
recorded_audio: Option<RecordedAudio>,
note: Option<String>,
activity: windows::ActivityLog,
transcriber: Option<&dyn transcribe::Transcriber>,
) -> Result<(PathBuf, ScrawlBundle, String)> {
finalize_capture_bundle_for_config(
bundle_dir,
target,
recording,
strokes,
events,
flags,
recorded_audio,
note,
activity,
transcriber,
None,
)
}
#[allow(clippy::too_many_arguments)]
pub fn finalize_capture_bundle_for_config(
bundle_dir: &Path,
target: TargetInfo,
recording: capture::ScreenRecording,
strokes: Vec<Stroke>,
events: Vec<InteractionEvent>,
flags: Vec<u64>,
recorded_audio: Option<RecordedAudio>,
note: Option<String>,
activity: windows::ActivityLog,
transcriber: Option<&dyn transcribe::Transcriber>,
engine_cfg: Option<&handoff::EngineConfig>,
) -> Result<(PathBuf, ScrawlBundle, String)> {
let started_at = activity
.stop_started
.unwrap_or_else(std::time::Instant::now);
let stop_ms = activity.stop_ms;
let capture::ScreenRecording {
frames,
video: movie,
duration_ms,
no_screen,
} = recording;
// A capture that streamed its samples to a partial file already has the
// audio: encoding an empty recording here would replace it with a 44-byte
// one. `settle_streamed_audio` publishes it after the journal is written.
if let Some(ref audio) = recorded_audio
&& !audio.is_on_disk()
&& let Ok(wav_bytes) = audio.wav_bytes_16k()
&& !wav_bytes.is_empty()
{
let wav_path = bundle_dir.join("audio.wav");
let _ = std::fs::create_dir_all(bundle_dir);
let _ = crate::routing::undo::write_private(&wav_path, &wav_bytes);
}
let wav_path = bundle_dir.join("audio.wav");
let journal = |video: Option<&Path>, video_offset_ms: u64| {
recover::write(
bundle_dir,
&recover::Unfinished {
target: target.clone(),
duration_ms,
video: video
.and_then(|v| v.file_name())
.map(|name| name.to_string_lossy().into_owned()),
video_offset_ms,
strokes: strokes.clone(),
events: events.clone(),
note: note.clone(),
windows: activity.windows.clone(),
cursor: activity.cursor.clone(),
},
);
};
// The movie may still be finishing: the journal guesses its start until it is done.
let hint = movie
.as_ref()
.map(|m| (m.path().to_path_buf(), m.offset_hint_ms()));
// The journal comes first: a movie and a finished `audio.wav` with no
// journal is what recovery rebuilds, so the streamed audio may only take
// its final name once this bundle is journaled.
journal(
hint.as_ref().map(|(path, _)| path.as_path()),
hint.as_ref().map_or(0, |h| h.1),
);
let recorded_audio = settle_streamed_audio(bundle_dir, recorded_audio, &wav_path)?;
let has_wav = wav_path.exists();
let crop_settings = (target.mode == CaptureMode::Display)
.then(|| match engine_cfg {
Some(cfg) => autocrop::Settings::from_engine_config(cfg),
None => autocrop::Settings::configured(),
})
.flatten();
let agent_context = engine_cfg.map(|cfg| cfg.experiment(handoff::AGENT_CONTEXT));
let mut finished = None;
let ((transcript, transcribe_ms), (predecoded, prepared)) = std::thread::scope(|scope| {
let transcribe_handle = scope.spawn(|| {
let t0 = std::time::Instant::now();
let tr = match transcriber {
Some(transcriber) => transcribe::transcribe_with(
has_wav.then_some(wav_path.as_path()),
recorded_audio.as_ref(),
transcriber,
),
None => transcribe::transcribe(
has_wav.then_some(wav_path.as_path()),
recorded_audio.as_ref(),
),
};
(tr, t0.elapsed().as_millis() as u64)
});
// Only what reads the movie waits for it to finish.
finished = movie.and_then(capture::Movie::wait);
if finished != hint {
journal(
finished.as_ref().map(|(path, _)| path.as_path()),
finished.as_ref().map_or(0, |f| f.1),
);
}
let pre = if let Some((ref movie, video_offset_ms)) = finished
&& !frames.is_empty()
{
let mut preview_marks = marks_of(&strokes);
for (i, &t) in flags.iter().enumerate() {
preview_marks.push(model::Mark {
id: format!("f{}", i + 1),
strokes: Vec::new(),
t0: t,
t1: t,
box_norm: [0.0, 0.0, 1.0, 1.0],
shape: Shape::Flag,
from: None,
to: None,
pin: None,
on: None,
description: "flagged this moment".into(),
frame: None,
});
}
let budget = keyframe_budget(duration_ms);
let preview = select_keyframes(
&frames,
&strokes,
&mut preview_marks,
&events,
&TranscriptData::default(),
budget,
);
// Marks alone filled the budget, so speech can't change the selection.
let marks_fill = preview.len() == budget
&& preview
.iter()
.all(|(k, _)| k.reason == model::KeyframeReason::Mark);
let times: Vec<u64> = preview.iter().map(|(k, _)| k.t).collect();
let decoded = movie_frames_at(movie, ×, video_offset_ms, 0).unwrap_or_default();
if duration_ms >= 20_000 {
let cache = if marks_fill {
Vec::new()
} else {
decoded.clone()
};
let (merged, _) = merge_full_keyframes(preview, decoded);
let vis = prepare_visuals(
merged,
frames.first(),
crop_settings.as_ref(),
&target,
duration_ms,
&strokes,
&preview_marks,
&events,
&activity,
);
(cache, vis)
} else {
(decoded, None)
}
} else {
(Vec::new(), None)
};
(transcribe_handle.join().unwrap(), pre)
});
let (video_path, video_offset_ms) = match finished {
Some((path, offset_ms)) => (Some(path), offset_ms),
None => (None, 0),
};
let built = build_bundle_from_parts(
bundle_dir,
target,
duration_ms,
frames,
strokes,
events,
transcript,
video_path.clone(),
note,
SourceExtras {
activity,
flags,
video_offset_ms,
autocrop: Some(crop_settings),
agent_context,
no_screen,
audio_stopped_at_ms: recorded_audio
.as_ref()
.and_then(RecordedAudio::audio_stopped_at_ms),
full_frames: video_path
.map(|movie| movie_keyframes_with_cache(movie, video_offset_ms, predecoded)),
prepared,
timings: StageTimings {
started_at: Some(started_at),
stop_ms,
transcribe_ms: Some(transcribe_ms),
..StageTimings::default()
},
..SourceExtras::default()
},
);
if built.is_ok() {
recover::finished(bundle_dir);
}
built
}
/// Gives a streamed capture's audio its final `audio.wav` name, now that the
/// journal which recovery reads exists. When the file cannot take the name,
/// its samples are read without consuming it and written by this build; only a
/// write that lands removes the partial. If the audio cannot be published or
/// written, the build fails with the journal left in place, so recovery adopts
/// the partial on the next launch rather than the audio being lost.
fn settle_streamed_audio(
bundle_dir: &Path,
recorded: Option<RecordedAudio>,
wav_path: &Path,
) -> Result<Option<RecordedAudio>> {
let Some(mut audio) = recorded else {
return Ok(None);
};
if !audio.is_on_disk() {
return Ok(Some(audio));
}
if audio.publish_audio(bundle_dir) {
return Ok(Some(audio));
}
crate::log::scrawl_log(format!(
"audio: could not give {} its final name; writing it from memory",
wav_path.display()
));
// Read it without consuming the partial: only a write that lands lets the
// partial go, so the audio is never nowhere on disk.
let memory = match audio.read_streamed() {
Ok(memory) => memory,
Err(error) => {
let _ = std::fs::remove_file(wav_path);
return Err(anyhow::anyhow!(
"could not read the capture's audio {}: {error:#}",
wav_path.display()
));
}
};
let written = memory
.wav_bytes_16k()
.map_err(|error| anyhow::anyhow!("could not encode the capture's audio: {error:#}"))
.and_then(|bytes| {
if bytes.is_empty() {
anyhow::bail!("the capture's audio is empty");
}
std::fs::create_dir_all(bundle_dir)?;
crate::routing::undo::write_private(wav_path, &bytes).map_err(anyhow::Error::from)
});
match written {
Ok(()) => {
audio.discard_streamed();
Ok(Some(memory))
}
Err(error) => {
// Leave the journal and the partial for recovery to adopt.
let _ = std::fs::remove_file(wav_path);
Err(anyhow::anyhow!(
"could not write the capture's audio to {}: {error:#}",
wav_path.display()
))
}
}
}
/// Builds a Screen capture's bundle in `out`, which holds its video and `audio.wav`, from them
/// and what the recording logged: `scrawl reprocess` and `scrawl recover`.
pub fn rebuild_screen_bundle(out: &Path, old: recover::Unfinished) -> Result<String> {
rebuild_screen_bundle_with(out, old, None, &recover::Media::SYSTEM)
}
/// `autocrop` as in `SourceExtras`: `None` follows the config, `Some(None)` keeps the whole frame.
pub fn rebuild_screen_bundle_with(
out: &Path,
old: recover::Unfinished,
autocrop: Option<Option<autocrop::Settings>>,
media: &recover::Media,
) -> Result<String> {
let started_at = std::time::Instant::now();
let video = old
.video
.as_ref()
.map(|name| out.join(name))
.filter(|p| p.is_file())
.context("The bundle has no video")?;
let wav = out.join("audio.wav");
// A crash between the journal and the audio's final name leaves every
// sample under the partial name: adopt it before rebuilding.
let partial = out.join(crate::recover::PARTIAL_AUDIO);
if !wav.is_file() && partial.is_file() {
let _ = std::fs::rename(&partial, &wav);
}
let recorded = if wav.is_file() {
Some(audio::recorded_audio_from_wav(std::fs::read(&wav)?)?)
} else {
None
};
let offset = old.video_offset_ms;
let ((transcript, transcribe_ms), joined) = std::thread::scope(|scope| {
let frames = scope.spawn(|| {
let t0 = std::time::Instant::now();
let res = (media.frames)(&video, helper::FrameTimes::Every(220), 640);
(res, t0.elapsed().as_millis() as u64)
});
let t0 = std::time::Instant::now();
let tr = (media.transcribe)(recorded.as_ref().map(|_| wav.as_path()), recorded.as_ref());
((tr, t0.elapsed().as_millis() as u64), frames.join())
});
let (frames, candidates_ms) = joined.map_err(|_| anyhow::anyhow!("Frame decoding panicked"))?;
let mut frames = frames?;
for frame in &mut frames {
frame.t_ms += offset;
}
// A macOS movie's final frame is held to the recording's stop, which can fall just past the
// capture's end: those frames repeat the last one.
frames.retain(|frame| frame.t_ms <= old.duration_ms);
let (decode, movie) = (media.frames, video.clone());
let full_frames: Option<FullFrames> = Some(Box::new(move |times: &[u64]| {
movie_frames_at_with(decode, &movie, times, offset, 0)
}));
Ok(build_bundle_from_parts(
out,
old.target,
old.duration_ms,
frames,
old.strokes,
old.events,
transcript,
Some(video),
old.note,
SourceExtras {
activity: windows::ActivityLog {
windows: old.windows,
cursor: old.cursor,
..Default::default()
},
full_frames,
video_offset_ms: offset,
autocrop,
timings: StageTimings {
started_at: Some(started_at),
candidates_ms: Some(candidates_ms),
transcribe_ms: Some(transcribe_ms),
..Default::default()
},
..SourceExtras::default()
},
)?
.2)
}
/// A bundle without its transcript yet (the speech model was still downloading) gets it later.
fn mark_transcript_pending(bundle_dir: &Path, bundle: &ScrawlBundle) {
if bundle.transcript.missing.as_ref().is_some_and(|m| m.retry) {
speech_model::mark_pending(bundle_dir);
}
}
#[allow(clippy::too_many_arguments)]
pub fn build_bundle_from_parts(
bundle_dir: &Path,
target: TargetInfo,
duration_ms: u64,
frames: Vec<RgbaFrame>,
strokes: Vec<Stroke>,
events: Vec<InteractionEvent>,
transcript: TranscriptData,
video_path: Option<PathBuf>,
note: Option<String>,
extras: SourceExtras,
) -> Result<(PathBuf, ScrawlBundle, String)> {
let total_started = extras
.timings
.started_at
.unwrap_or_else(std::time::Instant::now);
let mut marks = marks_of(&strokes);
for (i, &t) in extras.flags.iter().enumerate() {
marks.push(Mark {
id: format!("f{}", i + 1),
strokes: Vec::new(),
t0: t,
t1: t,
box_norm: [0.0, 0.0, 1.0, 1.0],
shape: Shape::Flag,
from: None,
to: None,
pin: None,
on: None,
description: "flagged this moment".into(),
frame: None,
});
}
let bench = std::env::var_os("SCRAWL_BENCH").is_some();
let started = std::time::Instant::now();
let selected = select_keyframes(
&frames,
&strokes,
&mut marks,
&events,
&transcript,
keyframe_budget(duration_ms),
);
let select_only_at = std::time::Instant::now();
let matches_prepared = extras.prepared.as_ref().is_some_and(|prep| {
prep.keyframes.len() == selected.len()
&& prep.keyframes.iter().zip(&selected).all(|(a, (b, _))| {
a.index == b.index
&& a.t == b.t
&& a.mark_id == b.mark_id
&& a.cursor == b.cursor
&& a.file == b.file
})
});
enum BundleOutput {
Prepared(PreparedVisuals),
Rendered {
annotated: Vec<(model::Keyframe, RgbaFrame)>,
cropped: Option<(model::AutocropInfo, Vec<(model::Keyframe, RgbaFrame)>)>,
full_sheet: Option<RgbaFrame>,
contact_sheet: RgbaFrame,
},
}
let mut extras = extras;
let (keyframes, autocrop, selected_at, annotated_at, rendered_at, output) = if matches_prepared
{
drop(frames);
let mut prep = extras.prepared.take().unwrap();
let keyframes: Vec<model::Keyframe> = selected.into_iter().map(|(kf, _)| kf).collect();
let selected_at = std::time::Instant::now();
let autocrop = prep.autocrop.take();
(
keyframes,
autocrop,
selected_at,
selected_at,
selected_at,
BundleOutput::Prepared(prep),
)
} else {
// Only the first candidate is needed from here on (auto-crop's baseline); free the rest
// before the full-size keyframes arrive.
let baseline = {
let mut frames = frames;
frames.truncate(1);
frames.pop()
};
let selected = match &extras.full_frames {
Some(decode) if !selected.is_empty() => {
let times: Vec<u64> = selected.iter().map(|(k, _)| k.t).collect();
match decode(×) {
Ok(full) => {
let total = selected.len();
let (merged, matched) = merge_full_keyframes(selected, full);
if matched < total {
crate::log::scrawl_log(format!(
"Full-quality keyframes: decoded {matched} of {total}"
));
}
merged
}
Err(error) => {
crate::log::scrawl_log(format!("Full-quality keyframes failed: {error:#}"));
selected
}
}
}
_ => selected,
};
let selected_at = std::time::Instant::now();
let crop_settings = match extras.autocrop {
Some(settings) => settings,
None if target.mode == CaptureMode::Display => autocrop::Settings::configured(),
None => None,
};
let (mut annotated_frames, mut cropped) = autocrop::annotate_and_crop(
selected,
baseline.as_ref(),
crop_settings.as_ref(),
&target,
duration_ms,
&strokes,
&marks,
&events,
&extras.activity.windows,
&extras.activity.cursor,
);
let keyframes: Vec<model::Keyframe> =
annotated_frames.iter().map(|(kf, _)| kf.clone()).collect();
let annotated_at = std::time::Instant::now();
let (full_sheet, contact_sheet) = std::thread::scope(|scope| {
let full_handle = cropped.as_ref().map(|(_, full)| {
scope.spawn(|| render::render_contact_sheet_for_duration(duration_ms, full))
});
let sheet = render::render_contact_sheet_for_duration(duration_ms, &annotated_frames);
(full_handle.map(|h| h.join().unwrap()), sheet)
});
render::stamp_keyframe_badges(&mut annotated_frames);
if let Some((_, full)) = &mut cropped {
render::stamp_keyframe_badges(full);
}
let rendered_at = std::time::Instant::now();
let autocrop = cropped.as_ref().map(|(info, _)| info.clone());
(
keyframes,
autocrop,
selected_at,
annotated_at,
rendered_at,
BundleOutput::Rendered {
annotated: annotated_frames,
cropped,
full_sheet,
contact_sheet,
},
)
};
let id = bundle_dir
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("scrawl-bundle")
.to_string();
let video_rel = video_path.and_then(|p| {
p.exists()
.then(|| p.file_name()?.to_str().map(str::to_owned))
.flatten()
});
let audio_rel = bundle_dir
.join("audio.wav")
.exists()
.then(|| "audio.wav".to_string());
let bundle = ScrawlBundle {
version: 1,
id,
created_at_ms: now_epoch_ms(),
duration_ms,
target,
transcript,
note,
strokes,
marks,
events,
keyframes,
contact_sheet: "contact-sheet.png".into(),
video: video_rel,
video_offset_ms: extras.video_offset_ms,
audio: audio_rel,
audio_stopped_at_ms: extras.audio_stopped_at_ms,
source: extras.source,
device: extras.device,
context: extras.context,
context_changes: extras.context_changes,
screens: extras.screens,
windows: extras.activity.windows,
cursor: extras.activity.cursor,
autocrop,
clean_frames: None,
destination: None,
no_screen: extras.no_screen,
extra: Default::default(),
};
let summary = match extras.agent_context {
Some(agent_context) => {
crate::sketch::summary_markdown_with(&bundle, bundle_dir, agent_context)
}
None => summary_markdown(&bundle, bundle_dir),
};
match output {
BundleOutput::Prepared(prep) => {
std::fs::create_dir_all(bundle_dir.join("frames"))
.with_context(|| format!("could not create {}", bundle_dir.display()))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ =
std::fs::set_permissions(bundle_dir, std::fs::Permissions::from_mode(0o700));
}
crate::routing::undo::write_private(
&bundle_dir.join(&bundle.contact_sheet),
&prep.contact_sheet_png,
)?;
for (rel, bytes) in &prep.frame_pngs {
crate::routing::undo::write_private(&bundle_dir.join(rel), bytes)?;
}
if let (Some(info), Some(full_sheet_png)) = (&bundle.autocrop, &prep.full_sheet_png) {
let full_dir = bundle_dir.join(&info.full_frames);
std::fs::create_dir_all(&full_dir)?;
crate::routing::undo::write_private(
&bundle_dir.join(&info.full_contact_sheet),
full_sheet_png,
)?;
for (name, bytes) in &prep.full_frame_pngs {
crate::routing::undo::write_private(&full_dir.join(name), bytes)?;
}
}
crate::routing::undo::write_private(
&bundle_dir.join("summary.md"),
summary.as_bytes(),
)?;
capture::publish_manifest(bundle_dir, &bundle)?;
}
BundleOutput::Rendered {
annotated,
cropped,
full_sheet,
contact_sheet,
} => {
std::thread::scope(|scope| -> Result<()> {
let full_write = match (&cropped, &full_sheet) {
(Some((info, full)), Some(sheet)) => Some(
scope.spawn(|| autocrop::write_full_frames(bundle_dir, info, full, sheet)),
),
_ => None,
};
let written = capture::write_bundle_files(
bundle_dir,
&bundle,
&annotated,
&contact_sheet,
&summary,
);
if let Some(handle) = full_write {
handle
.join()
.map_err(|_| anyhow::anyhow!("Full-frame writer panicked"))??;
}
written
})?;
// Last, once everything else is on disk: a bundle with a manifest is complete.
capture::publish_manifest(bundle_dir, &bundle)?;
}
}