From 3134bfa3dc14109faf8c88cc805369b21a6da0be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 9 Sep 2026 03:32:59 +0300 Subject: [PATCH] =?UTF-8?q?a=20downloaded=20video=20previews=20in=20every?= =?UTF-8?q?=20browser,=20not=20just=20the=20lenient=20ones:=20an=20mkv=20t?= =?UTF-8?q?hat=20sniffs=20as=20webm=20but=20carries=20tracks=20webm=20neve?= =?UTF-8?q?r=20blessed=20(vp9=20with=20aac=20audio=20=E2=80=94=20the=20sha?= =?UTF-8?q?pe=20every=20tiktok=20downloader=20makes)=20played=20in=20chrom?= =?UTF-8?q?ium=20and=20stalled=20silently=20in=20firefox's=20stricter=20de?= =?UTF-8?q?muxer,=20so=20the=20media=20route=20now=20builds=20a=20legal=20?= =?UTF-8?q?preview=20beside=20the=20file=20on=20first=20view=20=E2=80=94?= =?UTF-8?q?=20vp9/8/av1=20keeps=20its=20bytes=20and=20the=20audio=20become?= =?UTF-8?q?s=20opus,=20h264=20remuxes=20to=20faststart=20mp4=20=E2=80=94?= =?UTF-8?q?=20cached=20under=20previews/,=20served=20to=20the=20player=20w?= =?UTF-8?q?ith=20ranges,=20deleted=20with=20the=20file=20in=20every=20purg?= =?UTF-8?q?e=20path,=20while=20downloads=20keep=20the=20original=20bytes?= =?UTF-8?q?=20untouched;=20a=20matroska=20is=20only=20called=20webm=20now?= =?UTF-8?q?=20when=20its=20tracks=20say=20so,=20and=20one=20length-read-af?= =?UTF-8?q?ter-adopt=20bug=20that=20served=20an=20empty=20first=20response?= =?UTF-8?q?=20died=20in=20the=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/im.toml | 3 + crates/in-core/src/store/mod.rs | 30 ++ crates/in-core/src/store/previews.rs | 562 ++++++++++++++++++++++++ crates/in-core/src/store/sniff.rs | 380 +++++++++++++++- crates/in-core/src/store/turso_store.rs | 72 ++- crates/in-core/src/thumbs.rs | 8 +- crates/in-web/src/files.rs | 49 ++- crates/in-web/src/main.rs | 9 +- crates/in-web/src/share.rs | 25 +- crates/in-web/tests/http.rs | 182 +++++++- 10 files changed, 1294 insertions(+), 26 deletions(-) create mode 100644 config/im.toml create mode 100644 crates/in-core/src/store/previews.rs diff --git a/config/im.toml b/config/im.toml new file mode 100644 index 0000000..74e47cd --- /dev/null +++ b/config/im.toml @@ -0,0 +1,3 @@ +database = "im.db" +listen = "127.0.0.1:7650" +issuer = "http://127.0.0.1:7650" diff --git a/crates/in-core/src/store/mod.rs b/crates/in-core/src/store/mod.rs index 6865b10..627e7e0 100644 --- a/crates/in-core/src/store/mod.rs +++ b/crates/in-core/src/store/mod.rs @@ -26,6 +26,8 @@ pub mod sniff; pub mod turso_store; #[cfg(feature = "server")] pub mod r2; +#[cfg(feature = "server")] +pub mod previews; #[cfg(feature = "server")] pub use reconcile::{ReconcileOptions, reconcile}; @@ -167,6 +169,19 @@ pub struct FileSpan { pub stream: ByteStream, } +/// A preview derivative ready to serve in a video's place: the mime its own +/// bytes declare — the row's stored mime may say webm about an AAC-in-webm +/// Matroska no browser will play — and the honest length to serve. Built +/// once at media-serve time; `?dl=1` never sees it, a download is the +/// original. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MediaDerivative { + /// The container the derivative's bytes are, not the row's stored mime. + pub mime: &'static str, + /// The derivative's length, as the blob holds it. + pub size: u64, +} + /// Whether a file's thumbnail exists. `None` for bytes no thumbnail is /// attempted for; `Pending` while one is being made; `Ready` or `Failed` /// once the attempt settled. @@ -499,6 +514,21 @@ pub trait Store: 'static + Send + Sync { /// when no thumbnail was made, or its file went missing. async fn thumb_bytes(&self, id: &str) -> Result>>; + /// The preview derivative standing in for this video at media-serve + /// time — built on this first ask when the stored tracks need one (one + /// `ffmpeg` transcode, minutes for a long file), a cache read after + /// that — or `None`, the answer for anything that is not a video + /// container, already plays as stored, has no recipe, or whose build + /// failed: the caller serves the original, today's behavior either way. + async fn media_derivative(&self, id: &str) -> Result>; + + /// The cached derivative's bytes as a stream — `media_derivative`'s + /// answer is what names it. Same clamping contract as + /// [`Store::file_stream`]: a range serve reads only its span, and the + /// span is the span that exists. + async fn derivative_stream(&self, id: &str, start: u64, len: u64) + -> Result>; + /// Counts one user-facing download of a file's bytes. Byte routes call /// this once per download they complete — on `?dl=1` serves, not per /// range chunk, never for inline previews, thumbnails, or internal reads diff --git a/crates/in-core/src/store/previews.rs b/crates/in-core/src/store/previews.rs new file mode 100644 index 0000000..f832f46 --- /dev/null +++ b/crates/in-core/src/store/previews.rs @@ -0,0 +1,562 @@ +//! Preview derivatives: the playable stand-in for a video whose stored +//! bytes a browser cannot demux as they sit. +//! +//! The stored file is never rewritten — `?dl=1` and every download still +//! serve the original bytes byte for byte. What this module adds is a +//! second blob at `previews/`, built the first time a media route asks +//! to serve a file whose tracks are not what its container's magic claims: +//! the AAC-in-webm Matroska the sniffer used to have to call `video/webm` +//! (Firefox demuxes the VP9 and refuses the audio), HEVC-in-mp4, and kin. +//! After that one build, every media serve draws from the derivative. +//! +//! The build is one `ffmpeg` child under the same house rules +//! [`crate::thumbs`] runs — `-v error`, a runaway killed, output that must +//! declare itself the container it was asked for — staged to a temp file in +//! the previews tree and placed with [`Blobs::adopt`], so a reader of +//! `previews/` sees nothing or the whole derivative, never half, and +//! two racing builders cannot tear it. Every failure serves the original: +//! a derivative that cannot be made is a miss, not an error. + +use std::collections::HashMap; +use std::io::Read as _; +use std::path::Path; +use std::process::{Command, Stdio}; +use std::sync::{LazyLock, Mutex}; +use std::time::{Duration, Instant}; + +use futures_util::StreamExt; +use tokio::io::AsyncWriteExt as _; +use ulid::Ulid; + +use super::blobs::Blobs; +use super::sniff::{self, Track, TrackKind}; +use super::MediaDerivative; +use super::turso_store::FILES_DIR; + +/// The key family derivatives live in: `previews/`, beside `files/` and +/// `thumbs/` — deleted alongside them in every purge, and swept for orphans +/// at boot under the same watermark rule as every other half of the tree. +pub(super) const PREVIEWS_DIR: &str = "previews"; + +/// Head bytes inspected for a Matroska `Tracks` element. Muxers write the +/// tracks before the clusters, so the element sits near the head of every +/// real file; a Matroska that does not show it in this window is one the +/// verdict declines to name, and the original is served. +const DETECT_WINDOW: u64 = 1024 * 1024; + +/// The largest `moov` read whole for track inspection. A `moov` bigger than +/// this carries no codecs this needs — and a bound is what keeps a hostile +/// box walk from allocating to a size it names itself. +const MOOV_CAP: u64 = 16 * 1024 * 1024; + +/// How long one derivative build may run before it is killed. Unlike the +/// thumbnailer's one frame, this is a whole transcode of a whole file — +/// minutes, not milliseconds — but a build past ten minutes is wedged, and +/// the request behind it is better served the original. +const BUILD_TIMEOUT: Duration = Duration::from_secs(10 * 60); + +/// What to do with a file's stored bytes at media-serve time. +enum Plan { + /// The stored tracks play as they sit: serve the original. + Native, + /// Build this derivative first, then serve it. + Build(Build), + /// No recipe this module knows: serve the original, today's behavior. + Unsupported, +} + +/// One derivative worth building, and the `ffmpeg` recipe for it. +enum Build { + /// VP8/VP9/AV1 video stream-copied, the audio transcoded to Opus, + /// muxed as the webm the tracks were almost legal for. + Webm { video: bool, audio: bool }, + /// H.264 or H.265 video with AAC (or no) audio, remuxed into a + /// faststart mp4 — no re-encode, one container the browsers demux. + RemuxMp4 { audio: bool }, +} + +impl Build { + /// The mime the result will carry. + fn mime(&self) -> &'static str { + match self { + Build::Webm { .. } => "video/webm", + Build::RemuxMp4 { .. } => "video/mp4", + } + } + + /// The `ffmpeg` arguments: explicit stream maps, so nothing a track + /// parser never blessed — a subtitle, an attachment — rides along. + fn args(&self, input: &Path, output: &Path) -> Vec { + let mut args: Vec = vec![ + "-v".into(), + "error".into(), + "-y".into(), + "-i".into(), + input.display().to_string(), + ]; + match self { + Build::Webm { video, audio } => { + if *video { + args.extend(["-map", "0:v:0", "-c:v", "copy"].map(str::to_string)); + } + if *audio { + args.extend(["-map", "0:a:0", "-c:a", "libopus"].map(str::to_string)); + } + args.extend(["-f", "webm"].map(str::to_string)); + } + Build::RemuxMp4 { audio } => { + args.extend(["-map", "0:v:0"].map(str::to_string)); + if *audio { + args.extend(["-map", "0:a:0"].map(str::to_string)); + } + args.extend( + ["-c", "copy", "-movflags", "+faststart", "-f", "mp4"].map(str::to_string), + ); + } + } + args.push(output.display().to_string()); + args + } +} + +/// The derivative to serve for file `id` — built first, when the stored +/// tracks need one — or `None`, the answer for every file that is not a +/// video container, already plays, has no recipe, or whose build failed. +/// A first request may wait one whole transcode; the permit makes every +/// later one a cache read. +pub(super) async fn ensure( + storage: &Path, + blobs: &dyn Blobs, + id: &str, + mime: &str, +) -> Option { + if !is_video_container(mime) { + return None; + } + let key = format!("{PREVIEWS_DIR}/{id}"); + if let Some(ready) = cached(blobs, &key).await { + return Some(ready); + } + let permit = build_permit(id).await; + let _guard = permit.lock().await; + if let Some(ready) = cached(blobs, &key).await { + release_permit(id); + return Some(ready); + } + let built = match detect(blobs, id).await { + Plan::Native | Plan::Unsupported => None, + Plan::Build(build) => build_derivative(storage, blobs, id, &key, build).await, + }; + release_permit(id); + built +} + +/// The video containers a derivative may stand in for — the spellings the +/// sniffer and the moviemakers actually produce. +fn is_video_container(mime: &str) -> bool { + matches!( + mime, + "video/mp4" | "video/webm" | "video/quicktime" | "video/x-matroska" + ) +} + +/// The derivative already sitting at `key`, its mime read from its own head +/// — a restart forgets the recipe, not the derivative. A blob whose head +/// names no container is not a derivative: `None`, and the caller rebuilds. +async fn cached(blobs: &dyn Blobs, key: &str) -> Option { + let span = blobs.span(key, 0, u64::MAX).await.ok()??; + let head = read_stream(span.stream, 12).await; + let mime = container_mime(&head)?; + Some(MediaDerivative { + mime, + size: span.len, + }) +} + +/// The container a head of bytes declares: EBML magic or an `ftyp` box. +fn container_mime(head: &[u8]) -> Option<&'static str> { + if head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) { + Some("video/webm") + } else if head.len() >= 12 && &head[4..8] == b"ftyp" { + Some("video/mp4") + } else { + None + } +} + +/// What the stored bytes are, decided without staging: the tracks are read +/// out of windows of the blob, and only a build actually wanted drags the +/// whole original to disk. +async fn detect(blobs: &dyn Blobs, id: &str) -> Plan { + let key = format!("{FILES_DIR}/{id}"); + let head = match read_span(blobs, &key, 0, DETECT_WINDOW).await { + Some(found) => found, + None => return Plan::Unsupported, + }; + if head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) { + return match sniff::ebml_tracks(&head) { + None => Plan::Unsupported, + Some(tracks) if sniff::webm_legal(&tracks) => Plan::Native, + Some(tracks) => matroska_plan(&tracks), + }; + } + if head.len() >= 12 && &head[4..8] == b"ftyp" { + let total = match read_span_len(blobs, &key).await { + Some(len) => len, + None => return Plan::Unsupported, + }; + return mp4_plan(blobs, &key, total).await; + } + Plan::Unsupported +} + +/// The build for Matroska tracks that are not webm-legal: VP8/VP9/AV1 video +/// stream-copies into a real webm with whatever audio there is transcoded to +/// Opus; H.264 or H.265 with AAC (or silence) remuxes into a faststart mp4. +/// Anything else has no recipe worth a transcode — the original is what +/// plays-or-doesn't today. +fn matroska_plan(tracks: &[Track]) -> Plan { + let video = first_codec_of(tracks, TrackKind::Video); + let audio = first_codec_of(tracks, TrackKind::Audio); + let webm_video = matches!(video, Some("v_vp8" | "v_vp9" | "v_av1")); + let aac = matches!(audio, Some("a_aac")); + if webm_video { + return Plan::Build(Build::Webm { + video: video.is_some(), + audio: audio.is_some(), + }); + } + if matches!(video, Some("v_mpeg4/iso/avc" | "v_mpegh/iso/hevc")) + && (audio.is_none() || aac) + { + return Plan::Build(Build::RemuxMp4 { + audio: audio.is_some(), + }); + } + Plan::Unsupported +} + +/// The mp4 plan: an mp4 that is not native is helped only when its tracks +/// are the remuxable kind — H.264/H.265 video with AAC (or no) audio — +/// where the fix is the faststart moov, not the codecs. +async fn mp4_plan(blobs: &dyn Blobs, key: &str, total: u64) -> Plan { + let Some((moov_start, moov_len)) = moov_location(blobs, key, total).await else { + return Plan::Unsupported; + }; + if moov_len > MOOV_CAP { + return Plan::Unsupported; + } + let Some(moov) = read_span(blobs, key, moov_start, moov_len).await else { + return Plan::Unsupported; + }; + let tracks = sniff::mp4_tracks(&moov); + if sniff::mp4_native(&tracks) { + return Plan::Native; + } + let video = first_codec_of(&tracks, TrackKind::Video); + let audio = first_codec_of(&tracks, TrackKind::Audio); + if matches!(video, Some(codec) if codec.starts_with("avc") || codec == "hev1" || codec == "hvc1") + && (audio.is_none() || audio == Some("mp4a")) + { + return Plan::Build(Build::RemuxMp4 { + audio: audio.is_some(), + }); + } + Plan::Unsupported +} + +/// Where the `moov` sits: `(body offset, body length)`, walked one header +/// at a time — each read 16 bytes off the blob, each `mdat` skipped by its +/// declared size — so a faststart-less file, moov behind megabytes of +/// media, costs a handful of range reads and never the file. A `size` of 0 +/// (to end of file, the streaming-written shape) resolves against the +/// blob's own length; a walk that runs off the file finds nothing. +async fn moov_location(blobs: &dyn Blobs, key: &str, total: u64) -> Option<(u64, u64)> { + let mut at = 0u64; + for _ in 0..64 { + let header = read_span(blobs, key, at, 16).await?; + if header.len() < 8 { + return None; + } + let size = + u32::from_be_bytes([header[0], header[1], header[2], header[3]]) as u64; + let typ = [header[4], header[5], header[6], header[7]]; + let (header_len, box_len) = match size { + 1 => { + if header.len() < 16 { + return None; + } + ( + 16u64, + u64::from_be_bytes([ + header[8], header[9], header[10], header[11], header[12], header[13], + header[14], header[15], + ]), + ) + } + 0 => (8u64, total - at), + size => (8u64, size), + }; + if box_len < header_len { + return None; + } + if typ == *b"moov" { + return Some((at + header_len, box_len - header_len)); + } + at += box_len; + } + None +} +/// The codec of a kind's first track, for the verdicts that weigh one +/// stream of each class. +fn first_codec_of<'a>(tracks: &'a [Track], kind: TrackKind) -> Option<&'a str> { + tracks + .iter() + .find(|track| track.kind == kind) + .map(|track| track.codec.as_str()) +} + +/// Builds and places the derivative: stage the original, run one `ffmpeg` +/// child on it, adopt the result into place. The staging lives in the +/// previews tree so the adopt's rename is same-filesystem atomic. Any miss +/// answers `None` — the original is what the caller serves — and leaves +/// nothing behind but a log line. +async fn build_derivative( + storage: &Path, + blobs: &dyn Blobs, + id: &str, + key: &str, + build: Build, +) -> Option { + let dir = storage.join(PREVIEWS_DIR); + if std::fs::create_dir_all(&dir).is_err() { + return None; + } + let staged = dir.join(format!("{id}.{}.in.tmp", Ulid::new())); + let output = dir.join(format!("{id}.{}.out.tmp", Ulid::new())); + let staged_ok = stage_original(blobs, id, &staged).await.is_some(); + let built = if staged_ok { + let input = staged.clone(); + let target = output.clone(); + tokio::task::spawn_blocking(move || run_ffmpeg(&build, &input, &target)) + .await + .ok() + } else { + None + }; + // The length is read before the adopt: the adopt renames the staging + // away, and the honest serving length is the file that was placed. + let len = file_len(&output); + let derivative = match built { + Some(Ok(mime)) if len > 0 => match blobs.adopt(key, &output, len).await { + Ok(()) => Some(MediaDerivative { mime, size: len }), + Err(_) => None, + }, + _ => None, + }; + let _ = std::fs::remove_file(&staged); + let _ = std::fs::remove_file(&output); + derivative +} + +/// A file's length, `0` when it has gone missing — an adopt refuses a +/// missing staging anyway, and the caller serves the original. +fn file_len(path: &Path) -> u64 { + std::fs::metadata(path).map(|meta| meta.len()).unwrap_or(0) +} + +/// Copies the original blob to `dest`, frame by frame — never the whole +/// file in one buffer. `None` when the blob is not there to copy. +async fn stage_original(blobs: &dyn Blobs, id: &str, dest: &Path) -> Option<()> { + let span = blobs + .span(&format!("{FILES_DIR}/{id}"), 0, u64::MAX) + .await + .ok()??; + let mut file = tokio::fs::File::create(dest).await.ok()?; + let mut stream = span.stream; + while let Some(chunk) = stream.next().await { + file.write_all(&chunk.ok()?).await.ok()?; + } + file.flush().await.ok()?; + Some(()) +} + +/// Runs one derivative build: the recipe's `ffmpeg` arguments, the +/// container bytes into `output`. The same house rules as the thumbnailer — +/// `-v error`, a runaway killed, output that must declare the container it +/// was asked for — with stderr captured for the one failure line. `Err` +/// carries nothing: the caller's contract is "serve the original". +fn run_ffmpeg(build: &Build, input: &Path, output: &Path) -> Result<&'static str, ()> { + let mut child = Command::new("ffmpeg") + .args(build.args(input, output)) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|_| ())?; + // stderr drains on its own thread: the pipe buffer is small, and a + // parent that only `try_wait`s while the child fills it would deadlock + // against it. + let stderr = child.stderr.take(); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let mut message = String::new(); + if let Some(mut err) = stderr { + let _ = err.read_to_string(&mut message); + } + let _ = tx.send(message); + }); + let start = Instant::now(); + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break status.success(), + Ok(None) => { + if start.elapsed() >= BUILD_TIMEOUT { + let _ = child.kill(); + let _ = child.wait(); + break false; + } + std::thread::sleep(Duration::from_millis(50)); + } + Err(_) => break false, + } + }; + // Whatever left the pipe must be the container asked for, and nonempty: + // ffmpeg exits 0 over some failures it has already printed. + let mut head = [0u8; 12]; + let head_len = std::fs::File::open(output) + .and_then(|mut file| file.read(&mut head)) + .unwrap_or(0); + let mime = container_mime(&head[..head_len]); + match (status, mime) { + (true, Some(mime)) if mime == build.mime() => Ok(mime), + _ => { + let message = rx.recv().unwrap_or_default(); + let reason = message.lines().next().unwrap_or("no output"); + eprintln!("preview build for {} failed: {reason}", input.display()); + Err(()) + } + } +} + +/// The derivative to serve, straight off the key: same clamping contract as +/// the file stream, so a range serve reads only its span. +pub(super) async fn stream( + blobs: &dyn Blobs, + id: &str, + start: u64, + len: u64, +) -> Option { + blobs + .span(&format!("{PREVIEWS_DIR}/{id}"), start, len) + .await + .ok()? +} + +/// `len` bytes of a blob from `start`, buffered whole — the windows track +/// detection reads, never the file a transcode consumes. +async fn read_span(blobs: &dyn Blobs, key: &str, start: u64, len: u64) -> Option> { + let span = blobs.span(key, start, len).await.ok()??; + let bytes = read_stream(span.stream, span.len).await; + if bytes.len() as u64 == span.len { + Some(bytes) + } else { + None + } +} + +/// A blob's honest length: the span clamp against what the backend holds. +async fn read_span_len(blobs: &dyn Blobs, key: &str) -> Option { + blobs.span(key, 0, u64::MAX).await.ok()?.map(|span| span.len) +} + +/// Drains a span's stream into one buffer, capped at `max` bytes. +async fn read_stream( + mut stream: super::ByteStream, + max: u64, +) -> Vec { + let mut out = Vec::new(); + while out.len() < max as usize { + match stream.next().await { + Some(Ok(chunk)) => out.extend_from_slice(&chunk), + _ => break, + } + } + out +} + +/// One builder at a time per file: a permit per id in flight. The map +/// holds one entry per id whose build is somewhere running — the entry +/// leaves when its last holder is done, so the map never grows past the +/// files being built right now. +static PERMITS: LazyLock>>>> = + LazyLock::new(Default::default); + +/// The holder of a build: take one, guard it for the length of `ensure`. +async fn build_permit(id: &str) -> std::sync::Arc> { + PERMITS + .lock() + .expect("permit map") + .entry(id.to_string()) + .or_default() + .clone() +} + +/// Forgets a permit whose last holder just finished — the map's own +/// strong count is the only reader it can trust. +fn release_permit(id: &str) { + let mut permits = PERMITS.lock().expect("permit map"); + if let Some(permit) = permits.get(id) { + if std::sync::Arc::strong_count(permit) == 1 { + permits.remove(id); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn recipes_ask_for_the_containers_they_name() { + let webm = Build::Webm { + video: true, + audio: true, + }; + assert_eq!(webm.mime(), "video/webm"); + let args = webm.args(Path::new("in.mkv"), Path::new("out.tmp")); + let args: Vec<&str> = args.iter().map(String::as_str).collect(); + assert!(args.windows(2).any(|pair| pair == ["-c:v", "copy"])); + assert!(args.windows(2).any(|pair| pair == ["-c:a", "libopus"])); + let remux = Build::RemuxMp4 { audio: true }; + let remux_args = remux.args(Path::new("in.mp4"), Path::new("out.tmp")); + let args: Vec<&str> = remux_args.iter().map(String::as_str).collect(); + assert!(args.windows(2).any(|pair| pair == ["-c", "copy"])); + assert!(args.windows(2).any(|pair| pair == ["-movflags", "+faststart"])); + } + #[tokio::test] + async fn moov_location_walks_past_mdat_by_its_declared_size() { + // ftyp, then an mdat far bigger than any head window, then moov — + // the faststart-less shape the walk exists for. + let dir = std::env::temp_dir().join(format!("in-preview-{}", Ulid::new())); + std::fs::create_dir_all(dir.join("files")).unwrap(); + let mut bytes = Vec::new(); + bytes.extend_from_slice(&8u32.to_be_bytes()); + bytes.extend_from_slice(b"ftyp"); + let mdat_body = 10u64 * 1024 * 1024; + bytes.extend_from_slice(&((mdat_body + 8) as u32).to_be_bytes()); + bytes.extend_from_slice(b"mdat"); + bytes.extend(std::iter::repeat_n(0u8, mdat_body as usize)); + bytes.extend_from_slice(&(24u32).to_be_bytes()); + bytes.extend_from_slice(b"moov"); + bytes.extend([0u8; 16]); + std::fs::write(dir.join("files").join("x"), &bytes).unwrap(); + let total = bytes.len() as u64; + let blobs = super::super::blobs::LocalBlobs::new(&dir); + assert_eq!( + moov_location(&blobs, "files/x", total).await, + Some((total - 16, 16)) + ); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/in-core/src/store/sniff.rs b/crates/in-core/src/store/sniff.rs index d83a465..24e8ae3 100644 --- a/crates/in-core/src/store/sniff.rs +++ b/crates/in-core/src/store/sniff.rs @@ -81,7 +81,7 @@ pub fn sniff(bytes: &[u8]) -> &'static str { } else if bytes.len() >= 8 && &bytes[4..8] == b"ftyp" { "video/mp4" } else if bytes.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) { - "video/webm" + matroska_mime(bytes) } else if bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP" { "image/webp" } 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 { } } +/// What an EBML file is called. `video/webm` only when its tracks are all +/// webm-legal — the container's promise is the tracks, not the magic, and +/// the sniffer spent years calling every Matroska a webm, which Firefox +/// answers with silence when the audio turns out to be AAC. Bytes this +/// parser cannot bound keep their old name: an unparseable Matroska stays +/// `video/webm`, the verdict every EBML file wore before tracks counted. +fn matroska_mime(bytes: &[u8]) -> &'static str { + match ebml_tracks(bytes) { + Some(tracks) if webm_legal(&tracks) => "video/webm", + Some(_) => "video/x-matroska", + None => "video/webm", + } +} + +/// One track a container declares: its class, and the codec it names — a +/// Matroska `CodecID` such as `V_VP9`, or an ISO-BMFF sample-entry FourCC +/// such as `avc1` — lowercased so every verdict compares one spelling. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Track { + pub kind: TrackKind, + pub codec: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum TrackKind { + Video, + Audio, + Other, +} + +/// The Matroska tracks, read straight out of the bytes: the EBML header, +/// then the `Segment`'s children down to the `Tracks` element, one entry +/// per `TrackEntry` (`TrackType`, then `CodecID`). `None` when the +/// structure cannot be walked — an element whose size cannot be skipped, +/// a cluster met before the tracks — and the caller keeps its old verdict. +/// A track wearing `ContentEncodings` reads as unknown: a header-compressed +/// or encrypted track is not the codec its `CodecID` names. +pub(crate) fn ebml_tracks(bytes: &[u8]) -> Option> { + let end = bytes.len(); + let (_, _, _, header_end) = ebml_element(bytes, 0, end)?; + let (id, _, segment, segment_end) = ebml_element(bytes, header_end, end)?; + if id != 0x1853_8067 { + return None; // Segment + } + let mut at = segment; + while at < segment_end { + let (id, _, start, stop) = ebml_element(bytes, at, segment_end)?; + match id { + // Tracks + 0x1654_AE6B => return Some(track_entries(bytes, start, stop)), + // Cluster: muxers write the tracks before the clusters, so one + // met here means the walk is done looking. + 0x1F43_B675 => return None, + _ => {} + } + at = stop; + } + None +} + +/// The `TrackEntry`s of a `Tracks` payload: each entry's `TrackType` (1 is +/// video, 2 audio, anything else a kind webm has no word for) and its +/// `CodecID`. An entry with neither is a track no verdict can trust. +fn track_entries(bytes: &[u8], start: usize, end: usize) -> Vec { + let mut tracks = Vec::new(); + let mut at = start; + while at < end { + let (id, _, entry, entry_end) = match ebml_element(bytes, at, end) { + Some(found) => found, + None => break, + }; + at = entry_end; + if id != 0xAE { + continue; // TrackEntry + } + let (mut kind, mut codec, mut encoded) = (TrackKind::Other, None, false); + let mut inner = entry; + while inner < entry_end { + let (id, _, value, value_end) = match ebml_element(bytes, inner, entry_end) { + Some(found) => found, + None => break, + }; + inner = value_end; + match id { + 0x83 => { + if let Some(number) = ebml_uint(bytes, value, value_end) { + kind = match number { + 1 => TrackKind::Video, + 2 => TrackKind::Audio, + _ => TrackKind::Other, + }; + } + } + 0x86 => { + codec = Some(String::from_utf8_lossy(&bytes[value..value_end]).into_owned()); + } + // ContentEncodings: header compression or encryption. + 0x6D80 => encoded = true, + _ => {} + } + } + if encoded { + codec = Some(String::new()); + } + tracks.push(Track { + kind, + codec: codec.unwrap_or_default().to_lowercase(), + }); + } + tracks +} + +/// Whether every track is one a webm muxer may hold: video in the codec set +/// the container was cut down to (VP8, VP9, AV1), audio in its pair +/// (Vorbis, Opus), nothing else — and at least one track, since a file with +/// no tracks gives the verdict nothing to stand on. +pub(crate) fn webm_legal(tracks: &[Track]) -> bool { + !tracks.is_empty() + && tracks.iter().all(|track| match track.kind { + TrackKind::Video => matches!(track.codec.as_str(), "v_vp8" | "v_vp9" | "v_av1"), + TrackKind::Audio => matches!(track.codec.as_str(), "a_vorbis" | "a_opus"), + TrackKind::Other => false, + }) +} + +/// The tracks an mp4's `moov` declares, one per `trak`: the class from the +/// `mdia/hdlr` handler, the codec from the first `stsd` sample entry. An +/// mp4 this cannot read comes back with no tracks, which the verdicts +/// treat as native — nothing here may take the original away on a guess. +pub(crate) fn mp4_tracks(moov: &[u8]) -> Vec { + let mut tracks = Vec::new(); + let mut at = 0usize; + while at < moov.len() { + let (typ, _, body, body_end) = match box_at(moov, at, moov.len()) { + Some(found) => found, + None => break, + }; + at = body_end; + if typ != *b"trak" { + continue; + } + tracks.push(trak_track(moov, body, body_end)); + } + tracks +} + +/// Whether an mp4's tracks are ones a browser demuxes as they sit: H.264 +/// video and AAC audio, nothing else in. Tracks of no known class — a hint +/// or metadata track — do not stand in the way; an unreadable codec does. +pub(crate) fn mp4_native(tracks: &[Track]) -> bool { + tracks.iter().all(|track| match track.kind { + TrackKind::Video => track.codec.starts_with("avc"), + TrackKind::Audio => track.codec == "mp4a", + TrackKind::Other => true, + }) +} + +/// One `trak`: its handler's class and its first sample entry's codec. +fn trak_track(bytes: &[u8], start: usize, end: usize) -> Track { + let unknown = Track { + kind: TrackKind::Other, + codec: String::new(), + }; + let (media, media_end) = match find_box(bytes, start, end, b"mdia") { + Some(found) => found, + None => return unknown, + }; + // `hdlr`'s handler FourCC sits after its version/flags and reserved + // quad — twelve bytes into the box body. + let kind = find_box(bytes, media, media_end, b"hdlr") + .filter(|&(head, _)| bytes.len() >= head + 12) + .map(|(head, _)| match &bytes[head + 8..head + 12] { + b"vide" => TrackKind::Video, + b"soun" => TrackKind::Audio, + _ => TrackKind::Other, + }) + .unwrap_or(TrackKind::Other); + let codec = find_box(bytes, media, media_end, b"minf") + .and_then(|(minf, minf_end)| find_box(bytes, minf, minf_end, b"stbl")) + .and_then(|(stbl, stbl_end)| find_box(bytes, stbl, stbl_end, b"stsd")) + .and_then(|(stsd, stsd_end)| stsd_codec(bytes, stsd, stsd_end)) + .unwrap_or_default(); + Track { kind, codec } +} + +/// The codec of an `stsd`'s first sample entry: the FourCC right after the +/// entry's size — `avc1`, `mp4a`, `ac-3`, whatever the track really is. +fn stsd_codec(bytes: &[u8], start: usize, end: usize) -> Option { + let entry = start.checked_add(8)?; // version/flags, then entry count + if bytes.len() < entry + 8 || end < entry + 8 { + return None; + } + Some( + String::from_utf8_lossy(&bytes[entry + 4..entry + 8]) + .into_owned() + .to_lowercase(), + ) +} + +/// The body of the first box named `want`, between `start` and `end`. +fn find_box(bytes: &[u8], start: usize, end: usize, want: &[u8; 4]) -> Option<(usize, usize)> { + let mut at = start; + while at < end { + let (typ, _, body, body_end) = box_at(bytes, at, end)?; + if &typ == want { + return Some((body, body_end)); + } + at = body_end.max(at + 8); + } + None +} + +/// One ISO-BMFF box at `at`, bounded by `end`: its FourCC and the bounds +/// of its body. A `size` of 1 promotes to the 64-bit largesize; a `size` +/// of 0 runs to the end of the bytes. Anything malformed stops the walk. +fn box_at(bytes: &[u8], at: usize, end: usize) -> Option<([u8; 4], usize, usize, usize)> { + let head = bytes.get(at..end)?; + if head.len() < 8 { + return None; + } + let typ = [head[4], head[5], head[6], head[7]]; + let (header, total) = match u32::from_be_bytes([head[0], head[1], head[2], head[3]]) as u64 { + 1 => { + if head.len() < 16 { + return None; + } + let large = u64::from_be_bytes([ + head[8], head[9], head[10], head[11], head[12], head[13], head[14], head[15], + ]); + (16usize, usize::try_from(large).ok()?) + } + 0 => (8usize, head.len()), + size => (8usize, size as usize), + }; + let body_end = at.checked_add(total)?; + if total < header || body_end > end { + return None; + } + Some((typ, at, at + header, body_end)) +} + +/// One EBML element at `at`, bounded by `end`: its id, its payload size, +/// and the payload's bounds. The id keeps its marker bits — the length +/// encoding is the id — and the size drops them. A payload claiming past +/// `end` is clamped: a truncated tail decides nothing here. `None` for an +/// unknown-size element — a live-stream shape a file has no business +/// carrying — and for bytes that end inside a header. +fn ebml_element(bytes: &[u8], at: usize, end: usize) -> Option<(u32, u64, usize, usize)> { + let head = bytes.get(at..end)?; + let id_width = head.first()?.leading_zeros() as usize + 1; + if head.len() < id_width || id_width > 4 { + return None; + } + let mut id = head[0] as u64; + for &byte in &head[1..id_width] { + id = (id << 8) | byte as u64; + } + let id = id as u32; + // The size vint follows, same width rule, marker dropped. + let rest = &head[id_width..]; + let size_width = rest.first()?.leading_zeros() as usize + 1; + if rest.len() < size_width { + return None; + } + let marker = 0xFFu8.checked_shr(size_width as u32).unwrap_or(0); + let mut size = (rest[0] & marker) as u64; + for &byte in &rest[1..size_width] { + size = (size << 8) | byte as u64; + } + // Every value bit set is the unknown size — unbounded, so not a file. + if size == (1u64 << (7 * size_width)) - 1 { + return None; + } + let start = at + id_width + size_width; + let stop = start + .checked_add(usize::try_from(size).ok()?)? + .min(end); + Some((id, size, start, stop)) +} + +/// The unsigned integer an element's payload holds — `TrackType` and kin. +fn ebml_uint(bytes: &[u8], start: usize, end: usize) -> Option { + let value = bytes.get(start..end)?; + if value.len() > 8 { + return None; + } + let mut number = 0u64; + for &byte in value { + number = (number << 8) | byte as u64; + } + Some(number) +} + /// Which office document a zip's bytes declare, decided the way every reader /// of the format does: by the entry names a zip stores uncompressed. Ends in /// [`GENERIC_MIME_TYPES`]' zip bucket when the names name nothing. @@ -363,4 +656,89 @@ mod tests { // claims one — the marker is entry content, not an entry name. assert_eq!(office_entry_mime(head), None); } + fn matroska(tracks: &[(&str, u64)]) -> Vec { + let entries: Vec = tracks + .iter() + .flat_map(|&(codec, kind)| { + let mut entry = vec![0x83, 0x81, kind as u8, 0x86, 0x80 | codec.len() as u8]; + entry.extend_from_slice(codec.as_bytes()); + ebml(&[0xAE], &entry) + }) + .collect(); + let mut bytes = ebml(&[0x1A, 0x45, 0xDF, 0xA3], b""); + bytes.extend(ebml( + &[0x18, 0x53, 0x80, 0x67], + &ebml(&[0x16, 0x54, 0xAE, 0x6B], &entries), + )); + bytes + } + + /// An ISO-BMFF box: size, FourCC, body. + fn boxy(typ: &[u8; 4], body: &[u8]) -> Vec { + let mut bytes = ((body.len() + 8) as u32).to_be_bytes().to_vec(); + bytes.extend_from_slice(typ); + bytes.extend_from_slice(body); + bytes + } + + /// An EBML element: id, a one-octet size vint (marker bit on — the + /// bodies here stay under 128 bytes), body. + fn ebml(id: &[u8], body: &[u8]) -> Vec { + let mut bytes = id.to_vec(); + bytes.push(0x80 | body.len() as u8); + bytes.extend_from_slice(body); + bytes + } + fn moov(tracks: &[(&[u8; 4], &[u8; 4])]) -> Vec { + let traks: Vec = tracks + .iter() + .flat_map(|&(handler, codec)| { + let hdlr = boxy(b"hdlr", &[0, 0, 0, 0, 0, 0, 0, 0, handler[0], handler[1], handler[2], handler[3]]); + 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]]); + boxy(b"trak", &boxy(b"mdia", &[&hdlr[..], &boxy(b"minf", &boxy(b"stbl", &stsd))].concat())) + }) + .collect(); + boxy(b"moov", &traks) + } + + #[test] + fn a_matroska_counts_as_webm_only_when_its_tracks_are() { + let legal = matroska(&[("V_VP9", 1), ("A_OPUS", 2)]); + assert_eq!(sniff(&legal), "video/webm"); + let vp9_video_only = matroska(&[("V_VP9", 1)]); + assert_eq!(sniff(&vp9_video_only), "video/webm"); + // The AAC-in-webm mkv that started this: same magic, silent in + // Firefox until a derivative exists. + let aac = matroska(&[("V_VP9", 1), ("A_AAC", 2)]); + assert_eq!(sniff(&aac), "video/x-matroska"); + let h264 = matroska(&[("V_MPEG4/ISO/AVC", 1), ("A_AAC", 2)]); + assert_eq!(sniff(&h264), "video/x-matroska"); + // A subtitle track is a track webm's rule has no word for. + let subtitle = matroska(&[("V_VP9", 1), ("A_OPUS", 2), ("S_TEXT/UTF8", 0x11)]); + assert_eq!(sniff(&subtitle), "video/x-matroska"); + } + + #[test] + fn an_unparseable_matroska_keeps_its_old_name() { + assert_eq!(sniff(&[0x1A, 0x45, 0xDF, 0xA3, 0x00, 0x00]), "video/webm"); + } + + #[test] + fn an_mp4_is_native_only_for_h264_video_and_aac_audio() { + // The walk runs over moov's body, the way `previews` reads it out + // of the blob — hence the `[8..]` past each box's own header. + let tracks = mp4_tracks(&moov(&[(b"vide", b"avc1"), (b"soun", b"mp4a")])[8..]); + assert_eq!(tracks.len(), 2); + assert!(mp4_native(&tracks)); + let hevc = mp4_tracks(&moov(&[(b"vide", b"hev1"), (b"soun", b"mp4a")])[8..]); + assert!(!mp4_native(&hevc)); + let ac3 = mp4_tracks(&moov(&[(b"vide", b"avc1"), (b"soun", b"ac-3")])[8..]); + assert!(!mp4_native(&ac3)); + // A hint track (handler neither video nor audio) stands aside. + let hinted = mp4_tracks( + &moov(&[(b"vide", b"avc1"), (b"soun", b"mp4a"), (b"hint", b"rtp ")])[8..], + ); + assert!(mp4_native(&hinted)); + } + } diff --git a/crates/in-core/src/store/turso_store.rs b/crates/in-core/src/store/turso_store.rs index 6870920..4ba8c02 100644 --- a/crates/in-core/src/store/turso_store.rs +++ b/crates/in-core/src/store/turso_store.rs @@ -23,14 +23,21 @@ use super::{ReconcileOptions, reconcile, schema, sniff}; use crate::live::{Change, Topic}; use crate::thumbs; +use super::previews; + /// Where one file's bytes live: `/files/`, named by the row's /// own id. What an upload carried never decides a path here — the name is /// always store-made, so `name` stays a label. -const FILES_DIR: &str = "files"; +pub(crate) const FILES_DIR: &str = "files"; /// Where thumbnails live: `/thumbs/`, webp, longest edge 512. const THUMBS_DIR: &str = "thumbs"; /// Where upload chunks stage: `/uploads//`. const UPLOADS_DIR: &str = "uploads"; +/// Where preview derivatives live: `previews/`, the playable stand-in +/// a media route builds for a video whose stored tracks no browser demuxes. +/// Deleted beside `files/` and `thumbs/` in every purge, swept at boot with +/// the same watermark rule. +const PREVIEWS_DIR: &str = previews::PREVIEWS_DIR; /// Thumbnails are attempted only below this source size: 64 MiB. Past it the /// row wears `failed` rather than pinning memory the size of the file. @@ -267,6 +274,9 @@ impl TursoStore { for (dir, known, kind) in [ (FILES_DIR, &files, "file"), (THUMBS_DIR, &thumbs, "thumbnail"), + // A derivative may exist for any live file row — it is built on + // demand, not at ingest — so its known set is the same ids. + (PREVIEWS_DIR, &files, "preview"), ] { // One listing per half: the names the tree holds, temp files // included — a `.tmp` is an orphan like any other — each with @@ -786,6 +796,7 @@ fn ensure_storage_dirs(storage: &std::path::Path) -> Result<()> { storage.join(FILES_DIR), storage.join(THUMBS_DIR), storage.join(UPLOADS_DIR), + storage.join(PREVIEWS_DIR), ] { std::fs::create_dir_all(&dir) .map_err(|e| StoreError::Backend(format!("could not create {}: {e}", dir.display())))?; @@ -1797,6 +1808,44 @@ impl Store for TursoStore { .await .map_err(|e| StoreError::Backend(e.to_string())) } + + async fn media_derivative(&self, id: &str) -> Result> { + let conn = self.conn.lock().await; + let mut rows = conn + .query("SELECT mime FROM file WHERE id = ?1", params![id]) + .await + .map_err(backend)?; + let mime = match rows.next().await.map_err(backend)? { + Some(row) => text(&row, 0)?, + None => return Ok(None), + }; + drop(conn); + // The build's misses are the module's own log lines; the store's + // answer to every one of them is "serve the original". + Ok(previews::ensure(&self.storage, self.blobs.as_ref(), id, &mime).await) + } + + async fn derivative_stream( + &self, + id: &str, + start: u64, + len: u64, + ) -> Result> { + let conn = self.conn.lock().await; + let mut rows = conn + .query("SELECT 1 FROM file WHERE id = ?1", params![id]) + .await + .map_err(backend)?; + let known = rows.next().await.map_err(backend)?.is_some(); + drop(conn); + if !known { + return Ok(None); + } + // Same answer as `file_stream`: a missing derivative is "nothing + // to serve", not a stack. The span clamps against the real blob. + Ok(previews::stream(self.blobs.as_ref(), id, start, len).await) + } + async fn list_trash(&self, owner_id: &str) -> Result { let conn = self.conn.lock().await; let mut folders = Vec::new(); @@ -1977,7 +2026,11 @@ impl Store for TursoStore { // boot sweep collects. let _ = self .blobs - .delete(&[&format!("files/{id}"), &format!("thumbs/{id}")]) + .delete(&[ + &format!("files/{id}"), + &format!("thumbs/{id}"), + &format!("previews/{id}"), + ]) .await; self.announce([Topic::Library(owner.clone()), Topic::Trash(owner)]); Ok(true) @@ -2047,7 +2100,11 @@ impl Store for TursoStore { for file_id in &deleted_files { let _ = self .blobs - .delete(&[&format!("files/{file_id}"), &format!("thumbs/{file_id}")]) + .delete(&[ + &format!("files/{file_id}"), + &format!("thumbs/{file_id}"), + &format!("previews/{file_id}"), + ]) .await; } let purged = (deleted_files.len() + deleted_folders.len()) as u64; @@ -2762,7 +2819,11 @@ impl Store for TursoStore { // is what failed. let _ = self .blobs - .delete(&[&format!("files/{file_id}"), &format!("thumbs/{file_id}")]) + .delete(&[ + &format!("files/{file_id}"), + &format!("thumbs/{file_id}"), + &format!("previews/{file_id}"), + ]) .await; return Err(backend(e)); } @@ -3296,10 +3357,11 @@ async fn commit_trash_purge( // After the delete: bytes may only follow a delete that committed. // Best-effort — survivors are orphaned bytes the boot sweep collects. if !deleted_files.is_empty() { - let mut keys = Vec::with_capacity(deleted_files.len() * 2); + let mut keys = Vec::with_capacity(deleted_files.len() * 3); for id in &deleted_files { keys.push(format!("{FILES_DIR}/{id}")); keys.push(format!("{THUMBS_DIR}/{id}")); + keys.push(format!("{PREVIEWS_DIR}/{id}")); } let keys = keys.iter().map(String::as_str).collect::>(); let _ = store.blobs.delete(&keys).await; diff --git a/crates/in-core/src/thumbs.rs b/crates/in-core/src/thumbs.rs index 2befbd8..735d58a 100644 --- a/crates/in-core/src/thumbs.rs +++ b/crates/in-core/src/thumbs.rs @@ -51,9 +51,13 @@ pub fn thumbnailed(mime: &str) -> bool { } /// Whether `mime` is a video container this crate frames via `ffmpeg`: -/// exactly the video mimes the sniffer can name. +/// exactly the video mimes the sniffer can name — including the Matroska +/// spelling it gives a file whose tracks are not webm-legal. pub fn is_video_mime(mime: &str) -> bool { - matches!(mime, "video/mp4" | "video/webm" | "video/quicktime") + matches!( + mime, + "video/mp4" | "video/webm" | "video/quicktime" | "video/x-matroska" + ) } /// Whether `ffmpeg` is on `PATH`. The verdict comes from one `ffmpeg diff --git a/crates/in-web/src/files.rs b/crates/in-web/src/files.rs index dd3ec19..2fe9bbf 100644 --- a/crates/in-web/src/files.rs +++ b/crates/in-web/src/files.rs @@ -256,11 +256,6 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, topcoat::r let inline = !forced && inline_ok(&file.mime); let mut headers = HeaderMap::new(); - headers.insert( - header::CONTENT_TYPE, - HeaderValue::from_str(&file.mime) - .unwrap_or(HeaderValue::from_static("application/octet-stream")), - ); headers.insert( header::CONTENT_DISPOSITION, HeaderValue::from_str(&disposition_of(&file.name, inline)) @@ -291,7 +286,24 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, topcoat::r Some(Ok((0, _))) | None => true, _ => false, }; - match bytes_response(store.as_ref(), id, file.size_bytes, range, headers).await { + // A video whose stored tracks no browser demuxes as they sit plays + // through its derivative — built on this first ask, cached at + // `previews/{id}`, served under the mime the derivative really is. A + // download (`?dl=1`) never sees it: the original bytes, byte for byte. + let mut content_type = file.mime.clone(); + let mut total = file.size_bytes; + let mut source = ByteSource::Original; + if inline { + if let Ok(Some(derivative)) = store.media_derivative(id).await { + content_type = derivative.mime.to_string(); + total = derivative.size; + source = ByteSource::Preview; + } + } + if let Ok(value) = HeaderValue::from_str(&content_type) { + headers.insert(header::CONTENT_TYPE, value); + } + match bytes_response(store.as_ref(), id, total, range, headers, source).await { Some((status, headers, body)) => { if counts && status.is_success() { let _ = store.record_download(id).await; @@ -301,18 +313,30 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, topcoat::r None => Ok(not_found()), } } +/// Where a byte response's span comes from: the original blob, or the +/// preview derivative standing in for it at media-serve time. A download +/// is always [`ByteSource::Original`] — `?dl=1` serves the stored bytes +/// byte for byte, derivative or no. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum ByteSource { + Original, + Preview, +} /// The streamed answer for a file's bytes: the whole file from 0, or the -/// parsed range's span — [`Store::file_stream`] clamps both against what is -/// really on disk, and the `Content-Length` (and a 206's `Content-Range`) -/// say the clamped truth. `None` when the bytes are not there. Shared by the -/// signed-in route above and the public link's `download_bytes`. +/// parsed range's span — the source's store call clamps both against what +/// is really on disk, and the `Content-Length` (and a 206's +/// `Content-Range`) say the clamped truth. `total` is the serving length — +/// the original's or the derivative's, whichever the caller chose. `None` +/// when the bytes are not there. Shared by the signed-in route above and +/// the public link's `download_bytes` and `media_bytes`. pub(crate) async fn bytes_response( store: &dyn Store, id: &str, total: u64, range: Option<&str>, mut headers: HeaderMap, + source: ByteSource, ) -> Option<(StatusCode, HeaderMap, topcoat::router::Body)> { use futures_util::StreamExt; use http_body::Frame; @@ -329,7 +353,10 @@ pub(crate) async fn bytes_response( } None => (StatusCode::OK, 0, total), }; - let span = store.file_stream(id, start, len).await.ok().flatten()?; + let span = match source { + ByteSource::Original => store.file_stream(id, start, len).await.ok().flatten()?, + ByteSource::Preview => store.derivative_stream(id, start, len).await.ok().flatten()?, + }; if status == StatusCode::PARTIAL_CONTENT { let end = start + span.len.saturating_sub(1); headers.insert( diff --git a/crates/in-web/src/main.rs b/crates/in-web/src/main.rs index 9e7e7c0..e3ee440 100644 --- a/crates/in-web/src/main.rs +++ b/crates/in-web/src/main.rs @@ -301,9 +301,10 @@ async fn main() { } /// Makes the storage tree the store keeps binary files in, if it is not -/// there: `/files`, `/thumbs` and `/uploads`, -/// private to the user the process runs as. A directory that exists is left -/// exactly as it is; one that cannot be made stops the boot — the failure +/// there: `/files`, `/thumbs`, `/previews` and +/// `/uploads`, private to the user the process runs as. A +/// directory that exists is left exactly as it is; one that cannot be made +/// stops the boot — the failure /// this prevents is an upload landing in a tree that is not there, and it is /// better met before anything is opened. fn ensure_storage_tree(storage: &std::path::Path) { @@ -323,7 +324,7 @@ fn ensure_storage_tree(storage: &std::path::Path) { } }; make(storage); - for name in ["files", "thumbs", "uploads"] { + for name in ["files", "thumbs", "previews", "uploads"] { make(&storage.join(name)); } } diff --git a/crates/in-web/src/share.rs b/crates/in-web/src/share.rs index fd91294..697b946 100644 --- a/crates/in-web/src/share.rs +++ b/crates/in-web/src/share.rs @@ -994,7 +994,15 @@ async fn download_bytes( HeaderValue::from_static("private, no-cache"), ); let Some(parts) = - crate::files::bytes_response(store, file_id, size_bytes, range, headers).await + crate::files::bytes_response( + store, + file_id, + size_bytes, + range, + headers, + crate::files::ByteSource::Original, + ) + .await else { return dead_link(cx).await; }; @@ -1029,6 +1037,19 @@ async fn media_bytes( let range = request_headers(cx) .get(header::RANGE) .and_then(|value| value.to_str().ok()); + // The derivative, when the stored tracks need one and it can be had: + // the player draws webm/mp4 it can actually demux. Preview is what a + // view-only link grants, and this grants nothing beyond it — there is + // no download shape on this route, and `?dl=1` still answers the + // original or the dead card. + let (mime, total, source) = match store.media_derivative(file_id).await { + Ok(Some(derivative)) => ( + derivative.mime, + derivative.size, + crate::files::ByteSource::Preview, + ), + _ => (mime, size_bytes, crate::files::ByteSource::Original), + }; let mut headers = HeaderMap::new(); if let Ok(value) = HeaderValue::from_str(mime) { headers.insert(header::CONTENT_TYPE, value); @@ -1045,7 +1066,7 @@ async fn media_bytes( HeaderValue::from_static("private, no-cache"), ); let Some(parts) = - crate::files::bytes_response(store, file_id, size_bytes, range, headers).await + crate::files::bytes_response(store, file_id, total, range, headers, source).await else { return dead_link(cx).await; }; diff --git a/crates/in-web/tests/http.rs b/crates/in-web/tests/http.rs index 8548474..1e86074 100644 --- a/crates/in-web/tests/http.rs +++ b/crates/in-web/tests/http.rs @@ -9,12 +9,13 @@ //! //! New HTTP tests belong in this file rather than a new `tests/*.rs`: one //! test binary links and runs once. +use http::{HeaderValue, Request, StatusCode, header}; use in_core::{Config, OidcConfig}; use std::collections::HashMap; use std::path::PathBuf; +use std::process::Command; use std::sync::{Arc, Mutex}; -use http::{HeaderValue, Request, StatusCode, header}; use in_core::store::{ShareKind, Store, TursoStore}; use in_web::server::App; use topcoat::asset::{AssetBundle, RouterBuilderAssetExt}; @@ -1662,6 +1663,185 @@ async fn view_only_link_download_is_dead_card() { ); } +/// A tiny VP9+AAC Matroska, made by the system `ffmpeg` the way the +/// thumbnailer drives it: a test pattern and a tone, half a second. Small, +/// but exactly the file a browser refuses to play as a webm — VP9 video +/// with AAC audio. `None` skips the tests where ffmpeg is not installed. +fn vp9_aac_matroska() -> Option> { + if !in_core::thumbs::ffmpeg_available() { + eprintln!("skipping matroska preview tests: no ffmpeg on PATH"); + return None; + } + let dir = std::env::temp_dir().join(format!("in-mkv-{}", Ulid::new())); + std::fs::create_dir_all(&dir).unwrap(); + let out = dir.join("clip.mkv"); + let status = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-y", + "-f", + "lavfi", + "-i", + "testsrc=duration=0.5:size=128x96:rate=10", + "-f", + "lavfi", + "-i", + "sine=frequency=440:duration=0.5", + "-c:v", + "libvpx-vp9", + "-c:a", + "aac", + ]) + .arg(&out) + .status() + .ok()?; + let bytes = if status.success() { + std::fs::read(&out).ok() + } else { + None + }; + let _ = std::fs::remove_dir_all(&dir); + bytes +} + +/// What a cached derivative is replaced with to prove a later serve draws +/// the cache instead of rebuilding: a webm's magic and a body no transcode +/// could produce. The head stays a container the cache probe accepts. +fn cached_marker() -> Vec { + let mut marker = vec![0x1A, 0x45, 0xDF, 0xA3]; + marker.extend_from_slice(b"cached-derivative"); + marker +} + +/// A VP9+AAC mkv is stored under its honest Matroska name, the media route +/// serves it a webm derivative — built on the first ask, then cached, then +/// range-servable — and `?dl=1` still hands over the original bytes, byte +/// for byte. +#[tokio::test] +async fn a_webm_illegal_matroska_gains_a_derivative_preview() { + let Some(mkv) = vp9_aac_matroska() else { + return; + }; + let app = TestApp::build().await; + let cookie = app + .sign_in("sub-matroska", "matroska@in.test", "Matroska") + .await; + let user = app + .store + .user_by_oidc_sub("sub-matroska") + .await + .unwrap() + .unwrap(); + + app.post_multipart( + "/files", + Some(&cookie), + &[("folder_id", "")], + &[("clip.mkv", "video/x-matroska", &mkv)], + ) + .await; + let file = app + .store + .list_children(&user.id, None) + .await + .unwrap() + .files + .into_iter() + .next() + .unwrap(); + // The sniffer no longer calls these tracks a webm. + let stored = app.store.file(&file.id).await.unwrap().unwrap(); + assert_eq!(stored.mime, "video/x-matroska"); + + // The first inline serve builds the derivative and answers with it. + let inline = app.get(&format!("/file/{}", file.id), Some(&cookie)).await; + assert_eq!(inline.status, StatusCode::OK); + assert_eq!(inline.content_type.as_deref(), Some("video/webm")); + assert_ne!(inline.bytes, mkv, "the preview was the original bytes"); + // The serve's length is the derivative's own: the body is exactly the + // blob the build placed, never a clamp against the original's size. + let placed = std::fs::read(app.config.storage.join("previews").join(&file.id)).unwrap(); + assert!(!placed.is_empty()); + assert_eq!(inline.bytes, placed, "the preview was not the derivative"); + + // The second serve answers the cache, whatever it holds — a rebuild + // would have replaced this marker with fresh transcode output. + let derivative_key = app.config.storage.join("previews").join(&file.id); + let marker = cached_marker(); + std::fs::write(&derivative_key, &marker).unwrap(); + let again = app.get(&format!("/file/{}", file.id), Some(&cookie)).await; + assert_eq!(again.status, StatusCode::OK); + assert_eq!(again.bytes, marker, "the second serve rebuilt the cache"); + + // A range reads the derivative's span, against its own length. + let probe = app + .get_with_range(&format!("/file/{}", file.id), Some(&cookie), "bytes=0-3") + .await; + assert_eq!(probe.status, StatusCode::PARTIAL_CONTENT); + assert_eq!(probe.bytes, &marker[0..4]); + assert_eq!( + probe.content_range.as_deref(), + Some(&format!("bytes 0-3/{}", marker.len())[..]) + ); + + // The download is the original, byte for byte, whatever the preview is. + let taken = app + .get(&format!("/file/{}?dl=1", file.id), Some(&cookie)) + .await; + assert_eq!(taken.status, StatusCode::OK); + assert_eq!(taken.bytes, mkv); + assert_eq!(taken.bytes.len(), mkv.len()); + assert_eq!(taken.content_type.as_deref(), Some("video/x-matroska")); + assert!( + taken + .disposition + .as_deref() + .unwrap_or("") + .starts_with("attachment") + ); +} + +/// A view-only public link previews the derivative — that is what the +/// media stream is for — and still cannot be downloaded: `?dl=1` stays the +/// dead card, and the original never travels. +#[tokio::test] +async fn view_only_link_previews_a_matroska_but_cannot_download() { + let Some(mkv) = vp9_aac_matroska() else { + return; + }; + let app = TestApp::build().await; + let owner = owner_of(&app, "sub-admin").await; + let file = app + .store + .insert_file(&owner, None, "clip.mkv", &mkv) + .await + .unwrap() + .id; + let created = app + .store + .create_share_link(&owner, ShareKind::File, &file, false, None, None) + .await + .unwrap(); + + let media = app + .get(&format!("/s/{}?media=1", created.token), None) + .await; + assert_eq!(media.status, StatusCode::OK); + assert_eq!(media.content_type.as_deref(), Some("video/webm")); + assert_ne!(media.bytes, mkv, "the media stream was the original"); + assert!(media.bytes.starts_with(&[0x1A, 0x45, 0xDF, 0xA3])); + + let blocked = app + .get(&format!("/s/{}?dl=1", created.token), None) + .await; + assert!( + blocked.text().contains("no longer works"), + "view-only download showed: {}", + blocked.text() + ); +} + /// A password-protected link gates everything — card, download bytes — /// until the browser answers the gate once; the proof then lives in the /// link's own cookie. A wrong password answers the gate with the error and