forge
Explore
Log in

Don't you dare go Hollow

The walk a Matroska file still needs is written down once

Browse files at this commit

8651b1545a74039efd79963a54a98a1b2c291da7Ahmet Kaan GümüşParent: 8d969d0
  • perf
    • the walk a Matroska file still needs is written down once
Show full message
⚡ perf(demux): the walk a Matroska file still needs is written down once

The `Cues` path took the picture's open off the whole-cluster walk, but two
callers still pay it in full: a sound track, which Matroska indexes not at all
and which is walked on its own track number, and a picture whose index is
absent or caught lying. On a real 10.9 GB E-AC-3 film that is the first
contact with the file -- 9.7 s before a note is heard, and 298 ms every time
the session reopens it, which the editor does at every seek across a clip
boundary and once per export span.

That walk's answer is now written beside the user's other caches, in
`$XDG_CACHE_HOME/edith/mkvindex` (`~/.cache` where the desktop names none),
one file per track of every Matroska file walked, and read back instead of
re-walking.

Correctness first, speed second. A sidecar is valid for one file and nothing
else: its canonical path, its size, its modification time to the nanosecond,
the segment bounds and the track number are written into the record and
compared field by field on the way back. Format version in the magic, FNV-1a
over the payload, every field length-checked as it is read, nothing left over
at the end. Any mismatch at all -- absent, stale, damaged, another version, a
hash collision on the file name -- is a miss, which means the walk runs and
the file is rewritten. There is no path where a wrong index is believed.

Written atomically, temporary file then rename, so a reader sees a whole index
or none; a write that fails is a slow open rather than a failed one.

Hand-rolled little-endian records, no new dependency: a flat table of
fixed-width fields does not need a serializer, and this tree carries none.

The one thing the key does not cover is the code that filled it: a build whose
walk answers differently would believe every record written by the last one,
and only the magic's version byte stands there. It says so at the constant,
and it is bumped here for exactly that reason -- this tree's walk is not the
one the lane that first wrote this format had.
crates/engine/src/demux.rsmodified+428 -10
@@ -12,9 +12,12 @@
12 //! this project exports one, and a file this cannot reopen is a file it had no12 //! this project exports one, and a file this cannot reopen is a file it had no
13 //! business writing.13 //! business writing.
14 14
15+use std::ffi::OsString;
15 use std::fs::File;16 use std::fs::File;
16-use std::io::{BufReader, Read, Seek, SeekFrom};17+use std::io::{BufReader, Read, Seek, SeekFrom, Write};
17-use std::path::Path;18+use std::path::{Path, PathBuf};
19+use std::sync::atomic::{AtomicU64, Ordering};
20+use std::time::UNIX_EPOCH;
18 21
19 use mp4::{Mp4Reader, Mp4Track, TrackType};22 use mp4::{Mp4Reader, Mp4Track, TrackType};
20 23
@@ -767,6 +770,10 @@ struct Block {
767 /// numbers; only what they read to do it differs.770 /// numbers; only what they read to do it differs.
768 pub struct MkvDemuxer {771 pub struct MkvDemuxer {
769 file: File,772 file: File,
773+ /// The file's own path, kept for one reason: the whole walk this falls back
774+ /// to is cached beside the user's other caches, and a sidecar is named after
775+ /// the file it indexes ([`mkv_blocks`]).
776+ path: PathBuf,
770 /// The blocks walked so far, which for a lazily indexed file is the window777 /// The blocks walked so far, which for a lazily indexed file is the window
771 /// around what has been read and not the file: `blocks[i]` is the file's778 /// around what has been read and not the file: `blocks[i]` is the file's
772 /// block `base + i`.779 /// block `base + i`.
@@ -888,6 +895,7 @@ impl MkvDemuxer {
888 };895 };
889 let mut mkv = Self {896 let mut mkv = Self {
890 file,897 file,
898+ path: path.to_path_buf(),
891 blocks: Vec::new(),899 blocks: Vec::new(),
892 codec: video.codec,900 codec: video.codec,
893 config: video.config,901 config: video.config,
@@ -1017,7 +1025,8 @@ impl MkvDemuxer {
1017 if self.complete {1025 if self.complete {
1018 return Ok(());1026 return Ok(());
1019 }1027 }
1020- let (blocks, _, track_bytes) = mkv_blocks(&mut self.file, self.segment, self.number)?;1028+ let (blocks, _, track_bytes) =
1029+ mkv_blocks(&self.path, &mut self.file, self.segment, self.number)?;
1021 self.frames = blocks.len();1030 self.frames = blocks.len();
1022 self.blocks = blocks;1031 self.blocks = blocks;
1023 self.track_bytes = track_bytes;1032 self.track_bytes = track_bytes;
@@ -1397,7 +1406,7 @@ impl MkvAudio {
1397 if let Unpack::Refused(why) = &unpack {1406 if let Unpack::Refused(why) = &unpack {
1398 return Err(why.clone().into());1407 return Err(why.clone().into());
1399 }1408 }
1400- let (blocks, _, _) = mkv_blocks(&mut file, segment, number)?;1409+ let (blocks, _, _) = mkv_blocks(path, &mut file, segment, number)?;
1401 if blocks.is_empty() {1410 if blocks.is_empty() {
1402 return Err("the AC-3 track in this Matroska file has no blocks".into());1411 return Err("the AC-3 track in this Matroska file has no blocks".into());
1403 }1412 }
@@ -2356,11 +2365,34 @@ fn mkv_seek_position(
2356 /// Only element headers are read: a block's payload is seeked over and fetched2365 /// Only element headers are read: a block's payload is seeked over and fetched
2357 /// later by [`MkvDemuxer::next_access_unit`], which is what keeps this an index2366 /// later by [`MkvDemuxer::next_access_unit`], which is what keeps this an index
2358 /// pass rather than a read of the whole file.2367 /// pass rather than a read of the whole file.
2359-fn mkv_blocks(2368+/// The walk itself is [`mkv_walk_blocks`]; this is the sidecar cache in front of
2360- file: &mut File,2369+/// it. What still reaches it is what the `Cues` cannot answer -- the sound
2361- segment: (u64, u64),2370+/// track, which Matroska indexes not at all, and a picture whose index is absent
2362- number: u64,2371+/// or caught lying -- and those pay the whole walk on a file the user opens
2363-) -> crate::Result<(Vec<Block>, Option<(i64, i64)>, Vec<(u64, u64)>)> {2372+/// again and again. So the walk's answer is written beside the user's other
2373+/// caches and read back in milliseconds while the file it indexes is untouched.
2374+fn mkv_blocks(path: &Path, file: &mut File, segment: (u64, u64), number: u64) -> crate::Result<Index> {
2375+ let key = IndexKey::of(path, file, segment, number);
2376+ let at = key.as_ref().and_then(|key| key.sidecar());
2377+ if let Some((key, at)) = key.as_ref().zip(at.as_ref())
2378+ && let Some(index) = read_index(key, at)
2379+ {
2380+ return Ok(index);
2381+ }
2382+ let index = mkv_walk_blocks(file, segment, number)?;
2383+ if let Some((key, at)) = key.as_ref().zip(at.as_ref()) {
2384+ // A cache that cannot be written is a slow open, not a failed one.
2385+ let _ = write_index(key, at, &index);
2386+ }
2387+ Ok(index)
2388+}
2389+
2390+/// What one walk of the segment answers: the track's blocks, the span its
2391+/// timestamps cover, and every track's byte count. Named because it is also what
2392+/// the sidecar cache stores.
2393+type Index = (Vec<Block>, Option<(i64, i64)>, Vec<(u64, u64)>);
2394+
2395+fn mkv_walk_blocks(file: &mut File, segment: (u64, u64), number: u64) -> crate::Result<Index> {
2364 let mut blocks = Vec::new();2396 let mut blocks = Vec::new();
2365 // A file has a handful of tracks, so this is a shorter linear scan than a2397 // A file has a handful of tracks, so this is a shorter linear scan than a
2366 // hash would be a hash.2398 // hash would be a hash.
@@ -2508,6 +2540,244 @@ fn mkv_spread_laces(blocks: &mut [Block], laced: &[(usize, usize)]) {
2508 }2540 }
2509 }2541 }
2510 2542
2543+/// Magic and format version of the sidecar index. The last byte is the version:
2544+/// bump it and every file an older build wrote is a miss, which is the whole
2545+/// migration story -- a sidecar is rewritten, never upgraded.
2546+///
2547+/// **Bump it whenever the walk's output changes.** The key below binds a sidecar
2548+/// to the *file* -- its bytes, its times, its track -- and to nothing about the
2549+/// code that wrote it, so a build whose blocks, timestamps or lace spreading
2550+/// differ from the one that filled this directory will believe every stale
2551+/// record in it. This byte is the only thing standing there, and it is bumped by
2552+/// hand.
2553+const INDEX_MAGIC: &[u8; 8] = b"EDMKVIX2";
2554+
2555+/// What a sidecar index is valid for and nothing else: the file it was walked
2556+/// from, down to the byte and the modification time, and the track it indexes.
2557+/// Every field is written into the sidecar and compared on the way back, so a
2558+/// re-encode, an append, a truncation or a hash collision on the file name are
2559+/// all one thing -- a miss, and the walk runs.
2560+struct IndexKey {
2561+ /// Canonical, so a symlink and its target share one entry rather than
2562+ /// walking the same bytes twice under two names.
2563+ path: PathBuf,
2564+ len: u64,
2565+ /// Seconds since the epoch and nanoseconds within it; the seconds are signed
2566+ /// because a file can be stamped before 1970 and that is not an error.
2567+ mtime: (i64, u32),
2568+ segment: (u64, u64),
2569+ number: u64,
2570+}
2571+
2572+impl IndexKey {
2573+ /// `None` when the file cannot be stat'd or the platform has no modification
2574+ /// time, which is a file that gets the walk every time rather than a cache
2575+ /// nothing can invalidate.
2576+ fn of(path: &Path, file: &File, segment: (u64, u64), number: u64) -> Option<Self> {
2577+ let meta = file.metadata().ok()?;
2578+ let mtime = match meta.modified().ok()?.duration_since(UNIX_EPOCH) {
2579+ Ok(d) => (d.as_secs() as i64, d.subsec_nanos()),
2580+ Err(e) => (
2581+ -(e.duration().as_secs() as i64),
2582+ e.duration().subsec_nanos(),
2583+ ),
2584+ };
2585+ Some(Self {
2586+ path: std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()),
2587+ len: meta.len(),
2588+ mtime,
2589+ segment,
2590+ number,
2591+ })
2592+ }
2593+
2594+ /// Where this key's sidecar lives. The name is the path's hash and the track
2595+ /// number, *not* the size or the time: an edited file overwrites its own
2596+ /// entry instead of leaving the old one behind, which is what keeps the
2597+ /// directory one file per track of every Matroska file ever opened.
2598+ ///
2599+ /// ponytail: nothing evicts. That is bounded (a few MB for a feature film's
2600+ /// picture track) and the directory is the user's own cache to delete, but a
2601+ /// size-capped LRU sweep at open is the upgrade path if it ever matters.
2602+ fn sidecar(&self) -> Option<PathBuf> {
2603+ let dir = index_dir(std::env::var_os("XDG_CACHE_HOME"), std::env::var_os("HOME"))?;
2604+ Some(dir.join(format!(
2605+ "{:016x}-{}.idx",
2606+ fnv1a(self.path.as_os_str().as_encoded_bytes()),
2607+ self.number
2608+ )))
2609+ }
2610+}
2611+
2612+/// The path rule, with the environment handed in so it can be checked, as
2613+/// `keymap::config_path_in` is on the config side. An empty `XDG_CACHE_HOME` is
2614+/// one the spec says to ignore; with no `HOME` either there is nowhere to put a
2615+/// cache, and `None` -- always walk -- beats littering the working directory.
2616+fn index_dir(xdg: Option<OsString>, home: Option<OsString>) -> Option<PathBuf> {
2617+ xdg.filter(|v| !v.is_empty())
2618+ .map(PathBuf::from)
2619+ .or_else(|| {
2620+ home.filter(|v| !v.is_empty())
2621+ .map(|h| PathBuf::from(h).join(".cache"))
2622+ })
2623+ .map(|dir| dir.join("edith").join("mkvindex"))
2624+}
2625+
2626+/// FNV-1a, 64-bit: what names a sidecar and what checks it. Not a cryptographic
2627+/// hash and not asked to be -- nothing here is adversarial. It is the guard that
2628+/// turns a half-written or scrambled file into a miss; a *name* collision is
2629+/// caught by the key inside the file, which is compared field by field.
2630+fn fnv1a(bytes: &[u8]) -> u64 {
2631+ let mut hash = 0xcbf2_9ce4_8422_2325u64;
2632+ for &b in bytes {
2633+ hash ^= u64::from(b);
2634+ hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
2635+ }
2636+ hash
2637+}
2638+
2639+/// A cursor over an encoded index. Every read is bounds-checked and hands back
2640+/// `None` past the end, so a truncated file runs out of bytes rather than off
2641+/// the end of one, and one `?` per field is the whole validation.
2642+struct Take<'a>(&'a [u8]);
2643+
2644+impl<'a> Take<'a> {
2645+ fn bytes(&mut self, n: usize) -> Option<&'a [u8]> {
2646+ let (head, rest) = self.0.split_at_checked(n)?;
2647+ self.0 = rest;
2648+ Some(head)
2649+ }
2650+
2651+ fn u64(&mut self) -> Option<u64> {
2652+ Some(u64::from_le_bytes(self.bytes(8)?.try_into().ok()?))
2653+ }
2654+
2655+ fn i64(&mut self) -> Option<i64> {
2656+ Some(i64::from_le_bytes(self.bytes(8)?.try_into().ok()?))
2657+ }
2658+
2659+ fn u32(&mut self) -> Option<u32> {
2660+ Some(u32::from_le_bytes(self.bytes(4)?.try_into().ok()?))
2661+ }
2662+}
2663+
2664+/// The index as bytes: the key first, then the walk's three answers. Little
2665+/// endian throughout and hand-rolled, because this tree carries no serializer
2666+/// and a flat record of fixed-width fields does not need one.
2667+fn encode_index(key: &IndexKey, index: &Index) -> Vec<u8> {
2668+ let (blocks, span, track_bytes) = index;
2669+ let path = key.path.as_os_str().as_encoded_bytes();
2670+ let mut out = Vec::with_capacity(80 + path.len() + blocks.len() * 25 + track_bytes.len() * 16);
2671+ out.extend_from_slice(&key.len.to_le_bytes());
2672+ out.extend_from_slice(&key.mtime.0.to_le_bytes());
2673+ out.extend_from_slice(&key.mtime.1.to_le_bytes());
2674+ out.extend_from_slice(&key.segment.0.to_le_bytes());
2675+ out.extend_from_slice(&key.segment.1.to_le_bytes());
2676+ out.extend_from_slice(&key.number.to_le_bytes());
2677+ out.extend_from_slice(&(path.len() as u64).to_le_bytes());
2678+ out.extend_from_slice(path);
2679+ // A `None` span is written at the same width as a present one, so the record
2680+ // stays a table of fixed-width fields.
2681+ out.push(u8::from(span.is_some()));
2682+ let (first, last) = span.unwrap_or((0, 0));
2683+ out.extend_from_slice(&first.to_le_bytes());
2684+ out.extend_from_slice(&last.to_le_bytes());
2685+ out.extend_from_slice(&(track_bytes.len() as u64).to_le_bytes());
2686+ for (number, bytes) in track_bytes {
2687+ out.extend_from_slice(&number.to_le_bytes());
2688+ out.extend_from_slice(&bytes.to_le_bytes());
2689+ }
2690+ out.extend_from_slice(&(blocks.len() as u64).to_le_bytes());
2691+ for block in blocks {
2692+ out.extend_from_slice(&block.at.to_le_bytes());
2693+ out.extend_from_slice(&(block.len as u64).to_le_bytes());
2694+ out.extend_from_slice(&block.ts.to_le_bytes());
2695+ out.push(u8::from(block.key));
2696+ }
2697+ out
2698+}
2699+
2700+/// The sidecar at `at`, if it is this key's and intact. `None` for every other
2701+/// case there is -- absent, unreadable, another format version, a checksum that
2702+/// does not match, a key that does not, a record that ends early or one with
2703+/// bytes left over -- and every one of them means the same thing to the caller:
2704+/// walk the file and write this again.
2705+fn read_index(key: &IndexKey, at: &Path) -> Option<Index> {
2706+ let bytes = std::fs::read(at).ok()?;
2707+ let (head, body) = bytes.split_at_checked(16)?;
2708+ if &head[..8] != INDEX_MAGIC || u64::from_le_bytes(head[8..].try_into().ok()?) != fnv1a(body) {
2709+ return None;
2710+ }
2711+ let mut take = Take(body);
2712+ if take.u64()? != key.len
2713+ || take.i64()? != key.mtime.0
2714+ || take.u32()? != key.mtime.1
2715+ || take.u64()? != key.segment.0
2716+ || take.u64()? != key.segment.1
2717+ || take.u64()? != key.number
2718+ {
2719+ return None;
2720+ }
2721+ let path_len = usize::try_from(take.u64()?).ok()?;
2722+ if take.bytes(path_len)? != key.path.as_os_str().as_encoded_bytes() {
2723+ return None;
2724+ }
2725+ let present = take.bytes(1)?[0] != 0;
2726+ let (first, last) = (take.i64()?, take.i64()?);
2727+ let span = present.then_some((first, last));
2728+ let count = usize::try_from(take.u64()?).ok()?;
2729+ // Capacity is what the bytes left can actually hold, never what the record
2730+ // claims: the checksum has already passed, but a count is not a promise.
2731+ let mut track_bytes = Vec::with_capacity(count.min(take.0.len() / 16));
2732+ for _ in 0..count {
2733+ track_bytes.push((take.u64()?, take.u64()?));
2734+ }
2735+ let count = usize::try_from(take.u64()?).ok()?;
2736+ let mut blocks = Vec::with_capacity(count.min(take.0.len() / 25));
2737+ for _ in 0..count {
2738+ blocks.push(Block {
2739+ at: take.u64()?,
2740+ len: usize::try_from(take.u64()?).ok()?,
2741+ ts: take.i64()?,
2742+ key: take.bytes(1)?[0] != 0,
2743+ });
2744+ }
2745+ take.0.is_empty().then_some((blocks, span, track_bytes))
2746+}
2747+
2748+/// Writes the sidecar, atomically: a temporary file of its own, fsynced, then
2749+/// renamed over the name readers look under. A reader therefore sees the whole
2750+/// index or no index -- never a half-written one, which the checksum would catch
2751+/// anyway but only after the bytes were read.
2752+fn write_index(key: &IndexKey, at: &Path, index: &Index) -> std::io::Result<()> {
2753+ let dir = at
2754+ .parent()
2755+ .ok_or_else(|| std::io::Error::other("a sidecar path with no directory"))?;
2756+ std::fs::create_dir_all(dir)?;
2757+ let body = encode_index(key, index);
2758+ // Per process *and* per call: the picture and the sound of one file are
2759+ // opened by different threads, and two writers must not share a part file.
2760+ static NTH: AtomicU64 = AtomicU64::new(0);
2761+ let part = dir.join(format!(
2762+ "{}.{}.part",
2763+ std::process::id(),
2764+ NTH.fetch_add(1, Ordering::Relaxed)
2765+ ));
2766+ let result = File::create(&part)
2767+ .and_then(|mut f| {
2768+ f.write_all(INDEX_MAGIC)?;
2769+ f.write_all(&fnv1a(&body).to_le_bytes())?;
2770+ f.write_all(&body)?;
2771+ f.sync_all()
2772+ })
2773+ .and_then(|()| std::fs::rename(&part, at));
2774+ if result.is_err() {
2775+ let _ = std::fs::remove_file(&part);
2776+ }
2777+ result
2778+}
2779+
2780+
2511 /// The frames inside a laced block: one `(offset, length)` each, in order.2781 /// The frames inside a laced block: one `(offset, length)` each, in order.
2512 ///2782 ///
2513 /// Lacing packs several frames -- always whole ones, and only ones nothing else2783 /// Lacing packs several frames -- always whole ones, and only ones nothing else
@@ -3455,7 +3725,7 @@ mod tests {
3455 cued += usize::from(!lazy.complete);3725 cued += usize::from(!lazy.complete);
3456 // The walk, built beside it out of the same file.3726 // The walk, built beside it out of the same file.
3457 let mut file = File::open(&path).expect(&name);3727 let mut file = File::open(&path).expect(&name);
3458- let (walk, _, _) = mkv_blocks(&mut file, lazy.segment, lazy.number).expect(&name);3728+ let (walk, _, _) = mkv_walk_blocks(&mut file, lazy.segment, lazy.number).expect(&name);
3459 3729
3460 assert_eq!(3730 assert_eq!(
3461 meta.frame_count as usize,3731 meta.frame_count as usize,
@@ -3627,6 +3897,154 @@ mod tests {
3627 None3897 None
3628 }3898 }
3629 3899
3900+ /// The sidecar index, against the walk it stands in for: what comes back out
3901+ /// is the walk's own answer block for block, and every way a sidecar can be
3902+ /// wrong is a miss rather than a wrong answer.
3903+ ///
3904+ /// The cache path itself is handed in here rather than taken from the
3905+ /// environment, which is what lets a truncation and a flipped byte be tested
3906+ /// at all; the end-to-end half below drives [`mkv_blocks`] and therefore the
3907+ /// real cache directory.
3908+ /// The fixture always, plus every path in `VE_INDEX_FILES` (`:`-separated),
3909+ /// which is how this is pointed at the multi-GB films it really has to hold
3910+ /// for without naming one of them in the tree.
3911+ #[test]
3912+ fn a_cached_block_index_is_the_walk_it_replaces() {
3913+ let fixture =
3914+ std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_h264.mkv");
3915+ index_round_trip(&fixture);
3916+ for path in std::env::var("VE_INDEX_FILES")
3917+ .unwrap_or_default()
3918+ .split(':')
3919+ .filter(|p| !p.is_empty())
3920+ {
3921+ index_round_trip(Path::new(path));
3922+ }
3923+ }
3924+
3925+ fn index_round_trip(path: &Path) {
3926+ let mut file = File::open(path).expect("the file under test");
3927+ let end = file.metadata().expect("stat").len();
3928+ let segment = mkv_segment(&mut file, end).expect("segment");
3929+ let number = mkv_tracks(&mut file, segment)
3930+ .expect("tracks")
3931+ .0
3932+ .expect("a video track")
3933+ .number;
3934+ let walked = mkv_walk_blocks(&mut file, segment, number).expect("walk");
3935+ assert!(walked.0.len() > 1, "a file with blocks to index");
3936+
3937+ let key = IndexKey::of(path, &file, segment, number).expect("a key off the open file");
3938+ let at = crate::scratch::Scratch::file("ve_mkvindex", "idx");
3939+ assert!(read_index(&key, &at).is_none(), "nothing written yet");
3940+ write_index(&key, &at, &walked).expect("write the sidecar");
3941+ let cached = read_index(&key, &at).expect("read it back");
3942+ assert_eq!(cached.0, walked.0, "block for block, byte for byte");
3943+ assert_eq!(cached.1, walked.1, "the same timestamp span");
3944+ assert_eq!(cached.2, walked.2, "the same per-track byte counts");
3945+
3946+ // Every shape of a stale key: a file that grew, one re-encoded in place,
3947+ // and the other track of the same file.
3948+ for stale in [
3949+ IndexKey {
3950+ len: key.len + 1,
3951+ ..key_of(&key)
3952+ },
3953+ IndexKey {
3954+ mtime: (key.mtime.0 + 1, key.mtime.1),
3955+ ..key_of(&key)
3956+ },
3957+ IndexKey {
3958+ number: key.number + 1,
3959+ ..key_of(&key)
3960+ },
3961+ IndexKey {
3962+ path: key.path.with_extension("other"),
3963+ ..key_of(&key)
3964+ },
3965+ ] {
3966+ assert!(
3967+ read_index(&stale, &at).is_none(),
3968+ "a key that does not match is a miss, not a wrong index"
3969+ );
3970+ }
3971+
3972+ // ...and every shape of a damaged file. A flipped byte anywhere fails the
3973+ // checksum; a truncation runs out of bytes; extra bytes are a record this
3974+ // does not understand.
3975+ let good = std::fs::read(&at).expect("the sidecar");
3976+ for (why, bytes) in [
3977+ ("a flipped byte in the payload", {
3978+ let mut b = good.clone();
3979+ let last = b.len() - 1;
3980+ b[last] ^= 0x01;
3981+ b
3982+ }),
3983+ ("a flipped byte in the key", {
3984+ let mut b = good.clone();
3985+ b[20] ^= 0x80;
3986+ b
3987+ }),
3988+ ("another format version", {
3989+ let mut b = good.clone();
3990+ b[7] = b'0';
3991+ b
3992+ }),
3993+ ("a truncated file", good[..good.len() / 2].to_vec()),
3994+ ("an empty file", Vec::new()),
3995+ ("bytes left over", [good.clone(), vec![0u8; 4]].concat()),
3996+ ] {
3997+ std::fs::write(&at, &bytes).expect("write the damaged sidecar");
3998+ assert!(read_index(&key, &at).is_none(), "{why} is a miss");
3999+ }
4000+
4001+ // End to end, through the wrapper the demuxer calls and the real cache
4002+ // directory: the first open writes the sidecar, the second reads it, and
4003+ // neither may differ from the walk.
4004+ for round in 0..2 {
4005+ let (blocks, span, track_bytes) =
4006+ mkv_blocks(path, &mut file, segment, number).expect("cached open");
4007+ assert_eq!(blocks, walked.0, "round {round}");
4008+ assert_eq!(span, walked.1, "round {round}");
4009+ assert_eq!(track_bytes, walked.2, "round {round}");
4010+ }
4011+ }
4012+
4013+ /// `IndexKey` is not `Clone` -- nothing in the demuxer needs it to be, and a
4014+ /// test wanting four variants of one key is not a reason to widen it.
4015+ fn key_of(key: &IndexKey) -> IndexKey {
4016+ IndexKey {
4017+ path: key.path.clone(),
4018+ len: key.len,
4019+ mtime: key.mtime,
4020+ segment: key.segment,
4021+ number: key.number,
4022+ }
4023+ }
4024+
4025+ /// Where a sidecar goes, by the same rule the config file follows: the
4026+ /// desktop's cache directory, `~/.cache` when it names none, and nowhere at
4027+ /// all rather than the working directory when there is no home either.
4028+ #[test]
4029+ fn the_index_directory_follows_xdg() {
4030+ let dir = |xdg: Option<&str>, home: Option<&str>| {
4031+ index_dir(xdg.map(OsString::from), home.map(OsString::from))
4032+ };
4033+ assert_eq!(
4034+ dir(Some("/x/cache"), Some("/home/u")),
4035+ Some(PathBuf::from("/x/cache/edith/mkvindex"))
4036+ );
4037+ // An empty XDG_CACHE_HOME is one the spec says to ignore.
4038+ assert_eq!(
4039+ dir(Some(""), Some("/home/u")),
4040+ Some(PathBuf::from("/home/u/.cache/edith/mkvindex"))
4041+ );
4042+ assert!(dir(None, Some("/home/u")).expect("a home").is_absolute());
4043+ assert_eq!(dir(None, None), None, "no home, no cache -- walk instead");
4044+ assert_eq!(dir(Some(""), Some("")), None);
4045+ }
4046+
4047+
3630 /// What a `TrackEntry` states it is in, whichever of the two elements it4048 /// What a `TrackEntry` states it is in, whichever of the two elements it
3631 /// states it in -- [`mkv_language`]'s whole rule, as asserts.4049 /// states it in -- [`mkv_language`]'s whole rule, as asserts.
3632 #[test]4050 #[test]