a downloaded video previews in every browser, not just the lenient ones: an mkv that sniffs as webm but carries tracks webm never blessed (vp9 with aac audio — the shape every tiktok downloader makes) played in chromium and stalled silently in firefox's stricter demuxer, so the media route now builds a legal preview beside the file on first view — vp9/8/av1 keeps its bytes and the audio becomes opus, h264 remuxes to faststart mp4 — cached under previews/, served to the player with ranges, deleted with the file in every purge path, while downloads keep the original bytes untouched; a matroska is only called webm now when its tracks say so, and one length-read-after-adopt bug that served an empty first response died in the tests
Browse files at this commit3134bfa3dc14109faf8c88cc805369b21a6da0beParent: 95114ec10 changed files +1294 -26
- config/im.toml +3 -0
- crates/in-core/src/store/mod.rs +30 -0
- crates/in-core/src/store/previews.rs +562 -0
- crates/in-core/src/store/sniff.rs +379 -1
- crates/in-core/src/store/turso_store.rs +67 -5
- crates/in-core/src/thumbs.rs +6 -2
- crates/in-web/src/files.rs +38 -11
- crates/in-web/src/main.rs +5 -4
- crates/in-web/src/share.rs +23 -2
- crates/in-web/tests/http.rs +181 -1
config/im.tomladded+3 -0
| @@ -0,0 +1,3 @@ | ||
| 1 | +database = "im.db" | |
| 2 | +listen = "127.0.0.1:7650" | |
| 3 | +issuer = "http://127.0.0.1:7650" |
crates/in-core/src/store/mod.rsmodified+30 -0
| @@ -26,6 +26,8 @@ pub mod sniff; | ||
| 26 | 26 | pub mod turso_store; |
| 27 | 27 | #[cfg(feature = "server")] |
| 28 | 28 | pub mod r2; |
| 29 | +#[cfg(feature = "server")] | |
| 30 | +pub mod previews; | |
| 29 | 31 | |
| 30 | 32 | #[cfg(feature = "server")] |
| 31 | 33 | pub use reconcile::{ReconcileOptions, reconcile}; |
| @@ -167,6 +169,19 @@ pub struct FileSpan { | ||
| 167 | 169 | pub stream: ByteStream, |
| 168 | 170 | } |
| 169 | 171 | |
| 172 | +/// A preview derivative ready to serve in a video's place: the mime its own | |
| 173 | +/// bytes declare — the row's stored mime may say webm about an AAC-in-webm | |
| 174 | +/// Matroska no browser will play — and the honest length to serve. Built | |
| 175 | +/// once at media-serve time; `?dl=1` never sees it, a download is the | |
| 176 | +/// original. | |
| 177 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 178 | +pub struct MediaDerivative { | |
| 179 | + /// The container the derivative's bytes are, not the row's stored mime. | |
| 180 | + pub mime: &'static str, | |
| 181 | + /// The derivative's length, as the blob holds it. | |
| 182 | + pub size: u64, | |
| 183 | +} | |
| 184 | + | |
| 170 | 185 | /// Whether a file's thumbnail exists. `None` for bytes no thumbnail is |
| 171 | 186 | /// attempted for; `Pending` while one is being made; `Ready` or `Failed` |
| 172 | 187 | /// once the attempt settled. |
| @@ -499,6 +514,21 @@ pub trait Store: 'static + Send + Sync { | ||
| 499 | 514 | /// when no thumbnail was made, or its file went missing. |
| 500 | 515 | async fn thumb_bytes(&self, id: &str) -> Result<Option<Vec<u8>>>; |
| 501 | 516 | |
| 517 | + /// The preview derivative standing in for this video at media-serve | |
| 518 | + /// time — built on this first ask when the stored tracks need one (one | |
| 519 | + /// `ffmpeg` transcode, minutes for a long file), a cache read after | |
| 520 | + /// that — or `None`, the answer for anything that is not a video | |
| 521 | + /// container, already plays as stored, has no recipe, or whose build | |
| 522 | + /// failed: the caller serves the original, today's behavior either way. | |
| 523 | + async fn media_derivative(&self, id: &str) -> Result<Option<MediaDerivative>>; | |
| 524 | + | |
| 525 | + /// The cached derivative's bytes as a stream — `media_derivative`'s | |
| 526 | + /// answer is what names it. Same clamping contract as | |
| 527 | + /// [`Store::file_stream`]: a range serve reads only its span, and the | |
| 528 | + /// span is the span that exists. | |
| 529 | + async fn derivative_stream(&self, id: &str, start: u64, len: u64) | |
| 530 | + -> Result<Option<FileSpan>>; | |
| 531 | + | |
| 502 | 532 | /// Counts one user-facing download of a file's bytes. Byte routes call |
| 503 | 533 | /// this once per download they complete — on `?dl=1` serves, not per |
| 504 | 534 | /// range chunk, never for inline previews, thumbnails, or internal reads |
crates/in-core/src/store/previews.rsadded+562 -0
| @@ -0,0 +1,562 @@ | ||
| 1 | +//! Preview derivatives: the playable stand-in for a video whose stored | |
| 2 | +//! bytes a browser cannot demux as they sit. | |
| 3 | +//! | |
| 4 | +//! The stored file is never rewritten — `?dl=1` and every download still | |
| 5 | +//! serve the original bytes byte for byte. What this module adds is a | |
| 6 | +//! second blob at `previews/<id>`, built the first time a media route asks | |
| 7 | +//! to serve a file whose tracks are not what its container's magic claims: | |
| 8 | +//! the AAC-in-webm Matroska the sniffer used to have to call `video/webm` | |
| 9 | +//! (Firefox demuxes the VP9 and refuses the audio), HEVC-in-mp4, and kin. | |
| 10 | +//! After that one build, every media serve draws from the derivative. | |
| 11 | +//! | |
| 12 | +//! The build is one `ffmpeg` child under the same house rules | |
| 13 | +//! [`crate::thumbs`] runs — `-v error`, a runaway killed, output that must | |
| 14 | +//! declare itself the container it was asked for — staged to a temp file in | |
| 15 | +//! the previews tree and placed with [`Blobs::adopt`], so a reader of | |
| 16 | +//! `previews/<id>` sees nothing or the whole derivative, never half, and | |
| 17 | +//! two racing builders cannot tear it. Every failure serves the original: | |
| 18 | +//! a derivative that cannot be made is a miss, not an error. | |
| 19 | + | |
| 20 | +use std::collections::HashMap; | |
| 21 | +use std::io::Read as _; | |
| 22 | +use std::path::Path; | |
| 23 | +use std::process::{Command, Stdio}; | |
| 24 | +use std::sync::{LazyLock, Mutex}; | |
| 25 | +use std::time::{Duration, Instant}; | |
| 26 | + | |
| 27 | +use futures_util::StreamExt; | |
| 28 | +use tokio::io::AsyncWriteExt as _; | |
| 29 | +use ulid::Ulid; | |
| 30 | + | |
| 31 | +use super::blobs::Blobs; | |
| 32 | +use super::sniff::{self, Track, TrackKind}; | |
| 33 | +use super::MediaDerivative; | |
| 34 | +use super::turso_store::FILES_DIR; | |
| 35 | + | |
| 36 | +/// The key family derivatives live in: `previews/<id>`, beside `files/` and | |
| 37 | +/// `thumbs/` — deleted alongside them in every purge, and swept for orphans | |
| 38 | +/// at boot under the same watermark rule as every other half of the tree. | |
| 39 | +pub(super) const PREVIEWS_DIR: &str = "previews"; | |
| 40 | + | |
| 41 | +/// Head bytes inspected for a Matroska `Tracks` element. Muxers write the | |
| 42 | +/// tracks before the clusters, so the element sits near the head of every | |
| 43 | +/// real file; a Matroska that does not show it in this window is one the | |
| 44 | +/// verdict declines to name, and the original is served. | |
| 45 | +const DETECT_WINDOW: u64 = 1024 * 1024; | |
| 46 | + | |
| 47 | +/// The largest `moov` read whole for track inspection. A `moov` bigger than | |
| 48 | +/// this carries no codecs this needs — and a bound is what keeps a hostile | |
| 49 | +/// box walk from allocating to a size it names itself. | |
| 50 | +const MOOV_CAP: u64 = 16 * 1024 * 1024; | |
| 51 | + | |
| 52 | +/// How long one derivative build may run before it is killed. Unlike the | |
| 53 | +/// thumbnailer's one frame, this is a whole transcode of a whole file — | |
| 54 | +/// minutes, not milliseconds — but a build past ten minutes is wedged, and | |
| 55 | +/// the request behind it is better served the original. | |
| 56 | +const BUILD_TIMEOUT: Duration = Duration::from_secs(10 * 60); | |
| 57 | + | |
| 58 | +/// What to do with a file's stored bytes at media-serve time. | |
| 59 | +enum Plan { | |
| 60 | + /// The stored tracks play as they sit: serve the original. | |
| 61 | + Native, | |
| 62 | + /// Build this derivative first, then serve it. | |
| 63 | + Build(Build), | |
| 64 | + /// No recipe this module knows: serve the original, today's behavior. | |
| 65 | + Unsupported, | |
| 66 | +} | |
| 67 | + | |
| 68 | +/// One derivative worth building, and the `ffmpeg` recipe for it. | |
| 69 | +enum Build { | |
| 70 | + /// VP8/VP9/AV1 video stream-copied, the audio transcoded to Opus, | |
| 71 | + /// muxed as the webm the tracks were almost legal for. | |
| 72 | + Webm { video: bool, audio: bool }, | |
| 73 | + /// H.264 or H.265 video with AAC (or no) audio, remuxed into a | |
| 74 | + /// faststart mp4 — no re-encode, one container the browsers demux. | |
| 75 | + RemuxMp4 { audio: bool }, | |
| 76 | +} | |
| 77 | + | |
| 78 | +impl Build { | |
| 79 | + /// The mime the result will carry. | |
| 80 | + fn mime(&self) -> &'static str { | |
| 81 | + match self { | |
| 82 | + Build::Webm { .. } => "video/webm", | |
| 83 | + Build::RemuxMp4 { .. } => "video/mp4", | |
| 84 | + } | |
| 85 | + } | |
| 86 | + | |
| 87 | + /// The `ffmpeg` arguments: explicit stream maps, so nothing a track | |
| 88 | + /// parser never blessed — a subtitle, an attachment — rides along. | |
| 89 | + fn args(&self, input: &Path, output: &Path) -> Vec<String> { | |
| 90 | + let mut args: Vec<String> = vec![ | |
| 91 | + "-v".into(), | |
| 92 | + "error".into(), | |
| 93 | + "-y".into(), | |
| 94 | + "-i".into(), | |
| 95 | + input.display().to_string(), | |
| 96 | + ]; | |
| 97 | + match self { | |
| 98 | + Build::Webm { video, audio } => { | |
| 99 | + if *video { | |
| 100 | + args.extend(["-map", "0:v:0", "-c:v", "copy"].map(str::to_string)); | |
| 101 | + } | |
| 102 | + if *audio { | |
| 103 | + args.extend(["-map", "0:a:0", "-c:a", "libopus"].map(str::to_string)); | |
| 104 | + } | |
| 105 | + args.extend(["-f", "webm"].map(str::to_string)); | |
| 106 | + } | |
| 107 | + Build::RemuxMp4 { audio } => { | |
| 108 | + args.extend(["-map", "0:v:0"].map(str::to_string)); | |
| 109 | + if *audio { | |
| 110 | + args.extend(["-map", "0:a:0"].map(str::to_string)); | |
| 111 | + } | |
| 112 | + args.extend( | |
| 113 | + ["-c", "copy", "-movflags", "+faststart", "-f", "mp4"].map(str::to_string), | |
| 114 | + ); | |
| 115 | + } | |
| 116 | + } | |
| 117 | + args.push(output.display().to_string()); | |
| 118 | + args | |
| 119 | + } | |
| 120 | +} | |
| 121 | + | |
| 122 | +/// The derivative to serve for file `id` — built first, when the stored | |
| 123 | +/// tracks need one — or `None`, the answer for every file that is not a | |
| 124 | +/// video container, already plays, has no recipe, or whose build failed. | |
| 125 | +/// A first request may wait one whole transcode; the permit makes every | |
| 126 | +/// later one a cache read. | |
| 127 | +pub(super) async fn ensure( | |
| 128 | + storage: &Path, | |
| 129 | + blobs: &dyn Blobs, | |
| 130 | + id: &str, | |
| 131 | + mime: &str, | |
| 132 | +) -> Option<MediaDerivative> { | |
| 133 | + if !is_video_container(mime) { | |
| 134 | + return None; | |
| 135 | + } | |
| 136 | + let key = format!("{PREVIEWS_DIR}/{id}"); | |
| 137 | + if let Some(ready) = cached(blobs, &key).await { | |
| 138 | + return Some(ready); | |
| 139 | + } | |
| 140 | + let permit = build_permit(id).await; | |
| 141 | + let _guard = permit.lock().await; | |
| 142 | + if let Some(ready) = cached(blobs, &key).await { | |
| 143 | + release_permit(id); | |
| 144 | + return Some(ready); | |
| 145 | + } | |
| 146 | + let built = match detect(blobs, id).await { | |
| 147 | + Plan::Native | Plan::Unsupported => None, | |
| 148 | + Plan::Build(build) => build_derivative(storage, blobs, id, &key, build).await, | |
| 149 | + }; | |
| 150 | + release_permit(id); | |
| 151 | + built | |
| 152 | +} | |
| 153 | + | |
| 154 | +/// The video containers a derivative may stand in for — the spellings the | |
| 155 | +/// sniffer and the moviemakers actually produce. | |
| 156 | +fn is_video_container(mime: &str) -> bool { | |
| 157 | + matches!( | |
| 158 | + mime, | |
| 159 | + "video/mp4" | "video/webm" | "video/quicktime" | "video/x-matroska" | |
| 160 | + ) | |
| 161 | +} | |
| 162 | + | |
| 163 | +/// The derivative already sitting at `key`, its mime read from its own head | |
| 164 | +/// — a restart forgets the recipe, not the derivative. A blob whose head | |
| 165 | +/// names no container is not a derivative: `None`, and the caller rebuilds. | |
| 166 | +async fn cached(blobs: &dyn Blobs, key: &str) -> Option<MediaDerivative> { | |
| 167 | + let span = blobs.span(key, 0, u64::MAX).await.ok()??; | |
| 168 | + let head = read_stream(span.stream, 12).await; | |
| 169 | + let mime = container_mime(&head)?; | |
| 170 | + Some(MediaDerivative { | |
| 171 | + mime, | |
| 172 | + size: span.len, | |
| 173 | + }) | |
| 174 | +} | |
| 175 | + | |
| 176 | +/// The container a head of bytes declares: EBML magic or an `ftyp` box. | |
| 177 | +fn container_mime(head: &[u8]) -> Option<&'static str> { | |
| 178 | + if head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) { | |
| 179 | + Some("video/webm") | |
| 180 | + } else if head.len() >= 12 && &head[4..8] == b"ftyp" { | |
| 181 | + Some("video/mp4") | |
| 182 | + } else { | |
| 183 | + None | |
| 184 | + } | |
| 185 | +} | |
| 186 | + | |
| 187 | +/// What the stored bytes are, decided without staging: the tracks are read | |
| 188 | +/// out of windows of the blob, and only a build actually wanted drags the | |
| 189 | +/// whole original to disk. | |
| 190 | +async fn detect(blobs: &dyn Blobs, id: &str) -> Plan { | |
| 191 | + let key = format!("{FILES_DIR}/{id}"); | |
| 192 | + let head = match read_span(blobs, &key, 0, DETECT_WINDOW).await { | |
| 193 | + Some(found) => found, | |
| 194 | + None => return Plan::Unsupported, | |
| 195 | + }; | |
| 196 | + if head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) { | |
| 197 | + return match sniff::ebml_tracks(&head) { | |
| 198 | + None => Plan::Unsupported, | |
| 199 | + Some(tracks) if sniff::webm_legal(&tracks) => Plan::Native, | |
| 200 | + Some(tracks) => matroska_plan(&tracks), | |
| 201 | + }; | |
| 202 | + } | |
| 203 | + if head.len() >= 12 && &head[4..8] == b"ftyp" { | |
| 204 | + let total = match read_span_len(blobs, &key).await { | |
| 205 | + Some(len) => len, | |
| 206 | + None => return Plan::Unsupported, | |
| 207 | + }; | |
| 208 | + return mp4_plan(blobs, &key, total).await; | |
| 209 | + } | |
| 210 | + Plan::Unsupported | |
| 211 | +} | |
| 212 | + | |
| 213 | +/// The build for Matroska tracks that are not webm-legal: VP8/VP9/AV1 video | |
| 214 | +/// stream-copies into a real webm with whatever audio there is transcoded to | |
| 215 | +/// Opus; H.264 or H.265 with AAC (or silence) remuxes into a faststart mp4. | |
| 216 | +/// Anything else has no recipe worth a transcode — the original is what | |
| 217 | +/// plays-or-doesn't today. | |
| 218 | +fn matroska_plan(tracks: &[Track]) -> Plan { | |
| 219 | + let video = first_codec_of(tracks, TrackKind::Video); | |
| 220 | + let audio = first_codec_of(tracks, TrackKind::Audio); | |
| 221 | + let webm_video = matches!(video, Some("v_vp8" | "v_vp9" | "v_av1")); | |
| 222 | + let aac = matches!(audio, Some("a_aac")); | |
| 223 | + if webm_video { | |
| 224 | + return Plan::Build(Build::Webm { | |
| 225 | + video: video.is_some(), | |
| 226 | + audio: audio.is_some(), | |
| 227 | + }); | |
| 228 | + } | |
| 229 | + if matches!(video, Some("v_mpeg4/iso/avc" | "v_mpegh/iso/hevc")) | |
| 230 | + && (audio.is_none() || aac) | |
| 231 | + { | |
| 232 | + return Plan::Build(Build::RemuxMp4 { | |
| 233 | + audio: audio.is_some(), | |
| 234 | + }); | |
| 235 | + } | |
| 236 | + Plan::Unsupported | |
| 237 | +} | |
| 238 | + | |
| 239 | +/// The mp4 plan: an mp4 that is not native is helped only when its tracks | |
| 240 | +/// are the remuxable kind — H.264/H.265 video with AAC (or no) audio — | |
| 241 | +/// where the fix is the faststart moov, not the codecs. | |
| 242 | +async fn mp4_plan(blobs: &dyn Blobs, key: &str, total: u64) -> Plan { | |
| 243 | + let Some((moov_start, moov_len)) = moov_location(blobs, key, total).await else { | |
| 244 | + return Plan::Unsupported; | |
| 245 | + }; | |
| 246 | + if moov_len > MOOV_CAP { | |
| 247 | + return Plan::Unsupported; | |
| 248 | + } | |
| 249 | + let Some(moov) = read_span(blobs, key, moov_start, moov_len).await else { | |
| 250 | + return Plan::Unsupported; | |
| 251 | + }; | |
| 252 | + let tracks = sniff::mp4_tracks(&moov); | |
| 253 | + if sniff::mp4_native(&tracks) { | |
| 254 | + return Plan::Native; | |
| 255 | + } | |
| 256 | + let video = first_codec_of(&tracks, TrackKind::Video); | |
| 257 | + let audio = first_codec_of(&tracks, TrackKind::Audio); | |
| 258 | + if matches!(video, Some(codec) if codec.starts_with("avc") || codec == "hev1" || codec == "hvc1") | |
| 259 | + && (audio.is_none() || audio == Some("mp4a")) | |
| 260 | + { | |
| 261 | + return Plan::Build(Build::RemuxMp4 { | |
| 262 | + audio: audio.is_some(), | |
| 263 | + }); | |
| 264 | + } | |
| 265 | + Plan::Unsupported | |
| 266 | +} | |
| 267 | + | |
| 268 | +/// Where the `moov` sits: `(body offset, body length)`, walked one header | |
| 269 | +/// at a time — each read 16 bytes off the blob, each `mdat` skipped by its | |
| 270 | +/// declared size — so a faststart-less file, moov behind megabytes of | |
| 271 | +/// media, costs a handful of range reads and never the file. A `size` of 0 | |
| 272 | +/// (to end of file, the streaming-written shape) resolves against the | |
| 273 | +/// blob's own length; a walk that runs off the file finds nothing. | |
| 274 | +async fn moov_location(blobs: &dyn Blobs, key: &str, total: u64) -> Option<(u64, u64)> { | |
| 275 | + let mut at = 0u64; | |
| 276 | + for _ in 0..64 { | |
| 277 | + let header = read_span(blobs, key, at, 16).await?; | |
| 278 | + if header.len() < 8 { | |
| 279 | + return None; | |
| 280 | + } | |
| 281 | + let size = | |
| 282 | + u32::from_be_bytes([header[0], header[1], header[2], header[3]]) as u64; | |
| 283 | + let typ = [header[4], header[5], header[6], header[7]]; | |
| 284 | + let (header_len, box_len) = match size { | |
| 285 | + 1 => { | |
| 286 | + if header.len() < 16 { | |
| 287 | + return None; | |
| 288 | + } | |
| 289 | + ( | |
| 290 | + 16u64, | |
| 291 | + u64::from_be_bytes([ | |
| 292 | + header[8], header[9], header[10], header[11], header[12], header[13], | |
| 293 | + header[14], header[15], | |
| 294 | + ]), | |
| 295 | + ) | |
| 296 | + } | |
| 297 | + 0 => (8u64, total - at), | |
| 298 | + size => (8u64, size), | |
| 299 | + }; | |
| 300 | + if box_len < header_len { | |
| 301 | + return None; | |
| 302 | + } | |
| 303 | + if typ == *b"moov" { | |
| 304 | + return Some((at + header_len, box_len - header_len)); | |
| 305 | + } | |
| 306 | + at += box_len; | |
| 307 | + } | |
| 308 | + None | |
| 309 | +} | |
| 310 | +/// The codec of a kind's first track, for the verdicts that weigh one | |
| 311 | +/// stream of each class. | |
| 312 | +fn first_codec_of<'a>(tracks: &'a [Track], kind: TrackKind) -> Option<&'a str> { | |
| 313 | + tracks | |
| 314 | + .iter() | |
| 315 | + .find(|track| track.kind == kind) | |
| 316 | + .map(|track| track.codec.as_str()) | |
| 317 | +} | |
| 318 | + | |
| 319 | +/// Builds and places the derivative: stage the original, run one `ffmpeg` | |
| 320 | +/// child on it, adopt the result into place. The staging lives in the | |
| 321 | +/// previews tree so the adopt's rename is same-filesystem atomic. Any miss | |
| 322 | +/// answers `None` — the original is what the caller serves — and leaves | |
| 323 | +/// nothing behind but a log line. | |
| 324 | +async fn build_derivative( | |
| 325 | + storage: &Path, | |
| 326 | + blobs: &dyn Blobs, | |
| 327 | + id: &str, | |
| 328 | + key: &str, | |
| 329 | + build: Build, | |
| 330 | +) -> Option<MediaDerivative> { | |
| 331 | + let dir = storage.join(PREVIEWS_DIR); | |
| 332 | + if std::fs::create_dir_all(&dir).is_err() { | |
| 333 | + return None; | |
| 334 | + } | |
| 335 | + let staged = dir.join(format!("{id}.{}.in.tmp", Ulid::new())); | |
| 336 | + let output = dir.join(format!("{id}.{}.out.tmp", Ulid::new())); | |
| 337 | + let staged_ok = stage_original(blobs, id, &staged).await.is_some(); | |
| 338 | + let built = if staged_ok { | |
| 339 | + let input = staged.clone(); | |
| 340 | + let target = output.clone(); | |
| 341 | + tokio::task::spawn_blocking(move || run_ffmpeg(&build, &input, &target)) | |
| 342 | + .await | |
| 343 | + .ok() | |
| 344 | + } else { | |
| 345 | + None | |
| 346 | + }; | |
| 347 | + // The length is read before the adopt: the adopt renames the staging | |
| 348 | + // away, and the honest serving length is the file that was placed. | |
| 349 | + let len = file_len(&output); | |
| 350 | + let derivative = match built { | |
| 351 | + Some(Ok(mime)) if len > 0 => match blobs.adopt(key, &output, len).await { | |
| 352 | + Ok(()) => Some(MediaDerivative { mime, size: len }), | |
| 353 | + Err(_) => None, | |
| 354 | + }, | |
| 355 | + _ => None, | |
| 356 | + }; | |
| 357 | + let _ = std::fs::remove_file(&staged); | |
| 358 | + let _ = std::fs::remove_file(&output); | |
| 359 | + derivative | |
| 360 | +} | |
| 361 | + | |
| 362 | +/// A file's length, `0` when it has gone missing — an adopt refuses a | |
| 363 | +/// missing staging anyway, and the caller serves the original. | |
| 364 | +fn file_len(path: &Path) -> u64 { | |
| 365 | + std::fs::metadata(path).map(|meta| meta.len()).unwrap_or(0) | |
| 366 | +} | |
| 367 | + | |
| 368 | +/// Copies the original blob to `dest`, frame by frame — never the whole | |
| 369 | +/// file in one buffer. `None` when the blob is not there to copy. | |
| 370 | +async fn stage_original(blobs: &dyn Blobs, id: &str, dest: &Path) -> Option<()> { | |
| 371 | + let span = blobs | |
| 372 | + .span(&format!("{FILES_DIR}/{id}"), 0, u64::MAX) | |
| 373 | + .await | |
| 374 | + .ok()??; | |
| 375 | + let mut file = tokio::fs::File::create(dest).await.ok()?; | |
| 376 | + let mut stream = span.stream; | |
| 377 | + while let Some(chunk) = stream.next().await { | |
| 378 | + file.write_all(&chunk.ok()?).await.ok()?; | |
| 379 | + } | |
| 380 | + file.flush().await.ok()?; | |
| 381 | + Some(()) | |
| 382 | +} | |
| 383 | + | |
| 384 | +/// Runs one derivative build: the recipe's `ffmpeg` arguments, the | |
| 385 | +/// container bytes into `output`. The same house rules as the thumbnailer — | |
| 386 | +/// `-v error`, a runaway killed, output that must declare the container it | |
| 387 | +/// was asked for — with stderr captured for the one failure line. `Err` | |
| 388 | +/// carries nothing: the caller's contract is "serve the original". | |
| 389 | +fn run_ffmpeg(build: &Build, input: &Path, output: &Path) -> Result<&'static str, ()> { | |
| 390 | + let mut child = Command::new("ffmpeg") | |
| 391 | + .args(build.args(input, output)) | |
| 392 | + .stdin(Stdio::null()) | |
| 393 | + .stdout(Stdio::null()) | |
| 394 | + .stderr(Stdio::piped()) | |
| 395 | + .spawn() | |
| 396 | + .map_err(|_| ())?; | |
| 397 | + // stderr drains on its own thread: the pipe buffer is small, and a | |
| 398 | + // parent that only `try_wait`s while the child fills it would deadlock | |
| 399 | + // against it. | |
| 400 | + let stderr = child.stderr.take(); | |
| 401 | + let (tx, rx) = std::sync::mpsc::channel(); | |
| 402 | + std::thread::spawn(move || { | |
| 403 | + let mut message = String::new(); | |
| 404 | + if let Some(mut err) = stderr { | |
| 405 | + let _ = err.read_to_string(&mut message); | |
| 406 | + } | |
| 407 | + let _ = tx.send(message); | |
| 408 | + }); | |
| 409 | + let start = Instant::now(); | |
| 410 | + let status = loop { | |
| 411 | + match child.try_wait() { | |
| 412 | + Ok(Some(status)) => break status.success(), | |
| 413 | + Ok(None) => { | |
| 414 | + if start.elapsed() >= BUILD_TIMEOUT { | |
| 415 | + let _ = child.kill(); | |
| 416 | + let _ = child.wait(); | |
| 417 | + break false; | |
| 418 | + } | |
| 419 | + std::thread::sleep(Duration::from_millis(50)); | |
| 420 | + } | |
| 421 | + Err(_) => break false, | |
| 422 | + } | |
| 423 | + }; | |
| 424 | + // Whatever left the pipe must be the container asked for, and nonempty: | |
| 425 | + // ffmpeg exits 0 over some failures it has already printed. | |
| 426 | + let mut head = [0u8; 12]; | |
| 427 | + let head_len = std::fs::File::open(output) | |
| 428 | + .and_then(|mut file| file.read(&mut head)) | |
| 429 | + .unwrap_or(0); | |
| 430 | + let mime = container_mime(&head[..head_len]); | |
| 431 | + match (status, mime) { | |
| 432 | + (true, Some(mime)) if mime == build.mime() => Ok(mime), | |
| 433 | + _ => { | |
| 434 | + let message = rx.recv().unwrap_or_default(); | |
| 435 | + let reason = message.lines().next().unwrap_or("no output"); | |
| 436 | + eprintln!("preview build for {} failed: {reason}", input.display()); | |
| 437 | + Err(()) | |
| 438 | + } | |
| 439 | + } | |
| 440 | +} | |
| 441 | + | |
| 442 | +/// The derivative to serve, straight off the key: same clamping contract as | |
| 443 | +/// the file stream, so a range serve reads only its span. | |
| 444 | +pub(super) async fn stream( | |
| 445 | + blobs: &dyn Blobs, | |
| 446 | + id: &str, | |
| 447 | + start: u64, | |
| 448 | + len: u64, | |
| 449 | +) -> Option<super::FileSpan> { | |
| 450 | + blobs | |
| 451 | + .span(&format!("{PREVIEWS_DIR}/{id}"), start, len) | |
| 452 | + .await | |
| 453 | + .ok()? | |
| 454 | +} | |
| 455 | + | |
| 456 | +/// `len` bytes of a blob from `start`, buffered whole — the windows track | |
| 457 | +/// detection reads, never the file a transcode consumes. | |
| 458 | +async fn read_span(blobs: &dyn Blobs, key: &str, start: u64, len: u64) -> Option<Vec<u8>> { | |
| 459 | + let span = blobs.span(key, start, len).await.ok()??; | |
| 460 | + let bytes = read_stream(span.stream, span.len).await; | |
| 461 | + if bytes.len() as u64 == span.len { | |
| 462 | + Some(bytes) | |
| 463 | + } else { | |
| 464 | + None | |
| 465 | + } | |
| 466 | +} | |
| 467 | + | |
| 468 | +/// A blob's honest length: the span clamp against what the backend holds. | |
| 469 | +async fn read_span_len(blobs: &dyn Blobs, key: &str) -> Option<u64> { | |
| 470 | + blobs.span(key, 0, u64::MAX).await.ok()?.map(|span| span.len) | |
| 471 | +} | |
| 472 | + | |
| 473 | +/// Drains a span's stream into one buffer, capped at `max` bytes. | |
| 474 | +async fn read_stream( | |
| 475 | + mut stream: super::ByteStream, | |
| 476 | + max: u64, | |
| 477 | +) -> Vec<u8> { | |
| 478 | + let mut out = Vec::new(); | |
| 479 | + while out.len() < max as usize { | |
| 480 | + match stream.next().await { | |
| 481 | + Some(Ok(chunk)) => out.extend_from_slice(&chunk), | |
| 482 | + _ => break, | |
| 483 | + } | |
| 484 | + } | |
| 485 | + out | |
| 486 | +} | |
| 487 | + | |
| 488 | +/// One builder at a time per file: a permit per id in flight. The map | |
| 489 | +/// holds one entry per id whose build is somewhere running — the entry | |
| 490 | +/// leaves when its last holder is done, so the map never grows past the | |
| 491 | +/// files being built right now. | |
| 492 | +static PERMITS: LazyLock<Mutex<HashMap<String, std::sync::Arc<tokio::sync::Mutex<()>>>>> = | |
| 493 | + LazyLock::new(Default::default); | |
| 494 | + | |
| 495 | +/// The holder of a build: take one, guard it for the length of `ensure`. | |
| 496 | +async fn build_permit(id: &str) -> std::sync::Arc<tokio::sync::Mutex<()>> { | |
| 497 | + PERMITS | |
| 498 | + .lock() | |
| 499 | + .expect("permit map") | |
| 500 | + .entry(id.to_string()) | |
| 501 | + .or_default() | |
| 502 | + .clone() | |
| 503 | +} | |
| 504 | + | |
| 505 | +/// Forgets a permit whose last holder just finished — the map's own | |
| 506 | +/// strong count is the only reader it can trust. | |
| 507 | +fn release_permit(id: &str) { | |
| 508 | + let mut permits = PERMITS.lock().expect("permit map"); | |
| 509 | + if let Some(permit) = permits.get(id) { | |
| 510 | + if std::sync::Arc::strong_count(permit) == 1 { | |
| 511 | + permits.remove(id); | |
| 512 | + } | |
| 513 | + } | |
| 514 | +} | |
| 515 | + | |
| 516 | +#[cfg(test)] | |
| 517 | +mod tests { | |
| 518 | + use super::*; | |
| 519 | + | |
| 520 | + #[test] | |
| 521 | + fn recipes_ask_for_the_containers_they_name() { | |
| 522 | + let webm = Build::Webm { | |
| 523 | + video: true, | |
| 524 | + audio: true, | |
| 525 | + }; | |
| 526 | + assert_eq!(webm.mime(), "video/webm"); | |
| 527 | + let args = webm.args(Path::new("in.mkv"), Path::new("out.tmp")); | |
| 528 | + let args: Vec<&str> = args.iter().map(String::as_str).collect(); | |
| 529 | + assert!(args.windows(2).any(|pair| pair == ["-c:v", "copy"])); | |
| 530 | + assert!(args.windows(2).any(|pair| pair == ["-c:a", "libopus"])); | |
| 531 | + let remux = Build::RemuxMp4 { audio: true }; | |
| 532 | + let remux_args = remux.args(Path::new("in.mp4"), Path::new("out.tmp")); | |
| 533 | + let args: Vec<&str> = remux_args.iter().map(String::as_str).collect(); | |
| 534 | + assert!(args.windows(2).any(|pair| pair == ["-c", "copy"])); | |
| 535 | + assert!(args.windows(2).any(|pair| pair == ["-movflags", "+faststart"])); | |
| 536 | + } | |
| 537 | + #[tokio::test] | |
| 538 | + async fn moov_location_walks_past_mdat_by_its_declared_size() { | |
| 539 | + // ftyp, then an mdat far bigger than any head window, then moov — | |
| 540 | + // the faststart-less shape the walk exists for. | |
| 541 | + let dir = std::env::temp_dir().join(format!("in-preview-{}", Ulid::new())); | |
| 542 | + std::fs::create_dir_all(dir.join("files")).unwrap(); | |
| 543 | + let mut bytes = Vec::new(); | |
| 544 | + bytes.extend_from_slice(&8u32.to_be_bytes()); | |
| 545 | + bytes.extend_from_slice(b"ftyp"); | |
| 546 | + let mdat_body = 10u64 * 1024 * 1024; | |
| 547 | + bytes.extend_from_slice(&((mdat_body + 8) as u32).to_be_bytes()); | |
| 548 | + bytes.extend_from_slice(b"mdat"); | |
| 549 | + bytes.extend(std::iter::repeat_n(0u8, mdat_body as usize)); | |
| 550 | + bytes.extend_from_slice(&(24u32).to_be_bytes()); | |
| 551 | + bytes.extend_from_slice(b"moov"); | |
| 552 | + bytes.extend([0u8; 16]); | |
| 553 | + std::fs::write(dir.join("files").join("x"), &bytes).unwrap(); | |
| 554 | + let total = bytes.len() as u64; | |
| 555 | + let blobs = super::super::blobs::LocalBlobs::new(&dir); | |
| 556 | + assert_eq!( | |
| 557 | + moov_location(&blobs, "files/x", total).await, | |
| 558 | + Some((total - 16, 16)) | |
| 559 | + ); | |
| 560 | + let _ = std::fs::remove_dir_all(&dir); | |
| 561 | + } | |
| 562 | +} |
crates/in-core/src/store/sniff.rsmodified+379 -1
| @@ -81,7 +81,7 @@ pub fn sniff(bytes: &[u8]) -> &'static str { | ||
| 81 | 81 | } else if bytes.len() >= 8 && &bytes[4..8] == b"ftyp" { |
| 82 | 82 | "video/mp4" |
| 83 | 83 | } else if bytes.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) { |
| 84 | - "video/webm" | |
| 84 | + matroska_mime(bytes) | |
| 85 | 85 | } else if bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP" { |
| 86 | 86 | "image/webp" |
| 87 | 87 | } else if bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WAVE" { |
| @@ -103,6 +103,299 @@ pub fn sniff(bytes: &[u8]) -> &'static str { | ||
| 103 | 103 | } |
| 104 | 104 | } |
| 105 | 105 | |
| 106 | +/// What an EBML file is called. `video/webm` only when its tracks are all | |
| 107 | +/// webm-legal — the container's promise is the tracks, not the magic, and | |
| 108 | +/// the sniffer spent years calling every Matroska a webm, which Firefox | |
| 109 | +/// answers with silence when the audio turns out to be AAC. Bytes this | |
| 110 | +/// parser cannot bound keep their old name: an unparseable Matroska stays | |
| 111 | +/// `video/webm`, the verdict every EBML file wore before tracks counted. | |
| 112 | +fn matroska_mime(bytes: &[u8]) -> &'static str { | |
| 113 | + match ebml_tracks(bytes) { | |
| 114 | + Some(tracks) if webm_legal(&tracks) => "video/webm", | |
| 115 | + Some(_) => "video/x-matroska", | |
| 116 | + None => "video/webm", | |
| 117 | + } | |
| 118 | +} | |
| 119 | + | |
| 120 | +/// One track a container declares: its class, and the codec it names — a | |
| 121 | +/// Matroska `CodecID` such as `V_VP9`, or an ISO-BMFF sample-entry FourCC | |
| 122 | +/// such as `avc1` — lowercased so every verdict compares one spelling. | |
| 123 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 124 | +pub(crate) struct Track { | |
| 125 | + pub kind: TrackKind, | |
| 126 | + pub codec: String, | |
| 127 | +} | |
| 128 | + | |
| 129 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 130 | +pub(crate) enum TrackKind { | |
| 131 | + Video, | |
| 132 | + Audio, | |
| 133 | + Other, | |
| 134 | +} | |
| 135 | + | |
| 136 | +/// The Matroska tracks, read straight out of the bytes: the EBML header, | |
| 137 | +/// then the `Segment`'s children down to the `Tracks` element, one entry | |
| 138 | +/// per `TrackEntry` (`TrackType`, then `CodecID`). `None` when the | |
| 139 | +/// structure cannot be walked — an element whose size cannot be skipped, | |
| 140 | +/// a cluster met before the tracks — and the caller keeps its old verdict. | |
| 141 | +/// A track wearing `ContentEncodings` reads as unknown: a header-compressed | |
| 142 | +/// or encrypted track is not the codec its `CodecID` names. | |
| 143 | +pub(crate) fn ebml_tracks(bytes: &[u8]) -> Option<Vec<Track>> { | |
| 144 | + let end = bytes.len(); | |
| 145 | + let (_, _, _, header_end) = ebml_element(bytes, 0, end)?; | |
| 146 | + let (id, _, segment, segment_end) = ebml_element(bytes, header_end, end)?; | |
| 147 | + if id != 0x1853_8067 { | |
| 148 | + return None; // Segment | |
| 149 | + } | |
| 150 | + let mut at = segment; | |
| 151 | + while at < segment_end { | |
| 152 | + let (id, _, start, stop) = ebml_element(bytes, at, segment_end)?; | |
| 153 | + match id { | |
| 154 | + // Tracks | |
| 155 | + 0x1654_AE6B => return Some(track_entries(bytes, start, stop)), | |
| 156 | + // Cluster: muxers write the tracks before the clusters, so one | |
| 157 | + // met here means the walk is done looking. | |
| 158 | + 0x1F43_B675 => return None, | |
| 159 | + _ => {} | |
| 160 | + } | |
| 161 | + at = stop; | |
| 162 | + } | |
| 163 | + None | |
| 164 | +} | |
| 165 | + | |
| 166 | +/// The `TrackEntry`s of a `Tracks` payload: each entry's `TrackType` (1 is | |
| 167 | +/// video, 2 audio, anything else a kind webm has no word for) and its | |
| 168 | +/// `CodecID`. An entry with neither is a track no verdict can trust. | |
| 169 | +fn track_entries(bytes: &[u8], start: usize, end: usize) -> Vec<Track> { | |
| 170 | + let mut tracks = Vec::new(); | |
| 171 | + let mut at = start; | |
| 172 | + while at < end { | |
| 173 | + let (id, _, entry, entry_end) = match ebml_element(bytes, at, end) { | |
| 174 | + Some(found) => found, | |
| 175 | + None => break, | |
| 176 | + }; | |
| 177 | + at = entry_end; | |
| 178 | + if id != 0xAE { | |
| 179 | + continue; // TrackEntry | |
| 180 | + } | |
| 181 | + let (mut kind, mut codec, mut encoded) = (TrackKind::Other, None, false); | |
| 182 | + let mut inner = entry; | |
| 183 | + while inner < entry_end { | |
| 184 | + let (id, _, value, value_end) = match ebml_element(bytes, inner, entry_end) { | |
| 185 | + Some(found) => found, | |
| 186 | + None => break, | |
| 187 | + }; | |
| 188 | + inner = value_end; | |
| 189 | + match id { | |
| 190 | + 0x83 => { | |
| 191 | + if let Some(number) = ebml_uint(bytes, value, value_end) { | |
| 192 | + kind = match number { | |
| 193 | + 1 => TrackKind::Video, | |
| 194 | + 2 => TrackKind::Audio, | |
| 195 | + _ => TrackKind::Other, | |
| 196 | + }; | |
| 197 | + } | |
| 198 | + } | |
| 199 | + 0x86 => { | |
| 200 | + codec = Some(String::from_utf8_lossy(&bytes[value..value_end]).into_owned()); | |
| 201 | + } | |
| 202 | + // ContentEncodings: header compression or encryption. | |
| 203 | + 0x6D80 => encoded = true, | |
| 204 | + _ => {} | |
| 205 | + } | |
| 206 | + } | |
| 207 | + if encoded { | |
| 208 | + codec = Some(String::new()); | |
| 209 | + } | |
| 210 | + tracks.push(Track { | |
| 211 | + kind, | |
| 212 | + codec: codec.unwrap_or_default().to_lowercase(), | |
| 213 | + }); | |
| 214 | + } | |
| 215 | + tracks | |
| 216 | +} | |
| 217 | + | |
| 218 | +/// Whether every track is one a webm muxer may hold: video in the codec set | |
| 219 | +/// the container was cut down to (VP8, VP9, AV1), audio in its pair | |
| 220 | +/// (Vorbis, Opus), nothing else — and at least one track, since a file with | |
| 221 | +/// no tracks gives the verdict nothing to stand on. | |
| 222 | +pub(crate) fn webm_legal(tracks: &[Track]) -> bool { | |
| 223 | + !tracks.is_empty() | |
| 224 | + && tracks.iter().all(|track| match track.kind { | |
| 225 | + TrackKind::Video => matches!(track.codec.as_str(), "v_vp8" | "v_vp9" | "v_av1"), | |
| 226 | + TrackKind::Audio => matches!(track.codec.as_str(), "a_vorbis" | "a_opus"), | |
| 227 | + TrackKind::Other => false, | |
| 228 | + }) | |
| 229 | +} | |
| 230 | + | |
| 231 | +/// The tracks an mp4's `moov` declares, one per `trak`: the class from the | |
| 232 | +/// `mdia/hdlr` handler, the codec from the first `stsd` sample entry. An | |
| 233 | +/// mp4 this cannot read comes back with no tracks, which the verdicts | |
| 234 | +/// treat as native — nothing here may take the original away on a guess. | |
| 235 | +pub(crate) fn mp4_tracks(moov: &[u8]) -> Vec<Track> { | |
| 236 | + let mut tracks = Vec::new(); | |
| 237 | + let mut at = 0usize; | |
| 238 | + while at < moov.len() { | |
| 239 | + let (typ, _, body, body_end) = match box_at(moov, at, moov.len()) { | |
| 240 | + Some(found) => found, | |
| 241 | + None => break, | |
| 242 | + }; | |
| 243 | + at = body_end; | |
| 244 | + if typ != *b"trak" { | |
| 245 | + continue; | |
| 246 | + } | |
| 247 | + tracks.push(trak_track(moov, body, body_end)); | |
| 248 | + } | |
| 249 | + tracks | |
| 250 | +} | |
| 251 | + | |
| 252 | +/// Whether an mp4's tracks are ones a browser demuxes as they sit: H.264 | |
| 253 | +/// video and AAC audio, nothing else in. Tracks of no known class — a hint | |
| 254 | +/// or metadata track — do not stand in the way; an unreadable codec does. | |
| 255 | +pub(crate) fn mp4_native(tracks: &[Track]) -> bool { | |
| 256 | + tracks.iter().all(|track| match track.kind { | |
| 257 | + TrackKind::Video => track.codec.starts_with("avc"), | |
| 258 | + TrackKind::Audio => track.codec == "mp4a", | |
| 259 | + TrackKind::Other => true, | |
| 260 | + }) | |
| 261 | +} | |
| 262 | + | |
| 263 | +/// One `trak`: its handler's class and its first sample entry's codec. | |
| 264 | +fn trak_track(bytes: &[u8], start: usize, end: usize) -> Track { | |
| 265 | + let unknown = Track { | |
| 266 | + kind: TrackKind::Other, | |
| 267 | + codec: String::new(), | |
| 268 | + }; | |
| 269 | + let (media, media_end) = match find_box(bytes, start, end, b"mdia") { | |
| 270 | + Some(found) => found, | |
| 271 | + None => return unknown, | |
| 272 | + }; | |
| 273 | + // `hdlr`'s handler FourCC sits after its version/flags and reserved | |
| 274 | + // quad — twelve bytes into the box body. | |
| 275 | + let kind = find_box(bytes, media, media_end, b"hdlr") | |
| 276 | + .filter(|&(head, _)| bytes.len() >= head + 12) | |
| 277 | + .map(|(head, _)| match &bytes[head + 8..head + 12] { | |
| 278 | + b"vide" => TrackKind::Video, | |
| 279 | + b"soun" => TrackKind::Audio, | |
| 280 | + _ => TrackKind::Other, | |
| 281 | + }) | |
| 282 | + .unwrap_or(TrackKind::Other); | |
| 283 | + let codec = find_box(bytes, media, media_end, b"minf") | |
| 284 | + .and_then(|(minf, minf_end)| find_box(bytes, minf, minf_end, b"stbl")) | |
| 285 | + .and_then(|(stbl, stbl_end)| find_box(bytes, stbl, stbl_end, b"stsd")) | |
| 286 | + .and_then(|(stsd, stsd_end)| stsd_codec(bytes, stsd, stsd_end)) | |
| 287 | + .unwrap_or_default(); | |
| 288 | + Track { kind, codec } | |
| 289 | +} | |
| 290 | + | |
| 291 | +/// The codec of an `stsd`'s first sample entry: the FourCC right after the | |
| 292 | +/// entry's size — `avc1`, `mp4a`, `ac-3`, whatever the track really is. | |
| 293 | +fn stsd_codec(bytes: &[u8], start: usize, end: usize) -> Option<String> { | |
| 294 | + let entry = start.checked_add(8)?; // version/flags, then entry count | |
| 295 | + if bytes.len() < entry + 8 || end < entry + 8 { | |
| 296 | + return None; | |
| 297 | + } | |
| 298 | + Some( | |
| 299 | + String::from_utf8_lossy(&bytes[entry + 4..entry + 8]) | |
| 300 | + .into_owned() | |
| 301 | + .to_lowercase(), | |
| 302 | + ) | |
| 303 | +} | |
| 304 | + | |
| 305 | +/// The body of the first box named `want`, between `start` and `end`. | |
| 306 | +fn find_box(bytes: &[u8], start: usize, end: usize, want: &[u8; 4]) -> Option<(usize, usize)> { | |
| 307 | + let mut at = start; | |
| 308 | + while at < end { | |
| 309 | + let (typ, _, body, body_end) = box_at(bytes, at, end)?; | |
| 310 | + if &typ == want { | |
| 311 | + return Some((body, body_end)); | |
| 312 | + } | |
| 313 | + at = body_end.max(at + 8); | |
| 314 | + } | |
| 315 | + None | |
| 316 | +} | |
| 317 | + | |
| 318 | +/// One ISO-BMFF box at `at`, bounded by `end`: its FourCC and the bounds | |
| 319 | +/// of its body. A `size` of 1 promotes to the 64-bit largesize; a `size` | |
| 320 | +/// of 0 runs to the end of the bytes. Anything malformed stops the walk. | |
| 321 | +fn box_at(bytes: &[u8], at: usize, end: usize) -> Option<([u8; 4], usize, usize, usize)> { | |
| 322 | + let head = bytes.get(at..end)?; | |
| 323 | + if head.len() < 8 { | |
| 324 | + return None; | |
| 325 | + } | |
| 326 | + let typ = [head[4], head[5], head[6], head[7]]; | |
| 327 | + let (header, total) = match u32::from_be_bytes([head[0], head[1], head[2], head[3]]) as u64 { | |
| 328 | + 1 => { | |
| 329 | + if head.len() < 16 { | |
| 330 | + return None; | |
| 331 | + } | |
| 332 | + let large = u64::from_be_bytes([ | |
| 333 | + head[8], head[9], head[10], head[11], head[12], head[13], head[14], head[15], | |
| 334 | + ]); | |
| 335 | + (16usize, usize::try_from(large).ok()?) | |
| 336 | + } | |
| 337 | + 0 => (8usize, head.len()), | |
| 338 | + size => (8usize, size as usize), | |
| 339 | + }; | |
| 340 | + let body_end = at.checked_add(total)?; | |
| 341 | + if total < header || body_end > end { | |
| 342 | + return None; | |
| 343 | + } | |
| 344 | + Some((typ, at, at + header, body_end)) | |
| 345 | +} | |
| 346 | + | |
| 347 | +/// One EBML element at `at`, bounded by `end`: its id, its payload size, | |
| 348 | +/// and the payload's bounds. The id keeps its marker bits — the length | |
| 349 | +/// encoding is the id — and the size drops them. A payload claiming past | |
| 350 | +/// `end` is clamped: a truncated tail decides nothing here. `None` for an | |
| 351 | +/// unknown-size element — a live-stream shape a file has no business | |
| 352 | +/// carrying — and for bytes that end inside a header. | |
| 353 | +fn ebml_element(bytes: &[u8], at: usize, end: usize) -> Option<(u32, u64, usize, usize)> { | |
| 354 | + let head = bytes.get(at..end)?; | |
| 355 | + let id_width = head.first()?.leading_zeros() as usize + 1; | |
| 356 | + if head.len() < id_width || id_width > 4 { | |
| 357 | + return None; | |
| 358 | + } | |
| 359 | + let mut id = head[0] as u64; | |
| 360 | + for &byte in &head[1..id_width] { | |
| 361 | + id = (id << 8) | byte as u64; | |
| 362 | + } | |
| 363 | + let id = id as u32; | |
| 364 | + // The size vint follows, same width rule, marker dropped. | |
| 365 | + let rest = &head[id_width..]; | |
| 366 | + let size_width = rest.first()?.leading_zeros() as usize + 1; | |
| 367 | + if rest.len() < size_width { | |
| 368 | + return None; | |
| 369 | + } | |
| 370 | + let marker = 0xFFu8.checked_shr(size_width as u32).unwrap_or(0); | |
| 371 | + let mut size = (rest[0] & marker) as u64; | |
| 372 | + for &byte in &rest[1..size_width] { | |
| 373 | + size = (size << 8) | byte as u64; | |
| 374 | + } | |
| 375 | + // Every value bit set is the unknown size — unbounded, so not a file. | |
| 376 | + if size == (1u64 << (7 * size_width)) - 1 { | |
| 377 | + return None; | |
| 378 | + } | |
| 379 | + let start = at + id_width + size_width; | |
| 380 | + let stop = start | |
| 381 | + .checked_add(usize::try_from(size).ok()?)? | |
| 382 | + .min(end); | |
| 383 | + Some((id, size, start, stop)) | |
| 384 | +} | |
| 385 | + | |
| 386 | +/// The unsigned integer an element's payload holds — `TrackType` and kin. | |
| 387 | +fn ebml_uint(bytes: &[u8], start: usize, end: usize) -> Option<u64> { | |
| 388 | + let value = bytes.get(start..end)?; | |
| 389 | + if value.len() > 8 { | |
| 390 | + return None; | |
| 391 | + } | |
| 392 | + let mut number = 0u64; | |
| 393 | + for &byte in value { | |
| 394 | + number = (number << 8) | byte as u64; | |
| 395 | + } | |
| 396 | + Some(number) | |
| 397 | +} | |
| 398 | + | |
| 106 | 399 | /// Which office document a zip's bytes declare, decided the way every reader |
| 107 | 400 | /// of the format does: by the entry names a zip stores uncompressed. Ends in |
| 108 | 401 | /// [`GENERIC_MIME_TYPES`]' zip bucket when the names name nothing. |
| @@ -363,4 +656,89 @@ mod tests { | ||
| 363 | 656 | // claims one — the marker is entry content, not an entry name. |
| 364 | 657 | assert_eq!(office_entry_mime(head), None); |
| 365 | 658 | } |
| 659 | + fn matroska(tracks: &[(&str, u64)]) -> Vec<u8> { | |
| 660 | + let entries: Vec<u8> = tracks | |
| 661 | + .iter() | |
| 662 | + .flat_map(|&(codec, kind)| { | |
| 663 | + let mut entry = vec![0x83, 0x81, kind as u8, 0x86, 0x80 | codec.len() as u8]; | |
| 664 | + entry.extend_from_slice(codec.as_bytes()); | |
| 665 | + ebml(&[0xAE], &entry) | |
| 666 | + }) | |
| 667 | + .collect(); | |
| 668 | + let mut bytes = ebml(&[0x1A, 0x45, 0xDF, 0xA3], b""); | |
| 669 | + bytes.extend(ebml( | |
| 670 | + &[0x18, 0x53, 0x80, 0x67], | |
| 671 | + &ebml(&[0x16, 0x54, 0xAE, 0x6B], &entries), | |
| 672 | + )); | |
| 673 | + bytes | |
| 674 | + } | |
| 675 | + | |
| 676 | + /// An ISO-BMFF box: size, FourCC, body. | |
| 677 | + fn boxy(typ: &[u8; 4], body: &[u8]) -> Vec<u8> { | |
| 678 | + let mut bytes = ((body.len() + 8) as u32).to_be_bytes().to_vec(); | |
| 679 | + bytes.extend_from_slice(typ); | |
| 680 | + bytes.extend_from_slice(body); | |
| 681 | + bytes | |
| 682 | + } | |
| 683 | + | |
| 684 | + /// An EBML element: id, a one-octet size vint (marker bit on — the | |
| 685 | + /// bodies here stay under 128 bytes), body. | |
| 686 | + fn ebml(id: &[u8], body: &[u8]) -> Vec<u8> { | |
| 687 | + let mut bytes = id.to_vec(); | |
| 688 | + bytes.push(0x80 | body.len() as u8); | |
| 689 | + bytes.extend_from_slice(body); | |
| 690 | + bytes | |
| 691 | + } | |
| 692 | + fn moov(tracks: &[(&[u8; 4], &[u8; 4])]) -> Vec<u8> { | |
| 693 | + let traks: Vec<u8> = tracks | |
| 694 | + .iter() | |
| 695 | + .flat_map(|&(handler, codec)| { | |
| 696 | + let hdlr = boxy(b"hdlr", &[0, 0, 0, 0, 0, 0, 0, 0, handler[0], handler[1], handler[2], handler[3]]); | |
| 697 | + let stsd = boxy(b"stsd", &[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 8, codec[0], codec[1], codec[2], codec[3]]); | |
| 698 | + boxy(b"trak", &boxy(b"mdia", &[&hdlr[..], &boxy(b"minf", &boxy(b"stbl", &stsd))].concat())) | |
| 699 | + }) | |
| 700 | + .collect(); | |
| 701 | + boxy(b"moov", &traks) | |
| 702 | + } | |
| 703 | + | |
| 704 | + #[test] | |
| 705 | + fn a_matroska_counts_as_webm_only_when_its_tracks_are() { | |
| 706 | + let legal = matroska(&[("V_VP9", 1), ("A_OPUS", 2)]); | |
| 707 | + assert_eq!(sniff(&legal), "video/webm"); | |
| 708 | + let vp9_video_only = matroska(&[("V_VP9", 1)]); | |
| 709 | + assert_eq!(sniff(&vp9_video_only), "video/webm"); | |
| 710 | + // The AAC-in-webm mkv that started this: same magic, silent in | |
| 711 | + // Firefox until a derivative exists. | |
| 712 | + let aac = matroska(&[("V_VP9", 1), ("A_AAC", 2)]); | |
| 713 | + assert_eq!(sniff(&aac), "video/x-matroska"); | |
| 714 | + let h264 = matroska(&[("V_MPEG4/ISO/AVC", 1), ("A_AAC", 2)]); | |
| 715 | + assert_eq!(sniff(&h264), "video/x-matroska"); | |
| 716 | + // A subtitle track is a track webm's rule has no word for. | |
| 717 | + let subtitle = matroska(&[("V_VP9", 1), ("A_OPUS", 2), ("S_TEXT/UTF8", 0x11)]); | |
| 718 | + assert_eq!(sniff(&subtitle), "video/x-matroska"); | |
| 719 | + } | |
| 720 | + | |
| 721 | + #[test] | |
| 722 | + fn an_unparseable_matroska_keeps_its_old_name() { | |
| 723 | + assert_eq!(sniff(&[0x1A, 0x45, 0xDF, 0xA3, 0x00, 0x00]), "video/webm"); | |
| 724 | + } | |
| 725 | + | |
| 726 | + #[test] | |
| 727 | + fn an_mp4_is_native_only_for_h264_video_and_aac_audio() { | |
| 728 | + // The walk runs over moov's body, the way `previews` reads it out | |
| 729 | + // of the blob — hence the `[8..]` past each box's own header. | |
| 730 | + let tracks = mp4_tracks(&moov(&[(b"vide", b"avc1"), (b"soun", b"mp4a")])[8..]); | |
| 731 | + assert_eq!(tracks.len(), 2); | |
| 732 | + assert!(mp4_native(&tracks)); | |
| 733 | + let hevc = mp4_tracks(&moov(&[(b"vide", b"hev1"), (b"soun", b"mp4a")])[8..]); | |
| 734 | + assert!(!mp4_native(&hevc)); | |
| 735 | + let ac3 = mp4_tracks(&moov(&[(b"vide", b"avc1"), (b"soun", b"ac-3")])[8..]); | |
| 736 | + assert!(!mp4_native(&ac3)); | |
| 737 | + // A hint track (handler neither video nor audio) stands aside. | |
| 738 | + let hinted = mp4_tracks( | |
| 739 | + &moov(&[(b"vide", b"avc1"), (b"soun", b"mp4a"), (b"hint", b"rtp ")])[8..], | |
| 740 | + ); | |
| 741 | + assert!(mp4_native(&hinted)); | |
| 742 | + } | |
| 743 | + | |
| 366 | 744 | } |
crates/in-core/src/store/turso_store.rsmodified+67 -5
| @@ -23,14 +23,21 @@ use super::{ReconcileOptions, reconcile, schema, sniff}; | ||
| 23 | 23 | use crate::live::{Change, Topic}; |
| 24 | 24 | use crate::thumbs; |
| 25 | 25 | |
| 26 | +use super::previews; | |
| 27 | + | |
| 26 | 28 | /// Where one file's bytes live: `<storage>/files/<id>`, named by the row's |
| 27 | 29 | /// own id. What an upload carried never decides a path here — the name is |
| 28 | 30 | /// always store-made, so `name` stays a label. |
| 29 | -const FILES_DIR: &str = "files"; | |
| 31 | +pub(crate) const FILES_DIR: &str = "files"; | |
| 30 | 32 | /// Where thumbnails live: `<storage>/thumbs/<id>`, webp, longest edge 512. |
| 31 | 33 | const THUMBS_DIR: &str = "thumbs"; |
| 32 | 34 | /// Where upload chunks stage: `<storage>/uploads/<session-id>/<n>`. |
| 33 | 35 | const UPLOADS_DIR: &str = "uploads"; |
| 36 | +/// Where preview derivatives live: `previews/<id>`, the playable stand-in | |
| 37 | +/// a media route builds for a video whose stored tracks no browser demuxes. | |
| 38 | +/// Deleted beside `files/` and `thumbs/` in every purge, swept at boot with | |
| 39 | +/// the same watermark rule. | |
| 40 | +const PREVIEWS_DIR: &str = previews::PREVIEWS_DIR; | |
| 34 | 41 | |
| 35 | 42 | /// Thumbnails are attempted only below this source size: 64 MiB. Past it the |
| 36 | 43 | /// row wears `failed` rather than pinning memory the size of the file. |
| @@ -267,6 +274,9 @@ impl TursoStore { | ||
| 267 | 274 | for (dir, known, kind) in [ |
| 268 | 275 | (FILES_DIR, &files, "file"), |
| 269 | 276 | (THUMBS_DIR, &thumbs, "thumbnail"), |
| 277 | + // A derivative may exist for any live file row — it is built on | |
| 278 | + // demand, not at ingest — so its known set is the same ids. | |
| 279 | + (PREVIEWS_DIR, &files, "preview"), | |
| 270 | 280 | ] { |
| 271 | 281 | // One listing per half: the names the tree holds, temp files |
| 272 | 282 | // included — a `.tmp` is an orphan like any other — each with |
| @@ -786,6 +796,7 @@ fn ensure_storage_dirs(storage: &std::path::Path) -> Result<()> { | ||
| 786 | 796 | storage.join(FILES_DIR), |
| 787 | 797 | storage.join(THUMBS_DIR), |
| 788 | 798 | storage.join(UPLOADS_DIR), |
| 799 | + storage.join(PREVIEWS_DIR), | |
| 789 | 800 | ] { |
| 790 | 801 | std::fs::create_dir_all(&dir) |
| 791 | 802 | .map_err(|e| StoreError::Backend(format!("could not create {}: {e}", dir.display())))?; |
| @@ -1797,6 +1808,44 @@ impl Store for TursoStore { | ||
| 1797 | 1808 | .await |
| 1798 | 1809 | .map_err(|e| StoreError::Backend(e.to_string())) |
| 1799 | 1810 | } |
| 1811 | + | |
| 1812 | + async fn media_derivative(&self, id: &str) -> Result<Option<super::MediaDerivative>> { | |
| 1813 | + let conn = self.conn.lock().await; | |
| 1814 | + let mut rows = conn | |
| 1815 | + .query("SELECT mime FROM file WHERE id = ?1", params![id]) | |
| 1816 | + .await | |
| 1817 | + .map_err(backend)?; | |
| 1818 | + let mime = match rows.next().await.map_err(backend)? { | |
| 1819 | + Some(row) => text(&row, 0)?, | |
| 1820 | + None => return Ok(None), | |
| 1821 | + }; | |
| 1822 | + drop(conn); | |
| 1823 | + // The build's misses are the module's own log lines; the store's | |
| 1824 | + // answer to every one of them is "serve the original". | |
| 1825 | + Ok(previews::ensure(&self.storage, self.blobs.as_ref(), id, &mime).await) | |
| 1826 | + } | |
| 1827 | + | |
| 1828 | + async fn derivative_stream( | |
| 1829 | + &self, | |
| 1830 | + id: &str, | |
| 1831 | + start: u64, | |
| 1832 | + len: u64, | |
| 1833 | + ) -> Result<Option<super::FileSpan>> { | |
| 1834 | + let conn = self.conn.lock().await; | |
| 1835 | + let mut rows = conn | |
| 1836 | + .query("SELECT 1 FROM file WHERE id = ?1", params![id]) | |
| 1837 | + .await | |
| 1838 | + .map_err(backend)?; | |
| 1839 | + let known = rows.next().await.map_err(backend)?.is_some(); | |
| 1840 | + drop(conn); | |
| 1841 | + if !known { | |
| 1842 | + return Ok(None); | |
| 1843 | + } | |
| 1844 | + // Same answer as `file_stream`: a missing derivative is "nothing | |
| 1845 | + // to serve", not a stack. The span clamps against the real blob. | |
| 1846 | + Ok(previews::stream(self.blobs.as_ref(), id, start, len).await) | |
| 1847 | + } | |
| 1848 | + | |
| 1800 | 1849 | async fn list_trash(&self, owner_id: &str) -> Result<Listing> { |
| 1801 | 1850 | let conn = self.conn.lock().await; |
| 1802 | 1851 | let mut folders = Vec::new(); |
| @@ -1977,7 +2026,11 @@ impl Store for TursoStore { | ||
| 1977 | 2026 | // boot sweep collects. |
| 1978 | 2027 | let _ = self |
| 1979 | 2028 | .blobs |
| 1980 | - .delete(&[&format!("files/{id}"), &format!("thumbs/{id}")]) | |
| 2029 | + .delete(&[ | |
| 2030 | + &format!("files/{id}"), | |
| 2031 | + &format!("thumbs/{id}"), | |
| 2032 | + &format!("previews/{id}"), | |
| 2033 | + ]) | |
| 1981 | 2034 | .await; |
| 1982 | 2035 | self.announce([Topic::Library(owner.clone()), Topic::Trash(owner)]); |
| 1983 | 2036 | Ok(true) |
| @@ -2047,7 +2100,11 @@ impl Store for TursoStore { | ||
| 2047 | 2100 | for file_id in &deleted_files { |
| 2048 | 2101 | let _ = self |
| 2049 | 2102 | .blobs |
| 2050 | - .delete(&[&format!("files/{file_id}"), &format!("thumbs/{file_id}")]) | |
| 2103 | + .delete(&[ | |
| 2104 | + &format!("files/{file_id}"), | |
| 2105 | + &format!("thumbs/{file_id}"), | |
| 2106 | + &format!("previews/{file_id}"), | |
| 2107 | + ]) | |
| 2051 | 2108 | .await; |
| 2052 | 2109 | } |
| 2053 | 2110 | let purged = (deleted_files.len() + deleted_folders.len()) as u64; |
| @@ -2762,7 +2819,11 @@ impl Store for TursoStore { | ||
| 2762 | 2819 | // is what failed. |
| 2763 | 2820 | let _ = self |
| 2764 | 2821 | .blobs |
| 2765 | - .delete(&[&format!("files/{file_id}"), &format!("thumbs/{file_id}")]) | |
| 2822 | + .delete(&[ | |
| 2823 | + &format!("files/{file_id}"), | |
| 2824 | + &format!("thumbs/{file_id}"), | |
| 2825 | + &format!("previews/{file_id}"), | |
| 2826 | + ]) | |
| 2766 | 2827 | .await; |
| 2767 | 2828 | return Err(backend(e)); |
| 2768 | 2829 | } |
| @@ -3296,10 +3357,11 @@ async fn commit_trash_purge( | ||
| 3296 | 3357 | // After the delete: bytes may only follow a delete that committed. |
| 3297 | 3358 | // Best-effort — survivors are orphaned bytes the boot sweep collects. |
| 3298 | 3359 | if !deleted_files.is_empty() { |
| 3299 | - let mut keys = Vec::with_capacity(deleted_files.len() * 2); | |
| 3360 | + let mut keys = Vec::with_capacity(deleted_files.len() * 3); | |
| 3300 | 3361 | for id in &deleted_files { |
| 3301 | 3362 | keys.push(format!("{FILES_DIR}/{id}")); |
| 3302 | 3363 | keys.push(format!("{THUMBS_DIR}/{id}")); |
| 3364 | + keys.push(format!("{PREVIEWS_DIR}/{id}")); | |
| 3303 | 3365 | } |
| 3304 | 3366 | let keys = keys.iter().map(String::as_str).collect::<Vec<_>>(); |
| 3305 | 3367 | let _ = store.blobs.delete(&keys).await; |
crates/in-core/src/thumbs.rsmodified+6 -2
| @@ -51,9 +51,13 @@ pub fn thumbnailed(mime: &str) -> bool { | ||
| 51 | 51 | } |
| 52 | 52 | |
| 53 | 53 | /// Whether `mime` is a video container this crate frames via `ffmpeg`: |
| 54 | -/// exactly the video mimes the sniffer can name. | |
| 54 | +/// exactly the video mimes the sniffer can name — including the Matroska | |
| 55 | +/// spelling it gives a file whose tracks are not webm-legal. | |
| 55 | 56 | pub fn is_video_mime(mime: &str) -> bool { |
| 56 | - matches!(mime, "video/mp4" | "video/webm" | "video/quicktime") | |
| 57 | + matches!( | |
| 58 | + mime, | |
| 59 | + "video/mp4" | "video/webm" | "video/quicktime" | "video/x-matroska" | |
| 60 | + ) | |
| 57 | 61 | } |
| 58 | 62 | |
| 59 | 63 | /// Whether `ffmpeg` is on `PATH`. The verdict comes from one `ffmpeg |
crates/in-web/src/files.rsmodified+38 -11
| @@ -256,11 +256,6 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, topcoat::r | ||
| 256 | 256 | let inline = !forced && inline_ok(&file.mime); |
| 257 | 257 | |
| 258 | 258 | let mut headers = HeaderMap::new(); |
| 259 | - headers.insert( | |
| 260 | - header::CONTENT_TYPE, | |
| 261 | - HeaderValue::from_str(&file.mime) | |
| 262 | - .unwrap_or(HeaderValue::from_static("application/octet-stream")), | |
| 263 | - ); | |
| 264 | 259 | headers.insert( |
| 265 | 260 | header::CONTENT_DISPOSITION, |
| 266 | 261 | HeaderValue::from_str(&disposition_of(&file.name, inline)) |
| @@ -291,7 +286,24 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, topcoat::r | ||
| 291 | 286 | Some(Ok((0, _))) | None => true, |
| 292 | 287 | _ => false, |
| 293 | 288 | }; |
| 294 | - match bytes_response(store.as_ref(), id, file.size_bytes, range, headers).await { | |
| 289 | + // A video whose stored tracks no browser demuxes as they sit plays | |
| 290 | + // through its derivative — built on this first ask, cached at | |
| 291 | + // `previews/{id}`, served under the mime the derivative really is. A | |
| 292 | + // download (`?dl=1`) never sees it: the original bytes, byte for byte. | |
| 293 | + let mut content_type = file.mime.clone(); | |
| 294 | + let mut total = file.size_bytes; | |
| 295 | + let mut source = ByteSource::Original; | |
| 296 | + if inline { | |
| 297 | + if let Ok(Some(derivative)) = store.media_derivative(id).await { | |
| 298 | + content_type = derivative.mime.to_string(); | |
| 299 | + total = derivative.size; | |
| 300 | + source = ByteSource::Preview; | |
| 301 | + } | |
| 302 | + } | |
| 303 | + if let Ok(value) = HeaderValue::from_str(&content_type) { | |
| 304 | + headers.insert(header::CONTENT_TYPE, value); | |
| 305 | + } | |
| 306 | + match bytes_response(store.as_ref(), id, total, range, headers, source).await { | |
| 295 | 307 | Some((status, headers, body)) => { |
| 296 | 308 | if counts && status.is_success() { |
| 297 | 309 | let _ = store.record_download(id).await; |
| @@ -301,18 +313,30 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, topcoat::r | ||
| 301 | 313 | None => Ok(not_found()), |
| 302 | 314 | } |
| 303 | 315 | } |
| 316 | +/// Where a byte response's span comes from: the original blob, or the | |
| 317 | +/// preview derivative standing in for it at media-serve time. A download | |
| 318 | +/// is always [`ByteSource::Original`] — `?dl=1` serves the stored bytes | |
| 319 | +/// byte for byte, derivative or no. | |
| 320 | +#[derive(Clone, Copy, PartialEq, Eq)] | |
| 321 | +pub(crate) enum ByteSource { | |
| 322 | + Original, | |
| 323 | + Preview, | |
| 324 | +} | |
| 304 | 325 | |
| 305 | 326 | /// The streamed answer for a file's bytes: the whole file from 0, or the |
| 306 | -/// parsed range's span — [`Store::file_stream`] clamps both against what is | |
| 307 | -/// really on disk, and the `Content-Length` (and a 206's `Content-Range`) | |
| 308 | -/// say the clamped truth. `None` when the bytes are not there. Shared by the | |
| 309 | -/// signed-in route above and the public link's `download_bytes`. | |
| 327 | +/// parsed range's span — the source's store call clamps both against what | |
| 328 | +/// is really on disk, and the `Content-Length` (and a 206's | |
| 329 | +/// `Content-Range`) say the clamped truth. `total` is the serving length — | |
| 330 | +/// the original's or the derivative's, whichever the caller chose. `None` | |
| 331 | +/// when the bytes are not there. Shared by the signed-in route above and | |
| 332 | +/// the public link's `download_bytes` and `media_bytes`. | |
| 310 | 333 | pub(crate) async fn bytes_response( |
| 311 | 334 | store: &dyn Store, |
| 312 | 335 | id: &str, |
| 313 | 336 | total: u64, |
| 314 | 337 | range: Option<&str>, |
| 315 | 338 | mut headers: HeaderMap, |
| 339 | + source: ByteSource, | |
| 316 | 340 | ) -> Option<(StatusCode, HeaderMap, topcoat::router::Body)> { |
| 317 | 341 | use futures_util::StreamExt; |
| 318 | 342 | use http_body::Frame; |
| @@ -329,7 +353,10 @@ pub(crate) async fn bytes_response( | ||
| 329 | 353 | } |
| 330 | 354 | None => (StatusCode::OK, 0, total), |
| 331 | 355 | }; |
| 332 | - let span = store.file_stream(id, start, len).await.ok().flatten()?; | |
| 356 | + let span = match source { | |
| 357 | + ByteSource::Original => store.file_stream(id, start, len).await.ok().flatten()?, | |
| 358 | + ByteSource::Preview => store.derivative_stream(id, start, len).await.ok().flatten()?, | |
| 359 | + }; | |
| 333 | 360 | if status == StatusCode::PARTIAL_CONTENT { |
| 334 | 361 | let end = start + span.len.saturating_sub(1); |
| 335 | 362 | headers.insert( |
crates/in-web/src/main.rsmodified+5 -4
| @@ -301,9 +301,10 @@ async fn main() { | ||
| 301 | 301 | } |
| 302 | 302 | |
| 303 | 303 | /// Makes the storage tree the store keeps binary files in, if it is not |
| 304 | -/// there: `<storage>/files`, `<storage>/thumbs` and `<storage>/uploads`, | |
| 305 | -/// private to the user the process runs as. A directory that exists is left | |
| 306 | -/// exactly as it is; one that cannot be made stops the boot — the failure | |
| 304 | +/// there: `<storage>/files`, `<storage>/thumbs`, `<storage>/previews` and | |
| 305 | +/// `<storage>/uploads`, private to the user the process runs as. A | |
| 306 | +/// directory that exists is left exactly as it is; one that cannot be made | |
| 307 | +/// stops the boot — the failure | |
| 307 | 308 | /// this prevents is an upload landing in a tree that is not there, and it is |
| 308 | 309 | /// better met before anything is opened. |
| 309 | 310 | fn ensure_storage_tree(storage: &std::path::Path) { |
| @@ -323,7 +324,7 @@ fn ensure_storage_tree(storage: &std::path::Path) { | ||
| 323 | 324 | } |
| 324 | 325 | }; |
| 325 | 326 | make(storage); |
| 326 | - for name in ["files", "thumbs", "uploads"] { | |
| 327 | + for name in ["files", "thumbs", "previews", "uploads"] { | |
| 327 | 328 | make(&storage.join(name)); |
| 328 | 329 | } |
| 329 | 330 | } |
crates/in-web/src/share.rsmodified+23 -2
| @@ -994,7 +994,15 @@ async fn download_bytes( | ||
| 994 | 994 | HeaderValue::from_static("private, no-cache"), |
| 995 | 995 | ); |
| 996 | 996 | let Some(parts) = |
| 997 | - crate::files::bytes_response(store, file_id, size_bytes, range, headers).await | |
| 997 | + crate::files::bytes_response( | |
| 998 | + store, | |
| 999 | + file_id, | |
| 1000 | + size_bytes, | |
| 1001 | + range, | |
| 1002 | + headers, | |
| 1003 | + crate::files::ByteSource::Original, | |
| 1004 | + ) | |
| 1005 | + .await | |
| 998 | 1006 | else { |
| 999 | 1007 | return dead_link(cx).await; |
| 1000 | 1008 | }; |
| @@ -1029,6 +1037,19 @@ async fn media_bytes( | ||
| 1029 | 1037 | let range = request_headers(cx) |
| 1030 | 1038 | .get(header::RANGE) |
| 1031 | 1039 | .and_then(|value| value.to_str().ok()); |
| 1040 | + // The derivative, when the stored tracks need one and it can be had: | |
| 1041 | + // the player draws webm/mp4 it can actually demux. Preview is what a | |
| 1042 | + // view-only link grants, and this grants nothing beyond it — there is | |
| 1043 | + // no download shape on this route, and `?dl=1` still answers the | |
| 1044 | + // original or the dead card. | |
| 1045 | + let (mime, total, source) = match store.media_derivative(file_id).await { | |
| 1046 | + Ok(Some(derivative)) => ( | |
| 1047 | + derivative.mime, | |
| 1048 | + derivative.size, | |
| 1049 | + crate::files::ByteSource::Preview, | |
| 1050 | + ), | |
| 1051 | + _ => (mime, size_bytes, crate::files::ByteSource::Original), | |
| 1052 | + }; | |
| 1032 | 1053 | let mut headers = HeaderMap::new(); |
| 1033 | 1054 | if let Ok(value) = HeaderValue::from_str(mime) { |
| 1034 | 1055 | headers.insert(header::CONTENT_TYPE, value); |
| @@ -1045,7 +1066,7 @@ async fn media_bytes( | ||
| 1045 | 1066 | HeaderValue::from_static("private, no-cache"), |
| 1046 | 1067 | ); |
| 1047 | 1068 | let Some(parts) = |
| 1048 | - crate::files::bytes_response(store, file_id, size_bytes, range, headers).await | |
| 1069 | + crate::files::bytes_response(store, file_id, total, range, headers, source).await | |
| 1049 | 1070 | else { |
| 1050 | 1071 | return dead_link(cx).await; |
| 1051 | 1072 | }; |
crates/in-web/tests/http.rsmodified+181 -1
| @@ -9,12 +9,13 @@ | ||
| 9 | 9 | //! |
| 10 | 10 | //! New HTTP tests belong in this file rather than a new `tests/*.rs`: one |
| 11 | 11 | //! test binary links and runs once. |
| 12 | +use http::{HeaderValue, Request, StatusCode, header}; | |
| 12 | 13 | use in_core::{Config, OidcConfig}; |
| 13 | 14 | use std::collections::HashMap; |
| 14 | 15 | use std::path::PathBuf; |
| 16 | +use std::process::Command; | |
| 15 | 17 | use std::sync::{Arc, Mutex}; |
| 16 | 18 | |
| 17 | -use http::{HeaderValue, Request, StatusCode, header}; | |
| 18 | 19 | use in_core::store::{ShareKind, Store, TursoStore}; |
| 19 | 20 | use in_web::server::App; |
| 20 | 21 | use topcoat::asset::{AssetBundle, RouterBuilderAssetExt}; |
| @@ -1662,6 +1663,185 @@ async fn view_only_link_download_is_dead_card() { | ||
| 1662 | 1663 | ); |
| 1663 | 1664 | } |
| 1664 | 1665 | |
| 1666 | +/// A tiny VP9+AAC Matroska, made by the system `ffmpeg` the way the | |
| 1667 | +/// thumbnailer drives it: a test pattern and a tone, half a second. Small, | |
| 1668 | +/// but exactly the file a browser refuses to play as a webm — VP9 video | |
| 1669 | +/// with AAC audio. `None` skips the tests where ffmpeg is not installed. | |
| 1670 | +fn vp9_aac_matroska() -> Option<Vec<u8>> { | |
| 1671 | + if !in_core::thumbs::ffmpeg_available() { | |
| 1672 | + eprintln!("skipping matroska preview tests: no ffmpeg on PATH"); | |
| 1673 | + return None; | |
| 1674 | + } | |
| 1675 | + let dir = std::env::temp_dir().join(format!("in-mkv-{}", Ulid::new())); | |
| 1676 | + std::fs::create_dir_all(&dir).unwrap(); | |
| 1677 | + let out = dir.join("clip.mkv"); | |
| 1678 | + let status = Command::new("ffmpeg") | |
| 1679 | + .args([ | |
| 1680 | + "-v", | |
| 1681 | + "error", | |
| 1682 | + "-y", | |
| 1683 | + "-f", | |
| 1684 | + "lavfi", | |
| 1685 | + "-i", | |
| 1686 | + "testsrc=duration=0.5:size=128x96:rate=10", | |
| 1687 | + "-f", | |
| 1688 | + "lavfi", | |
| 1689 | + "-i", | |
| 1690 | + "sine=frequency=440:duration=0.5", | |
| 1691 | + "-c:v", | |
| 1692 | + "libvpx-vp9", | |
| 1693 | + "-c:a", | |
| 1694 | + "aac", | |
| 1695 | + ]) | |
| 1696 | + .arg(&out) | |
| 1697 | + .status() | |
| 1698 | + .ok()?; | |
| 1699 | + let bytes = if status.success() { | |
| 1700 | + std::fs::read(&out).ok() | |
| 1701 | + } else { | |
| 1702 | + None | |
| 1703 | + }; | |
| 1704 | + let _ = std::fs::remove_dir_all(&dir); | |
| 1705 | + bytes | |
| 1706 | +} | |
| 1707 | + | |
| 1708 | +/// What a cached derivative is replaced with to prove a later serve draws | |
| 1709 | +/// the cache instead of rebuilding: a webm's magic and a body no transcode | |
| 1710 | +/// could produce. The head stays a container the cache probe accepts. | |
| 1711 | +fn cached_marker() -> Vec<u8> { | |
| 1712 | + let mut marker = vec![0x1A, 0x45, 0xDF, 0xA3]; | |
| 1713 | + marker.extend_from_slice(b"cached-derivative"); | |
| 1714 | + marker | |
| 1715 | +} | |
| 1716 | + | |
| 1717 | +/// A VP9+AAC mkv is stored under its honest Matroska name, the media route | |
| 1718 | +/// serves it a webm derivative — built on the first ask, then cached, then | |
| 1719 | +/// range-servable — and `?dl=1` still hands over the original bytes, byte | |
| 1720 | +/// for byte. | |
| 1721 | +#[tokio::test] | |
| 1722 | +async fn a_webm_illegal_matroska_gains_a_derivative_preview() { | |
| 1723 | + let Some(mkv) = vp9_aac_matroska() else { | |
| 1724 | + return; | |
| 1725 | + }; | |
| 1726 | + let app = TestApp::build().await; | |
| 1727 | + let cookie = app | |
| 1728 | + .sign_in("sub-matroska", "matroska@in.test", "Matroska") | |
| 1729 | + .await; | |
| 1730 | + let user = app | |
| 1731 | + .store | |
| 1732 | + .user_by_oidc_sub("sub-matroska") | |
| 1733 | + .await | |
| 1734 | + .unwrap() | |
| 1735 | + .unwrap(); | |
| 1736 | + | |
| 1737 | + app.post_multipart( | |
| 1738 | + "/files", | |
| 1739 | + Some(&cookie), | |
| 1740 | + &[("folder_id", "")], | |
| 1741 | + &[("clip.mkv", "video/x-matroska", &mkv)], | |
| 1742 | + ) | |
| 1743 | + .await; | |
| 1744 | + let file = app | |
| 1745 | + .store | |
| 1746 | + .list_children(&user.id, None) | |
| 1747 | + .await | |
| 1748 | + .unwrap() | |
| 1749 | + .files | |
| 1750 | + .into_iter() | |
| 1751 | + .next() | |
| 1752 | + .unwrap(); | |
| 1753 | + // The sniffer no longer calls these tracks a webm. | |
| 1754 | + let stored = app.store.file(&file.id).await.unwrap().unwrap(); | |
| 1755 | + assert_eq!(stored.mime, "video/x-matroska"); | |
| 1756 | + | |
| 1757 | + // The first inline serve builds the derivative and answers with it. | |
| 1758 | + let inline = app.get(&format!("/file/{}", file.id), Some(&cookie)).await; | |
| 1759 | + assert_eq!(inline.status, StatusCode::OK); | |
| 1760 | + assert_eq!(inline.content_type.as_deref(), Some("video/webm")); | |
| 1761 | + assert_ne!(inline.bytes, mkv, "the preview was the original bytes"); | |
| 1762 | + // The serve's length is the derivative's own: the body is exactly the | |
| 1763 | + // blob the build placed, never a clamp against the original's size. | |
| 1764 | + let placed = std::fs::read(app.config.storage.join("previews").join(&file.id)).unwrap(); | |
| 1765 | + assert!(!placed.is_empty()); | |
| 1766 | + assert_eq!(inline.bytes, placed, "the preview was not the derivative"); | |
| 1767 | + | |
| 1768 | + // The second serve answers the cache, whatever it holds — a rebuild | |
| 1769 | + // would have replaced this marker with fresh transcode output. | |
| 1770 | + let derivative_key = app.config.storage.join("previews").join(&file.id); | |
| 1771 | + let marker = cached_marker(); | |
| 1772 | + std::fs::write(&derivative_key, &marker).unwrap(); | |
| 1773 | + let again = app.get(&format!("/file/{}", file.id), Some(&cookie)).await; | |
| 1774 | + assert_eq!(again.status, StatusCode::OK); | |
| 1775 | + assert_eq!(again.bytes, marker, "the second serve rebuilt the cache"); | |
| 1776 | + | |
| 1777 | + // A range reads the derivative's span, against its own length. | |
| 1778 | + let probe = app | |
| 1779 | + .get_with_range(&format!("/file/{}", file.id), Some(&cookie), "bytes=0-3") | |
| 1780 | + .await; | |
| 1781 | + assert_eq!(probe.status, StatusCode::PARTIAL_CONTENT); | |
| 1782 | + assert_eq!(probe.bytes, &marker[0..4]); | |
| 1783 | + assert_eq!( | |
| 1784 | + probe.content_range.as_deref(), | |
| 1785 | + Some(&format!("bytes 0-3/{}", marker.len())[..]) | |
| 1786 | + ); | |
| 1787 | + | |
| 1788 | + // The download is the original, byte for byte, whatever the preview is. | |
| 1789 | + let taken = app | |
| 1790 | + .get(&format!("/file/{}?dl=1", file.id), Some(&cookie)) | |
| 1791 | + .await; | |
| 1792 | + assert_eq!(taken.status, StatusCode::OK); | |
| 1793 | + assert_eq!(taken.bytes, mkv); | |
| 1794 | + assert_eq!(taken.bytes.len(), mkv.len()); | |
| 1795 | + assert_eq!(taken.content_type.as_deref(), Some("video/x-matroska")); | |
| 1796 | + assert!( | |
| 1797 | + taken | |
| 1798 | + .disposition | |
| 1799 | + .as_deref() | |
| 1800 | + .unwrap_or("") | |
| 1801 | + .starts_with("attachment") | |
| 1802 | + ); | |
| 1803 | +} | |
| 1804 | + | |
| 1805 | +/// A view-only public link previews the derivative — that is what the | |
| 1806 | +/// media stream is for — and still cannot be downloaded: `?dl=1` stays the | |
| 1807 | +/// dead card, and the original never travels. | |
| 1808 | +#[tokio::test] | |
| 1809 | +async fn view_only_link_previews_a_matroska_but_cannot_download() { | |
| 1810 | + let Some(mkv) = vp9_aac_matroska() else { | |
| 1811 | + return; | |
| 1812 | + }; | |
| 1813 | + let app = TestApp::build().await; | |
| 1814 | + let owner = owner_of(&app, "sub-admin").await; | |
| 1815 | + let file = app | |
| 1816 | + .store | |
| 1817 | + .insert_file(&owner, None, "clip.mkv", &mkv) | |
| 1818 | + .await | |
| 1819 | + .unwrap() | |
| 1820 | + .id; | |
| 1821 | + let created = app | |
| 1822 | + .store | |
| 1823 | + .create_share_link(&owner, ShareKind::File, &file, false, None, None) | |
| 1824 | + .await | |
| 1825 | + .unwrap(); | |
| 1826 | + | |
| 1827 | + let media = app | |
| 1828 | + .get(&format!("/s/{}?media=1", created.token), None) | |
| 1829 | + .await; | |
| 1830 | + assert_eq!(media.status, StatusCode::OK); | |
| 1831 | + assert_eq!(media.content_type.as_deref(), Some("video/webm")); | |
| 1832 | + assert_ne!(media.bytes, mkv, "the media stream was the original"); | |
| 1833 | + assert!(media.bytes.starts_with(&[0x1A, 0x45, 0xDF, 0xA3])); | |
| 1834 | + | |
| 1835 | + let blocked = app | |
| 1836 | + .get(&format!("/s/{}?dl=1", created.token), None) | |
| 1837 | + .await; | |
| 1838 | + assert!( | |
| 1839 | + blocked.text().contains("no longer works"), | |
| 1840 | + "view-only download showed: {}", | |
| 1841 | + blocked.text() | |
| 1842 | + ); | |
| 1843 | +} | |
| 1844 | + | |
| 1665 | 1845 | /// A password-protected link gates everything — card, download bytes — |
| 1666 | 1846 | /// until the browser answers the gate once; the proof then lives in the |
| 1667 | 1847 | /// link's own cookie. A wrong password answers the gate with the error and |