rbox 0.1.8

Rust library for interacting with the local and export data of Pioneers Rekordbox DJ software
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
// Copyright (C) 2026 Dylan Jones
// SPDX-License-Identifier: GPL-3.0-only

//! Lazy access to ANLZ files, with ordered sections and selective serialization.
//!
//! [`Anlz`] owns the source file and caches decoded sections. The binary models
//! and their eager parsers are defined in [`super::sections`].

use std::io::{Cursor, SeekFrom};
use std::ops::Range;

use binrw::io::{Read, Seek, Write};
use binrw::{BinRead, BinWrite};

use super::sections::*;
use crate::error::{Error, Result};

/// One section occurrence in the file's ordered sequence.
///
/// Duplicate tags have separate entries. New entries are decoded and marked
/// for serialization; unloaded entries always have a source byte range.
struct SectionEntry {
    /// Complete section range, including its header, in the current source.
    /// Absent for a newly inserted section until it is saved to that source.
    original_range: Option<Range<u64>>,
    /// Indexed tag, used until the section is decoded.
    tag: AnlzTag,
    /// Cached section, including any edits made through a mutable getter.
    decoded: Option<Section>,
    /// Serialize on save instead of copying source bytes. Set before exposing
    /// mutable access, since subsequent changes to the reference cannot be tracked.
    potentially_modified: bool,
}

impl SectionEntry {
    /// Prefer the live tag so low-level edits cannot leave lookups stale.
    fn tag(&self) -> &AnlzTag {
        self.decoded.as_ref().map_or(&self.tag, |s| &s.tag)
    }
}

/// Lazily read and edit a Rekordbox `.DAT`, `.EXT`, or `.2EX` analysis file.
///
/// Opening reads the file header and indexes the section boundaries. Payloads
/// are decoded and cached on first access; cached sections remain in memory
/// until this handler is consumed or dropped.
///
/// # Access and editing
///
/// Shared section getters (`get_*`) borrow cached data without marking it modified. They
/// still require `&mut self` because a first access may read and populate the cache.
/// The `get_mut_*` methods mark a returned section for serialization, even if the
/// caller ultimately makes no changes. Edits remain in memory until
/// [`dump`](Self::dump) or [`dump_copy`](Self::dump_copy) succeeds.
///
/// Optional getters return `Ok(None)` when no matching section is present.
/// Typed getters also return `None` if a low-level edit has made a section's tag
/// inconsistent with its content; saving rejects that inconsistency. I/O and
/// payload parsing failures are returned as errors when the section is accessed.
/// An error in an unread payload therefore need not prevent opening the file.
///
/// # Saving and source lifetime
///
/// Saves write a complete output file in the original section order. Sections
/// accessed mutably are serialized; untouched sections, including unknown tags,
/// are copied from the source byte-for-byte. Duplicate tags remain distinct.
///
/// Keep the backing file unchanged externally while this handler is alive:
/// cached values and indexed byte ranges are tied to that source. Dropping the
/// handler closes its file handle and discards unsaved edits.
///
/// # Examples
///
/// ```no_run
/// use rbox::anlz::Anlz;
///
/// # fn main() -> rbox::Result<()> {
/// let mut file = Anlz::load("ANLZ0000.DAT")?;
/// if let Some(grid) = file.get_beat_grid()? {
///     println!("{} beats", grid.beats.len());
/// }
/// if let Some(grid) = file.get_mut_beat_grid()? {
///     grid.set_grid_offset(25);
/// }
/// file.dump_copy("ANLZ_EDITED.DAT")?;
/// # Ok(())
/// # }
/// ```
pub struct Anlz {
    /// Canonical source path; distinct from the audio path stored in PPTH.
    path: std::path::PathBuf,
    /// Closed immediately before replacing the source. A failed replacement
    /// leaves this empty until the next operation that needs source bytes.
    source: Option<std::fs::File>,
    /// PMAI header from the most recent load or successful source save.
    header: Header,
    /// Opaque bytes following the common 12-byte PMAI header.
    header_data: Vec<u8>,
    /// Authoritative serialization order, including duplicate and unknown tags.
    sections: Vec<SectionEntry>,
}

impl Anlz {
    /// Open an analysis file and index its sections without decoding their payloads.
    ///
    /// The path is canonicalized and a file handle is retained for later reads.
    /// The file-header extension is loaded; section bodies are skipped using their
    /// declared lengths. Opening does not validate individual payloads.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be opened or read, the PMAI header is
    /// invalid, its declared total size differs from the physical file size, or a
    /// section has invalid or truncated outer bounds.
    pub fn load<P: AsRef<std::path::Path>>(path: P) -> Result<Self> {
        let path = std::fs::canonicalize(path)?;
        let mut source = std::fs::File::open(&path)?;
        let (header, header_data, sections) = Self::index(&mut source)?;
        Ok(Self {
            path,
            source: Some(source),
            header,
            header_data,
            sections,
        })
    }

    /// Scan common headers, checking bounds before seeking over section bodies.
    /// The ordered entries are also the authoritative order used when saving.
    fn index<R: Read + Seek>(source: &mut R) -> Result<(Header, Vec<u8>, Vec<SectionEntry>)> {
        let physical_size = source.seek(SeekFrom::End(0))?;
        source.seek(SeekFrom::Start(0))?;
        let header = Self::read_header(source)?;
        if header.tag != AnlzTag::File
            || header.size < 12
            || header.total_size < header.size
            || u64::from(header.total_size) != physical_size
        {
            return Err(Error::AnlzError(
                "Invalid ANLZ header or file length".into(),
            ));
        }
        let mut header_data = vec![0; (header.size - 12) as usize];
        source.read_exact(&mut header_data)?;
        let mut offset = u64::from(header.size);
        let mut sections = Vec::new();
        while offset < physical_size {
            if physical_size - offset < 12 {
                return Err(Error::AnlzError(format!(
                    "Truncated section header at {offset}"
                )));
            }
            source.seek(SeekFrom::Start(offset))?;
            let h = Self::read_header(source)?;
            let end = offset
                .checked_add(u64::from(h.total_size))
                .ok_or_else(|| Error::AnlzError("Section offset overflow".into()))?;
            if h.size < 12 || h.total_size < h.size || end > physical_size {
                return Err(Error::AnlzError(format!(
                    "Invalid section bounds at {offset}"
                )));
            }
            sections.push(SectionEntry {
                original_range: Some(offset..end),
                tag: h.tag,
                decoded: None,
                potentially_modified: false,
            });
            offset = end;
        }
        Ok((header, header_data, sections))
    }

    fn read_header<R: Read>(source: &mut R) -> Result<Header> {
        // AnlzTag's derived reader backtracks through enum alternatives. Keep
        // those small reads in memory rather than repeating filesystem calls.
        let mut bytes = [0; 12];
        source.read_exact(&mut bytes)?;
        Ok(Header::read_be(&mut Cursor::new(bytes))?)
    }

    /// Reopen the original source after a failed attempt to replace it.
    fn source(&mut self) -> Result<&mut std::fs::File> {
        if self.source.is_none() {
            self.source = Some(std::fs::File::open(&self.path)?);
        }
        Ok(self.source.as_mut().unwrap())
    }

    /// Return the number of top-level sections, excluding the PMAI file header.
    ///
    /// Includes duplicate tags, unknown tags, and newly inserted sections.
    /// This uses the index and does not read or decode payloads.
    pub fn section_count(&self) -> usize {
        self.sections.len()
    }

    /// Populate one valid index on success; leave failed decodes uncached.
    fn decode(&mut self, index: usize) -> Result<()> {
        if self.sections[index].decoded.is_none() {
            self.source()?;
        }
        let entry = &mut self.sections[index];
        if entry.decoded.is_none() {
            let range = entry
                .original_range
                .as_ref()
                .expect("unloaded section has source bytes");
            let result = (|| -> Result<Section> {
                let source = self.source.as_mut().unwrap();
                source.seek(SeekFrom::Start(range.start))?;
                let mut bytes = vec![0; (range.end - range.start) as usize];
                source.read_exact(&mut bytes)?;
                // Isolate the parser from adjacent sections, including its seeks
                // and enum backtracking. Drop these raw bytes after decoding.
                let mut reader = Cursor::new(bytes);
                let section = Section::read_be(&mut reader)?;
                if reader.position() != range.end - range.start {
                    return Err(Error::AnlzError(
                        "Section parser did not consume its declared size".into(),
                    ));
                }
                Ok(section)
            })();
            entry.decoded = Some(result.map_err(|e| {
                Error::AnlzError(format!(
                    "{}: section {index} ({:?}) at {}: {e}",
                    self.path.display(),
                    entry.tag,
                    range.start
                ))
            })?);
        }
        Ok(())
    }

    /// Borrow the section at a zero-based position in the current file order.
    ///
    /// Decodes and caches that section on first access without marking it modified.
    /// Returns `Ok(None)` for an out-of-range index and an error if decoding fails.
    /// Indices refer to positions, not stable identifiers: inserting a missing
    /// PPTH through [`set_path`](Self::set_path) shifts existing positions by one.
    pub fn get_section(&mut self, index: usize) -> Result<Option<&Section>> {
        if index >= self.sections.len() {
            return Ok(None);
        }
        self.decode(index)?;
        Ok(self.sections[index].decoded.as_ref())
    }

    /// Mutably borrow the section at a zero-based position in the current file order.
    ///
    /// Uses the same loading and bounds behavior as [`get_section`](Self::get_section).
    /// A successful access marks the section for serialization even if no fields
    /// are changed. When editing the whole section, keep its tag and content variant
    /// consistent; [`dump_copy`](Self::dump_copy) checks this before committing output.
    pub fn get_mut_section(&mut self, index: usize) -> Result<Option<&mut Section>> {
        if index >= self.sections.len() {
            return Ok(None);
        }
        self.decode(index)?;
        self.sections[index].potentially_modified = true;
        Ok(self.sections[index].decoded.as_mut())
    }

    /// Mutably borrow the first section with `tag`, in file order.
    ///
    /// Returns `Ok(None)` if absent. Only the selected section is decoded and marked
    /// for serialization. Use [`get_mut_sections_by_tag`](Self::get_mut_sections_by_tag)
    /// to edit every occurrence of a repeated tag. Reading or parsing can fail.
    pub fn get_mut_section_by_tag(&mut self, tag: AnlzTag) -> Result<Option<&mut Section>> {
        match self.sections.iter().position(|s| s.tag() == &tag) {
            Some(i) => self.get_mut_section(i),
            None => Ok(None),
        }
    }

    /// Borrow the first section with `tag`, in file order.
    ///
    /// Returns `Ok(None)` if absent. Only the selected section is decoded; the
    /// access does not mark it modified. Reading or parsing can fail.
    /// Use indexed access to select a later occurrence of a repeated tag.
    pub fn get_section_by_tag(&mut self, tag: AnlzTag) -> Result<Option<&Section>> {
        match self.sections.iter().position(|s| s.tag() == &tag) {
            Some(i) => self.get_section(i),
            None => Ok(None),
        }
    }

    /// Mutably borrow every section with `tag`, preserving file order.
    ///
    /// Returns an empty vector if absent. All matches are decoded before any are
    /// marked for serialization. If a decode fails, the error is returned and
    /// earlier successful decodes remain cached; this call adds no modification
    /// flags. On success, every returned section is marked for serialization.
    pub fn get_mut_sections_by_tag(&mut self, tag: AnlzTag) -> Result<Vec<&mut Section>> {
        let indices: Vec<_> = self
            .sections
            .iter()
            .enumerate()
            .filter_map(|(i, s)| (s.tag() == &tag).then_some(i))
            .collect();
        for &i in &indices {
            self.decode(i)?;
        }
        Ok(self
            .sections
            .iter_mut()
            .enumerate()
            .filter_map(|(i, s)| {
                if indices.binary_search(&i).is_ok() {
                    s.potentially_modified = true;
                    s.decoded.as_mut()
                } else {
                    None
                }
            })
            .collect())
    }

    /// Return whether any section currently has `tag`, without reading payloads.
    ///
    /// Uses cached tags when available, so tag edits through mutable section
    /// access are reflected immediately.
    pub fn contains(&self, tag: AnlzTag) -> bool {
        self.sections.iter().any(|s| s.tag() == &tag)
    }

    /// Return section names in file order, retaining duplicate and unknown tags.
    ///
    /// Names use [`AnlzTag::to_string`] (for example, `"BeatGrid"`, not `"PQTZ"`).
    /// This reads no payloads; the `Result` return type is retained for API compatibility.
    pub fn get_tags(&self) -> Result<Vec<String>> {
        Ok(self.sections.iter().map(|s| s.tag().to_string()).collect())
    }

    /// Consume the handler and materialize all sections as owned [`AnlzData`].
    ///
    /// Includes cached edits, decodes every remaining section, and recalculates the
    /// file-header sizes. No output is written. Returns an error if any remaining
    /// section cannot be read or parsed; the handler is consumed even on failure.
    pub fn into_data(mut self) -> Result<AnlzData> {
        for i in 0..self.sections.len() {
            self.decode(i)?;
        }
        let mut data = AnlzData {
            header: self.header,
            header_data: self.header_data,
            sections: self
                .sections
                .into_iter()
                .map(|s| s.decoded.unwrap())
                .collect(),
        };
        data.update_total_size();
        Ok(data)
    }

    /// Write the current contents to `path`, replacing an existing destination.
    ///
    /// Writes a complete file through a temporary sibling, preserving section order.
    /// Sections marked for serialization are encoded from their cached values;
    /// untouched sections are copied directly from the source, even when cached.
    /// Consequently, saving does not validate the payloads of untouched sections.
    /// Lengths are updated from the output, which is flushed and synced before
    /// replacing the destination.
    ///
    /// If `path` resolves to the original source path, behaves like [`dump`](Self::dump):
    /// adopts the new file, refreshes byte ranges, and clears modification flags.
    /// Otherwise the source, cached edits, and modification flags are retained.
    ///
    /// # Errors
    ///
    /// Returns errors from source reads, serialization, destination creation or
    /// replacement, inconsistent tag/content pairs, and output exceeding the
    /// format's 32-bit file length. The destination's parent must already exist.
    /// Failures before replacement leave the destination and cached edits intact
    /// so the caller can correct the problem and retry.
    pub fn dump_copy<P: AsRef<std::path::Path>>(&mut self, path: P) -> Result<()> {
        let path = path.as_ref();
        let destination = if path.exists() {
            std::fs::canonicalize(path)?
        } else {
            let parent = path
                .parent()
                .filter(|p| !p.as_os_str().is_empty())
                .unwrap_or_else(|| std::path::Path::new("."));
            std::fs::canonicalize(parent)?.join(
                path.file_name()
                    .ok_or_else(|| Error::AnlzError("Missing output filename".into()))?,
            )
        };
        let replace_source = destination == self.path;
        self.source()?;
        let mut output = tempfile::NamedTempFile::new_in(destination.parent().unwrap())?;
        self.header.write_be(&mut output)?;
        output.write_all(&self.header_data)?;
        let mut ranges = Vec::with_capacity(self.sections.len());
        for entry in &self.sections {
            let start = output.stream_position()?;
            if entry.potentially_modified {
                let section = entry.decoded.as_ref().expect("modified section is decoded");
                if !section.tag_matches_content() {
                    return Err(Error::AnlzError(format!(
                        "Tag/content mismatch: {:?}",
                        section.tag
                    )));
                }
                section.write_be(&mut output)?;
            } else {
                let range = entry
                    .original_range
                    .as_ref()
                    .expect("clean section has source bytes");
                let source = self.source.as_mut().unwrap();
                source.seek(SeekFrom::Start(range.start))?;
                let len = range.end - range.start;
                let copied = std::io::copy(&mut source.take(len), &mut output)?;
                if copied != len {
                    return Err(Error::AnlzError("Backing file was truncated".into()));
                }
            }
            let end = output.stream_position()?;
            if end > u64::from(u32::MAX) {
                return Err(Error::AnlzError("ANLZ output exceeds 32-bit length".into()));
            }
            if entry.potentially_modified {
                // Cached binary structs can retain their original size fields.
                // Patch the common section length using the bytes actually written.
                output.seek(SeekFrom::Start(start + 8))?;
                ((end - start) as u32).write_be(&mut output)?;
                output.seek(SeekFrom::Start(end))?;
            }
            ranges.push(start..end);
        }
        let mut header = self.header.clone();
        header.total_size = u32::try_from(output.stream_position()?)
            .map_err(|_| Error::AnlzError("ANLZ output exceeds 32-bit length".into()))?;
        output.seek(SeekFrom::Start(0))?;
        header.write_be(&mut output)?;
        if let Ok(metadata) = std::fs::metadata(&destination) {
            output.as_file().set_permissions(metadata.permissions())?;
        }
        output.flush()?;
        output.as_file().sync_all()?;
        // Release the source before replacement for Windows filesystems that
        // reject replacing an open file. On failure the source is reopened when
        // next needed; cached edits and original offsets remain intact.
        if replace_source {
            self.source.take();
        }
        let file = output.persist(&destination).map_err(|e| {
            Error::AnlzError(format!("Replacing {}: {}", destination.display(), e.error))
        })?;
        if replace_source {
            // Commit offsets only after replacement succeeds. Copies to another
            // path must keep using the original ranges and modification flags.
            self.source = Some(file);
            self.header = header;
            for (entry, range) in self.sections.iter_mut().zip(ranges) {
                entry.original_range = Some(range);
                entry.potentially_modified = false;
                entry.tag = entry.tag().clone();
            }
        }
        Ok(())
    }

    /// Save the current contents to the original ANLZ path.
    ///
    /// Uses [`dump_copy`](Self::dump_copy), including its temporary-file replacement
    /// and error handling. On success, the output becomes the new backing source;
    /// byte ranges are refreshed and modification flags cleared. Decoded sections
    /// remain cached, and previously unread sections can still be loaded lazily.
    pub fn dump(&mut self) -> Result<()> {
        self.dump_copy(self.path.clone())
    }

    // ---- Beat Grid Tags -------------------------------------------------------------------------

    /// Mutably borrow the first PQTZ section (beat grid).
    ///
    /// Uses the same selection and loading behavior as [`get_beat_grid`](Self::get_beat_grid).
    /// Marks the section for serialization even if the returned value is not changed.
    pub fn get_mut_beat_grid(&mut self) -> Result<Option<&mut BeatGrid>> {
        Ok(match self.get_mut_section_by_tag(AnlzTag::BeatGrid)? {
            Some(Section {
                content: Content::BeatGrid(value),
                ..
            }) => Some(value),
            _ => None,
        })
    }

    /// Borrow the first PQTZ section (beat grid), in file order.
    ///
    /// Decodes and caches only that section without marking it modified.
    /// Returns `Ok(None)` if absent; reading or parsing errors are propagated.
    pub fn get_beat_grid(&mut self) -> Result<Option<&BeatGrid>> {
        Ok(match self.get_section_by_tag(AnlzTag::BeatGrid)? {
            Some(Section {
                content: Content::BeatGrid(value),
                ..
            }) => Some(value),
            _ => None,
        })
    }

    /// Mutably borrow the first PQT2 section (extended beat grid).
    ///
    /// Uses the same selection and loading behavior as [`get_extended_beat_grid`](Self::get_extended_beat_grid).
    /// Marks the section for serialization even if the returned value is not changed.
    pub fn get_mut_extended_beat_grid(&mut self) -> Result<Option<&mut ExtendedBeatGrid>> {
        Ok(
            match self.get_mut_section_by_tag(AnlzTag::ExtendedBeatGrid)? {
                Some(Section {
                    content: Content::ExtendedBeatGrid(value),
                    ..
                }) => Some(value),
                _ => None,
            },
        )
    }

    /// Borrow the first PQT2 section (extended beat grid), in file order.
    ///
    /// Decodes and caches only that section without marking it modified.
    /// Returns `Ok(None)` if absent; reading or parsing errors are propagated.
    pub fn get_extended_beat_grid(&mut self) -> Result<Option<&ExtendedBeatGrid>> {
        Ok(match self.get_section_by_tag(AnlzTag::ExtendedBeatGrid)? {
            Some(Section {
                content: Content::ExtendedBeatGrid(value),
                ..
            }) => Some(value),
            _ => None,
        })
    }

    // ---- Cue List Tags --------------------------------------------------------------------------

    /// Resolve a cue-list subtype without marking inspected candidates modified.
    fn cue_index(&mut self, tag: AnlzTag, list_type: CueListType) -> Result<Option<usize>> {
        for i in 0..self.sections.len() {
            if self.sections[i].tag() != &tag {
                continue;
            }
            let section = self.get_section(i)?.unwrap();
            let matches = match &section.content {
                Content::CueList(c) => c.list_type == list_type,
                Content::ExtendedCueList(c) => c.list_type == list_type,
                _ => false,
            };
            if matches {
                return Ok(Some(i));
            }
        }
        Ok(None)
    }

    /// Mutably borrow the first hot-cue list (PCOB), in file order.
    ///
    /// Uses the same selection and decoding behavior as [`get_hot_cues`](Self::get_hot_cues).
    /// Only the selected list is marked for serialization by this call; inspecting
    /// other candidates leaves their existing modification flags unchanged.
    pub fn get_mut_hot_cues(&mut self) -> Result<Option<&mut CueList>> {
        let Some(i) = self.cue_index(AnlzTag::CueList, CueListType::HotCues)? else {
            return Ok(None);
        };
        Ok(match self.get_mut_section(i)? {
            Some(Section {
                content: Content::CueList(value),
                ..
            }) => Some(value),
            _ => None,
        })
    }

    /// Borrow the first hot-cue list (PCOB), in file order.
    ///
    /// The same tag can hold memory or hot cues. Matching-tag sections are decoded
    /// in order until their list type matches, so more than one list may be cached.
    /// Returns `Ok(None)` if none matches, or an error if a candidate cannot be decoded.
    /// No modification flags are set.
    pub fn get_hot_cues(&mut self) -> Result<Option<&CueList>> {
        let Some(i) = self.cue_index(AnlzTag::CueList, CueListType::HotCues)? else {
            return Ok(None);
        };
        Ok(match self.get_section(i)? {
            Some(Section {
                content: Content::CueList(value),
                ..
            }) => Some(value),
            _ => None,
        })
    }

    /// Mutably borrow the first memory-cue list (PCOB), in file order.
    ///
    /// Uses the same selection and decoding behavior as [`get_memory_cues`](Self::get_memory_cues).
    /// Only the selected list is marked for serialization by this call; inspecting
    /// other candidates leaves their existing modification flags unchanged.
    pub fn get_mut_memory_cues(&mut self) -> Result<Option<&mut CueList>> {
        let Some(i) = self.cue_index(AnlzTag::CueList, CueListType::MemoryCues)? else {
            return Ok(None);
        };
        Ok(match self.get_mut_section(i)? {
            Some(Section {
                content: Content::CueList(value),
                ..
            }) => Some(value),
            _ => None,
        })
    }

    /// Borrow the first memory-cue list (PCOB), in file order.
    ///
    /// The same tag can hold memory or hot cues. Matching-tag sections are decoded
    /// in order until their list type matches, so more than one list may be cached.
    /// Returns `Ok(None)` if none matches, or an error if a candidate cannot be decoded.
    /// No modification flags are set.
    pub fn get_memory_cues(&mut self) -> Result<Option<&CueList>> {
        let Some(i) = self.cue_index(AnlzTag::CueList, CueListType::MemoryCues)? else {
            return Ok(None);
        };
        Ok(match self.get_section(i)? {
            Some(Section {
                content: Content::CueList(value),
                ..
            }) => Some(value),
            _ => None,
        })
    }

    /// Mutably borrow the first extended hot-cue list (PCO2), in file order.
    ///
    /// Uses the same selection and decoding behavior as [`get_extended_hot_cues`](Self::get_extended_hot_cues).
    /// Only the selected list is marked for serialization by this call; inspecting
    /// other candidates leaves their existing modification flags unchanged.
    pub fn get_mut_extended_hot_cues(&mut self) -> Result<Option<&mut ExtendedCueList>> {
        let Some(i) = self.cue_index(AnlzTag::ExtendedCueList, CueListType::HotCues)? else {
            return Ok(None);
        };
        Ok(match self.get_mut_section(i)? {
            Some(Section {
                content: Content::ExtendedCueList(value),
                ..
            }) => Some(value),
            _ => None,
        })
    }

    /// Borrow the first extended hot-cue list (PCO2), in file order.
    ///
    /// The same tag can hold memory or hot cues. Matching-tag sections are decoded
    /// in order until their list type matches, so more than one list may be cached.
    /// Returns `Ok(None)` if none matches, or an error if a candidate cannot be decoded.
    /// No modification flags are set.
    pub fn get_extended_hot_cues(&mut self) -> Result<Option<&ExtendedCueList>> {
        let Some(i) = self.cue_index(AnlzTag::ExtendedCueList, CueListType::HotCues)? else {
            return Ok(None);
        };
        Ok(match self.get_section(i)? {
            Some(Section {
                content: Content::ExtendedCueList(value),
                ..
            }) => Some(value),
            _ => None,
        })
    }

    /// Mutably borrow the first extended memory-cue list (PCO2), in file order.
    ///
    /// Uses the same selection and decoding behavior as [`get_extended_memory_cues`](Self::get_extended_memory_cues).
    /// Only the selected list is marked for serialization by this call; inspecting
    /// other candidates leaves their existing modification flags unchanged.
    pub fn get_mut_extended_memory_cues(&mut self) -> Result<Option<&mut ExtendedCueList>> {
        let Some(i) = self.cue_index(AnlzTag::ExtendedCueList, CueListType::MemoryCues)? else {
            return Ok(None);
        };
        Ok(match self.get_mut_section(i)? {
            Some(Section {
                content: Content::ExtendedCueList(value),
                ..
            }) => Some(value),
            _ => None,
        })
    }

    /// Borrow the first extended memory-cue list (PCO2), in file order.
    ///
    /// The same tag can hold memory or hot cues. Matching-tag sections are decoded
    /// in order until their list type matches, so more than one list may be cached.
    /// Returns `Ok(None)` if none matches, or an error if a candidate cannot be decoded.
    /// No modification flags are set.
    pub fn get_extended_memory_cues(&mut self) -> Result<Option<&ExtendedCueList>> {
        let Some(i) = self.cue_index(AnlzTag::ExtendedCueList, CueListType::MemoryCues)? else {
            return Ok(None);
        };
        Ok(match self.get_section(i)? {
            Some(Section {
                content: Content::ExtendedCueList(value),
                ..
            }) => Some(value),
            _ => None,
        })
    }

    // ---- Path Tag -------------------------------------------------------------------------------

    /// Return an owned copy of the audio path in the first PPTH section.
    ///
    /// This is the embedded audio-file path, not the ANLZ file's source path.
    /// Returns `Ok(None)` if absent; reading or parsing PPTH can fail.
    /// Does not mark the section modified.
    pub fn get_path(&mut self) -> Result<Option<String>> {
        Ok(match self.get_section_by_tag(AnlzTag::Path)? {
            Some(Section {
                content: Content::Path(p),
                ..
            }) => Some(p.path.to_string()),
            _ => None,
        })
    }

    /// Set the embedded audio path in the first PPTH section.
    ///
    /// Updates an existing section in place, or inserts a new PPTH as the first
    /// section after PMAI. Insertion shifts existing section indices by one.
    /// Path conversion follows [`Path::set`], including normalizing backslashes to
    /// forward slashes. The ANLZ source path is unchanged.
    ///
    /// Only the affected section is marked for serialization; unrelated payloads
    /// are not decoded. Call [`dump`](Self::dump) or [`dump_copy`](Self::dump_copy)
    /// to persist the edit. Reading an existing PPTH or a tag/content mismatch
    /// can produce an error.
    pub fn set_path<P: AsRef<std::path::Path>>(&mut self, path: P) -> Result<()> {
        if let Some(section) = self.get_mut_section_by_tag(AnlzTag::Path)? {
            match &mut section.content {
                Content::Path(p) => p.set(path),
                _ => return Err(Error::AnlzError("Path tag/content mismatch".into())),
            }
        } else {
            self.sections.insert(
                0,
                SectionEntry {
                    original_range: None,
                    tag: AnlzTag::Path,
                    decoded: Some(Section {
                        tag: AnlzTag::Path,
                        content: Content::Path(Path::new(path)),
                    }),
                    potentially_modified: true,
                },
            );
        }
        Ok(())
    }

    // ---- VBR Tag --------------------------------------------------------------------------------

    /// Mutably borrow the first PVBR section (variable-bitrate seek table).
    ///
    /// Uses the same selection and loading behavior as [`get_vbr`](Self::get_vbr).
    /// Marks the section for serialization even if the returned value is not changed.
    pub fn get_mut_vbr(&mut self) -> Result<Option<&mut VBR>> {
        Ok(match self.get_mut_section_by_tag(AnlzTag::VBR)? {
            Some(Section {
                content: Content::VBR(value),
                ..
            }) => Some(value),
            _ => None,
        })
    }

    /// Borrow the first PVBR section (variable-bitrate seek table), in file order.
    ///
    /// Decodes and caches only that section without marking it modified.
    /// Returns `Ok(None)` if absent; reading or parsing errors are propagated.
    pub fn get_vbr(&mut self) -> Result<Option<&VBR>> {
        Ok(match self.get_section_by_tag(AnlzTag::VBR)? {
            Some(Section {
                content: Content::VBR(value),
                ..
            }) => Some(value),
            _ => None,
        })
    }

    /// Return an owned big-endian byte representation of the PVBR index and trailer.
    ///
    /// Contains the 400 index values followed by `u2`, excluding the section header
    /// and `u1`. Retained for compatibility; prefer [`get_vbr`](Self::get_vbr)
    /// for typed access without this allocation. Shares that getter's loading,
    /// absence, and error behavior.
    pub fn get_vbr_data(&mut self) -> Result<Option<Vec<u8>>> {
        Ok(self.get_vbr()?.map(|v| {
            v.index
                .iter()
                .chain(std::iter::once(&v.u2))
                .flat_map(|v| v.to_be_bytes())
                .collect()
        }))
    }

    /// Mutably borrow the first PVB2 section (frame seek index).
    ///
    /// Uses the same selection and loading behavior as [`get_seek_index`](Self::get_seek_index).
    /// Marks the section for serialization even if the returned value is not changed.
    pub fn get_mut_seek_index(&mut self) -> Result<Option<&mut SeekIndex>> {
        Ok(match self.get_mut_section_by_tag(AnlzTag::SeekIndex)? {
            Some(Section {
                content: Content::SeekIndex(value),
                ..
            }) => Some(value),
            _ => None,
        })
    }

    /// Borrow the first PVB2 section (frame seek index), in file order.
    ///
    /// Decodes and caches only that section without marking it modified.
    /// Returns `Ok(None)` if absent; reading or parsing errors are propagated.
    pub fn get_seek_index(&mut self) -> Result<Option<&SeekIndex>> {
        Ok(match self.get_section_by_tag(AnlzTag::SeekIndex)? {
            Some(Section {
                content: Content::SeekIndex(value),
                ..
            }) => Some(value),
            _ => None,
        })
    }

    // ---- Tiny Waveform Preview Tag --------------------------------------------------------------

    /// Mutably borrow the first PWV2 section (small monochrome waveform preview).
    ///
    /// Uses the same selection and loading behavior as [`get_tiny_waveform_preview`](Self::get_tiny_waveform_preview).
    /// Marks the section for serialization even if the returned value is not changed.
    pub fn get_mut_tiny_waveform_preview(&mut self) -> Result<Option<&mut TinyWaveformPreview>> {
        Ok(
            match self.get_mut_section_by_tag(AnlzTag::TinyWaveformPreview)? {
                Some(Section {
                    content: Content::TinyWaveformPreview(value),
                    ..
                }) => Some(value),
                _ => None,
            },
        )
    }

    /// Borrow the first PWV2 section (small monochrome waveform preview), in file order.
    ///
    /// Decodes and caches only that section without marking it modified.
    /// Returns `Ok(None)` if absent; reading or parsing errors are propagated.
    pub fn get_tiny_waveform_preview(&mut self) -> Result<Option<&TinyWaveformPreview>> {
        Ok(
            match self.get_section_by_tag(AnlzTag::TinyWaveformPreview)? {
                Some(Section {
                    content: Content::TinyWaveformPreview(value),
                    ..
                }) => Some(value),
                _ => None,
            },
        )
    }

    // ---- Waveform Tags --------------------------------------------------------------------------

    /// Mutably borrow the first PWAV section (monochrome waveform preview).
    ///
    /// Uses the same selection and loading behavior as [`get_waveform_preview`](Self::get_waveform_preview).
    /// Marks the section for serialization even if the returned value is not changed.
    pub fn get_mut_waveform_preview(&mut self) -> Result<Option<&mut WaveformPreview>> {
        Ok(
            match self.get_mut_section_by_tag(AnlzTag::WaveformPreview)? {
                Some(Section {
                    content: Content::WaveformPreview(value),
                    ..
                }) => Some(value),
                _ => None,
            },
        )
    }

    /// Borrow the first PWAV section (monochrome waveform preview), in file order.
    ///
    /// Decodes and caches only that section without marking it modified.
    /// Returns `Ok(None)` if absent; reading or parsing errors are propagated.
    pub fn get_waveform_preview(&mut self) -> Result<Option<&WaveformPreview>> {
        Ok(match self.get_section_by_tag(AnlzTag::WaveformPreview)? {
            Some(Section {
                content: Content::WaveformPreview(value),
                ..
            }) => Some(value),
            _ => None,
        })
    }

    /// Mutably borrow the first PWV3 section (detailed monochrome waveform).
    ///
    /// Uses the same selection and loading behavior as [`get_waveform_detail`](Self::get_waveform_detail).
    /// Marks the section for serialization even if the returned value is not changed.
    pub fn get_mut_waveform_detail(&mut self) -> Result<Option<&mut WaveformDetail>> {
        Ok(
            match self.get_mut_section_by_tag(AnlzTag::WaveformDetail)? {
                Some(Section {
                    content: Content::WaveformDetail(value),
                    ..
                }) => Some(value),
                _ => None,
            },
        )
    }

    /// Borrow the first PWV3 section (detailed monochrome waveform), in file order.
    ///
    /// Decodes and caches only that section without marking it modified.
    /// Returns `Ok(None)` if absent; reading or parsing errors are propagated.
    pub fn get_waveform_detail(&mut self) -> Result<Option<&WaveformDetail>> {
        Ok(match self.get_section_by_tag(AnlzTag::WaveformDetail)? {
            Some(Section {
                content: Content::WaveformDetail(value),
                ..
            }) => Some(value),
            _ => None,
        })
    }

    // ---- Waveform Color Tag ---------------------------------------------------------------------

    /// Mutably borrow the first PWV4 section (color waveform preview).
    ///
    /// Uses the same selection and loading behavior as [`get_waveform_color_preview`](Self::get_waveform_color_preview).
    /// Marks the section for serialization even if the returned value is not changed.
    pub fn get_mut_waveform_color_preview(&mut self) -> Result<Option<&mut WaveformColorPreview>> {
        Ok(
            match self.get_mut_section_by_tag(AnlzTag::WaveformColorPreview)? {
                Some(Section {
                    content: Content::WaveformColorPreview(value),
                    ..
                }) => Some(value),
                _ => None,
            },
        )
    }

    /// Borrow the first PWV4 section (color waveform preview), in file order.
    ///
    /// Decodes and caches only that section without marking it modified.
    /// Returns `Ok(None)` if absent; reading or parsing errors are propagated.
    pub fn get_waveform_color_preview(&mut self) -> Result<Option<&WaveformColorPreview>> {
        Ok(
            match self.get_section_by_tag(AnlzTag::WaveformColorPreview)? {
                Some(Section {
                    content: Content::WaveformColorPreview(value),
                    ..
                }) => Some(value),
                _ => None,
            },
        )
    }

    // ---- Waveform Color Detail Tag --------------------------------------------------------------

    /// Mutably borrow the first PWV5 section (detailed color waveform).
    ///
    /// Uses the same selection and loading behavior as [`get_waveform_color_detail`](Self::get_waveform_color_detail).
    /// Marks the section for serialization even if the returned value is not changed.
    pub fn get_mut_waveform_color_detail(&mut self) -> Result<Option<&mut WaveformColorDetail>> {
        Ok(
            match self.get_mut_section_by_tag(AnlzTag::WaveformColorDetail)? {
                Some(Section {
                    content: Content::WaveformColorDetail(value),
                    ..
                }) => Some(value),
                _ => None,
            },
        )
    }

    /// Borrow the first PWV5 section (detailed color waveform), in file order.
    ///
    /// Decodes and caches only that section without marking it modified.
    /// Returns `Ok(None)` if absent; reading or parsing errors are propagated.
    pub fn get_waveform_color_detail(&mut self) -> Result<Option<&WaveformColorDetail>> {
        Ok(
            match self.get_section_by_tag(AnlzTag::WaveformColorDetail)? {
                Some(Section {
                    content: Content::WaveformColorDetail(value),
                    ..
                }) => Some(value),
                _ => None,
            },
        )
    }

    // ---- Waveform 3-Band Tags -------------------------------------------------------------------

    /// Mutably borrow the first PWV6 section (three-band waveform preview).
    ///
    /// Uses the same selection and loading behavior as [`get_waveform_3band_preview`](Self::get_waveform_3band_preview).
    /// Marks the section for serialization even if the returned value is not changed.
    pub fn get_mut_waveform_3band_preview(&mut self) -> Result<Option<&mut Waveform3BandPreview>> {
        Ok(
            match self.get_mut_section_by_tag(AnlzTag::Waveform3BandPreview)? {
                Some(Section {
                    content: Content::Waveform3BandPreview(value),
                    ..
                }) => Some(value),
                _ => None,
            },
        )
    }

    /// Borrow the first PWV6 section (three-band waveform preview), in file order.
    ///
    /// Decodes and caches only that section without marking it modified.
    /// Returns `Ok(None)` if absent; reading or parsing errors are propagated.
    pub fn get_waveform_3band_preview(&mut self) -> Result<Option<&Waveform3BandPreview>> {
        Ok(
            match self.get_section_by_tag(AnlzTag::Waveform3BandPreview)? {
                Some(Section {
                    content: Content::Waveform3BandPreview(value),
                    ..
                }) => Some(value),
                _ => None,
            },
        )
    }

    /// Mutably borrow the first PWV7 section (detailed three-band waveform).
    ///
    /// Uses the same selection and loading behavior as [`get_waveform_3band_detail`](Self::get_waveform_3band_detail).
    /// Marks the section for serialization even if the returned value is not changed.
    pub fn get_mut_waveform_3band_detail(&mut self) -> Result<Option<&mut Waveform3BandDetail>> {
        Ok(
            match self.get_mut_section_by_tag(AnlzTag::Waveform3BandDetail)? {
                Some(Section {
                    content: Content::Waveform3BandDetail(value),
                    ..
                }) => Some(value),
                _ => None,
            },
        )
    }

    /// Borrow the first PWV7 section (detailed three-band waveform), in file order.
    ///
    /// Decodes and caches only that section without marking it modified.
    /// Returns `Ok(None)` if absent; reading or parsing errors are propagated.
    pub fn get_waveform_3band_detail(&mut self) -> Result<Option<&Waveform3BandDetail>> {
        Ok(
            match self.get_section_by_tag(AnlzTag::Waveform3BandDetail)? {
                Some(Section {
                    content: Content::Waveform3BandDetail(value),
                    ..
                }) => Some(value),
                _ => None,
            },
        )
    }

    // ---- Waveform 3-Band Calibration Tag --------------------------------------------------------

    /// Mutably borrow the first PWVC section (three-band waveform calibration).
    ///
    /// Uses the same selection and loading behavior as [`get_waveform_3band_calibration`](Self::get_waveform_3band_calibration).
    /// Marks the section for serialization even if the returned value is not changed.
    pub fn get_mut_waveform_3band_calibration(
        &mut self,
    ) -> Result<Option<&mut Waveform3BandCalibration>> {
        Ok(
            match self.get_mut_section_by_tag(AnlzTag::Waveform3BandCalibration)? {
                Some(Section {
                    content: Content::Waveform3BandCalibration(value),
                    ..
                }) => Some(value),
                _ => None,
            },
        )
    }

    /// Borrow the first PWVC section (three-band waveform calibration), in file order.
    ///
    /// Decodes and caches only that section without marking it modified.
    /// Returns `Ok(None)` if absent; reading or parsing errors are propagated.
    pub fn get_waveform_3band_calibration(&mut self) -> Result<Option<&Waveform3BandCalibration>> {
        Ok(
            match self.get_section_by_tag(AnlzTag::Waveform3BandCalibration)? {
                Some(Section {
                    content: Content::Waveform3BandCalibration(value),
                    ..
                }) => Some(value),
                _ => None,
            },
        )
    }

    // ---- Song Structure Tag ---------------------------------------------------------------------

    /// Mutably borrow the analysis data in the first PSSI song-structure section.
    ///
    /// Decodes the section on demand, including decryption when needed, and marks
    /// it for serialization. The enclosing section's version and encryption fields
    /// are preserved; use [`get_mut_section_by_tag`](Self::get_mut_section_by_tag)
    /// to edit those fields. Returns `Ok(None)` if absent or an error on decode failure.
    pub fn get_mut_song_structure(&mut self) -> Result<Option<&mut SongStructureData>> {
        Ok(match self.get_mut_section_by_tag(AnlzTag::SongStructure)? {
            Some(Section {
                content: Content::SongStructure(s),
                ..
            }) => Some(&mut s.data),
            _ => None,
        })
    }

    /// Borrow the analysis data in the first PSSI song-structure section.
    ///
    /// Decodes and caches the section, including decryption when needed, without
    /// marking it modified. Returns `Ok(None)` if absent or an error on decode failure.
    /// Call `.cloned()` on the returned option when an owned copy is needed.
    pub fn get_song_structure(&mut self) -> Result<Option<&SongStructureData>> {
        Ok(match self.get_section_by_tag(AnlzTag::SongStructure)? {
            Some(Section {
                content: Content::SongStructure(s),
                ..
            }) => Some(&s.data),
            _ => None,
        })
    }

    // ---- Vocal Detection ------------------------------------------------------------------------

    /// Mutably borrow the first PVDI section (vocal-detection confidence data).
    ///
    /// Uses the same selection and loading behavior as [`get_vocal_detection`](Self::get_vocal_detection).
    /// Marks the section for serialization even if the returned value is not changed.
    pub fn get_mut_vocal_detection(&mut self) -> Result<Option<&mut VocalDetection>> {
        Ok(
            match self.get_mut_section_by_tag(AnlzTag::VocalDetection)? {
                Some(Section {
                    content: Content::VocalDetection(value),
                    ..
                }) => Some(value),
                _ => None,
            },
        )
    }

    /// Borrow the first PVDI section (vocal-detection confidence data), in file order.
    ///
    /// Decodes and caches only that section without marking it modified.
    /// Returns `Ok(None)` if absent; reading or parsing errors are propagated.
    pub fn get_vocal_detection(&mut self) -> Result<Option<&VocalDetection>> {
        Ok(match self.get_section_by_tag(AnlzTag::VocalDetection)? {
            Some(Section {
                content: Content::VocalDetection(value),
                ..
            }) => Some(value),
            _ => None,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(windows)]
    #[test]
    fn failed_source_replacement_reopens_for_retry() {
        use std::os::windows::fs::OpenOptionsExt;
        let bytes = file_bytes(&[path_section("/old"), waveform()]);
        let (_dir, mut file) = open(&bytes);
        file.set_path("/new").unwrap();
        // Allow readers/writers but deny delete sharing, forcing replacement to fail.
        let lock = std::fs::OpenOptions::new()
            .read(true)
            .share_mode(3)
            .open(&file.path)
            .unwrap();
        assert!(file.dump().is_err());
        assert!(file.source.is_none());
        assert_eq!(std::fs::read(&file.path).unwrap(), bytes);
        assert!(file.sections[0].potentially_modified);
        drop(lock);
        // An unloaded read must reopen the old source with its original offsets.
        assert_eq!(
            file.get_waveform_detail().unwrap().unwrap().data.len(),
            100_000
        );
        file.dump().unwrap();
        assert_eq!(
            Anlz::load(&file.path)
                .unwrap()
                .get_path()
                .unwrap()
                .as_deref(),
            Some("/new")
        );
    }

    #[test]
    fn index_reads_only_headers_and_seeks_over_payloads() {
        struct TrackedReader {
            inner: Cursor<Vec<u8>>,
            reads: Vec<Range<u64>>,
        }
        impl Read for TrackedReader {
            fn read(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
                let start = self.inner.position();
                let n = self.inner.read(bytes)?;
                self.reads.push(start..start + n as u64);
                Ok(n)
            }
        }
        impl Seek for TrackedReader {
            fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
                self.inner.seek(pos)
            }
        }
        let wave = waveform();
        let mut reader = TrackedReader {
            inner: Cursor::new(file_bytes(&[wave.clone(), wave])),
            reads: Vec::new(),
        };
        let (_, _, entries) = Anlz::index(&mut reader).unwrap();
        for entry in entries {
            let range = entry.original_range.unwrap();
            let payload = range.start + 12..range.end;
            assert!(reader
                .reads
                .iter()
                .all(|r| r.end <= payload.start || r.start >= payload.end));
        }
        assert_eq!(
            reader.reads.iter().map(|r| r.end - r.start).sum::<u64>(),
            28 + 2 * 12
        );
    }

    #[test]
    fn section_boundary_prevents_consuming_next_section() {
        let mut broken = waveform();
        broken.truncate(24); // claims one sample but has no payload
        broken[8..12].copy_from_slice(&24u32.to_be_bytes());
        broken[16..20].copy_from_slice(&1u32.to_be_bytes());
        let (_dir, mut file) = open(&file_bytes(&[broken, path_section("/still-readable")]));
        assert!(file.get_waveform_detail().is_err());
        assert_eq!(file.get_path().unwrap().as_deref(), Some("/still-readable"));
    }

    #[test]
    fn persistence_failure_can_be_retried() {
        let bytes = file_bytes(&[path_section("/old"), waveform()]);
        let (dir, mut file) = open(&bytes);
        file.set_path("/new").unwrap();
        let directory_destination = dir.path().join("a-directory");
        std::fs::create_dir(&directory_destination).unwrap();
        assert!(file.dump_copy(&directory_destination).is_err());
        assert_eq!(std::fs::read(&file.path).unwrap(), bytes);
        assert!(file.sections[0].potentially_modified);
        file.dump().unwrap();
        assert_eq!(file.get_path().unwrap().as_deref(), Some("/new"));
    }

    fn section(tag: &[u8; 4], header_size: u32, payload: &[u8]) -> Vec<u8> {
        let mut bytes = tag.to_vec();
        bytes.extend(header_size.to_be_bytes());
        bytes.extend((12 + payload.len() as u32).to_be_bytes());
        bytes.extend(payload);
        bytes
    }

    fn file_bytes(sections: &[Vec<u8>]) -> Vec<u8> {
        let mut bytes = b"PMAI".to_vec();
        bytes.extend(28u32.to_be_bytes());
        bytes.extend((28 + sections.iter().map(Vec::len).sum::<usize>() as u32).to_be_bytes());
        bytes.extend([0x45; 16]); // opaque file-header extension must survive saves
        for s in sections {
            bytes.extend(s);
        }
        bytes
    }

    fn path_section(path: &str) -> Vec<u8> {
        let mut cursor = Cursor::new(Vec::new());
        Section {
            tag: AnlzTag::Path,
            content: Content::Path(Path::new(path)),
        }
        .write_be(&mut cursor)
        .unwrap();
        cursor.into_inner()
    }

    fn waveform() -> Vec<u8> {
        let mut payload = Vec::new();
        payload.extend(1u32.to_be_bytes());
        payload.extend(100_000u32.to_be_bytes());
        payload.extend(0x00960000u32.to_be_bytes());
        payload.extend(vec![0x23; 100_000]);
        section(b"PWV3", 24, &payload)
    }

    fn cue(list_type: u32) -> Vec<u8> {
        let mut payload = list_type.to_be_bytes().to_vec();
        payload.extend([0; 4]);
        payload.extend(u32::MAX.to_be_bytes());
        section(b"PCOB", 24, &payload)
    }

    fn open(bytes: &[u8]) -> (tempfile::TempDir, Anlz) {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("ANLZ0000.EXT");
        std::fs::write(&path, bytes).unwrap();
        let file = Anlz::load(path).unwrap();
        (dir, file)
    }

    #[test]
    fn indexing_and_path_edits_leave_waveforms_unloaded() {
        let wave = waveform();
        let unknown = section(b"ZZZZ", 12, &[9, 8, 7]);
        let bytes = file_bytes(&[path_section("/old"), wave.clone(), unknown.clone()]);
        let (dir, mut file) = open(&bytes);
        assert_eq!(file.section_count(), 3);
        assert!(file.contains(AnlzTag::WaveformDetail));
        assert_eq!(file.get_tags().unwrap()[0], "Path");
        assert!(file.sections.iter().all(|s| s.decoded.is_none()));
        file.set_path("/a/much/longer/audio/path.flac").unwrap();
        let copy = dir.path().join("copy.EXT");
        file.dump_copy(&copy).unwrap();
        assert!(file.sections[0].potentially_modified);
        assert!(file.sections[1..].iter().all(|s| s.decoded.is_none()));
        assert_eq!(std::fs::read(&file.path).unwrap(), bytes);
        let output = std::fs::read(&copy).unwrap();
        assert!(output.ends_with(&[wave, unknown].concat()));
        assert_eq!(&output[12..28], &bytes[12..28]);
        let eager = AnlzData::read_be(&mut Cursor::new(&output)).unwrap();
        assert_eq!(eager.header.total_size as usize, output.len());
        assert_eq!(file.into_data().unwrap(), eager);
    }

    #[test]
    fn shared_access_caches_without_dirtying_and_mutable_access_dirties() {
        let (_dir, mut file) = open(&file_bytes(&[waveform()]));
        let first = file.get_waveform_detail().unwrap().unwrap().data.as_ptr();
        assert_eq!(
            first,
            file.get_waveform_detail().unwrap().unwrap().data.as_ptr()
        );
        assert!(!file.sections[0].potentially_modified);
        file.get_mut_waveform_detail().unwrap().unwrap().data.pop();
        assert!(file.sections[0].potentially_modified);
    }

    #[test]
    fn repeated_in_place_saves_refresh_unloaded_offsets() {
        let (_dir, mut file) = open(&file_bytes(&[path_section("/old"), waveform()]));
        file.set_path("/new/longer/path.flac").unwrap();
        file.dump().unwrap(); // also exercises Windows replacement of an open source
        assert!(file.sections.iter().all(|s| !s.potentially_modified));
        assert!(file.sections[1].decoded.is_none());
        file.dump_copy(file.path.clone()).unwrap();
        assert_eq!(
            file.get_waveform_detail().unwrap().unwrap().data.len(),
            100_000
        );
        file.get_mut_waveform_detail()
            .unwrap()
            .unwrap()
            .data
            .truncate(17);
        file.dump().unwrap();
        let mut reopened = Anlz::load(&file.path).unwrap();
        assert_eq!(
            reopened.get_path().unwrap().as_deref(),
            Some("/new/longer/path.flac")
        );
        assert_eq!(
            reopened.get_waveform_detail().unwrap().unwrap().data.len(),
            17
        );
        // Parsed structs retain private input-length fields; writers recalculate
        // them. Compare the materialized wire representation after resizing.
        let mut cached = Cursor::new(Vec::new());
        file.into_data().unwrap().write_be(&mut cached).unwrap();
        let mut fresh = Cursor::new(Vec::new());
        reopened.into_data().unwrap().write_be(&mut fresh).unwrap();
        assert_eq!(cached.into_inner(), fresh.into_inner());
    }

    #[test]
    fn unknown_duplicates_and_missing_path_keep_order() {
        let unknown = section(b"ZZZZ", 12, &[7, 6, 5]);
        let bytes = file_bytes(&[unknown.clone(), cue(1), cue(0), unknown.clone()]);
        let (_dir, mut file) = open(&bytes);
        assert_eq!(
            file.get_mut_hot_cues().unwrap().unwrap().list_type,
            CueListType::HotCues
        );
        assert_eq!(
            file.get_mut_memory_cues().unwrap().unwrap().list_type,
            CueListType::MemoryCues
        );
        file.set_path("/inserted").unwrap();
        file.dump().unwrap();
        let mut reopened = Anlz::load(&file.path).unwrap();
        assert_eq!(reopened.get_section(0).unwrap().unwrap().tag, AnlzTag::Path);
        assert_eq!(
            reopened
                .get_mut_sections_by_tag(AnlzTag::CueList)
                .unwrap()
                .len(),
            2
        );
        assert_eq!(
            reopened.get_section(1).unwrap().unwrap().tag,
            AnlzTag::Unknown(*b"ZZZZ")
        );
        assert_eq!(
            reopened.get_section(4).unwrap().unwrap().tag,
            AnlzTag::Unknown(*b"ZZZZ")
        );
        assert!(reopened.get_section(5).unwrap().is_none());
        assert!(std::fs::read(&file.path).unwrap().ends_with(&unknown));
    }

    #[test]
    fn malformed_payload_is_deferred_and_can_be_copied_untouched() {
        let invalid = section(b"PQTZ", 24, &[0; 12]); // valid outer header, invalid PQTZ header size/data
        let mut invalid = invalid;
        // n_beats = 1 but there are no beat records.
        invalid[20..24].copy_from_slice(&1u32.to_be_bytes());
        let bytes = file_bytes(&[path_section("/old"), invalid.clone(), waveform()]);
        let (dir, mut file) = open(&bytes);
        assert!(file.get_mut_beat_grid().is_err());
        assert!(file.sections[1].decoded.is_none());
        assert!(file.sections.iter().all(|s| !s.potentially_modified));
        file.set_path("/new").unwrap();
        let out = dir.path().join("copy.EXT");
        file.dump_copy(&out).unwrap();
        let mut copied = Anlz::load(&out).unwrap();
        assert_eq!(copied.get_path().unwrap().as_deref(), Some("/new"));
        assert!(copied.get_mut_beat_grid().is_err());
        assert_eq!(
            copied.get_waveform_detail().unwrap().unwrap().data.len(),
            100_000
        );
    }

    #[test]
    fn invalid_outer_bounds_fail_at_open() {
        for (offset, value) in [(4, 11u32), (8, 1), (32, 11), (36, 0), (36, u32::MAX)] {
            let mut bytes = file_bytes(&[waveform()]);
            bytes[offset..offset + 4].copy_from_slice(&value.to_be_bytes());
            let dir = tempfile::tempdir().unwrap();
            let path = dir.path().join("bad.EXT");
            std::fs::write(&path, bytes).unwrap();
            assert!(Anlz::load(path).is_err(), "offset {offset}, value {value}");
        }
    }

    #[test]
    fn unchanged_save_is_byte_exact_even_after_shared_reads() {
        let bytes = file_bytes(&[path_section("/audio.flac"), waveform(), cue(0), cue(1)]);
        let (_dir, mut file) = open(&bytes);
        file.get_waveform_detail().unwrap();
        file.get_memory_cues().unwrap();
        file.dump().unwrap();
        assert_eq!(std::fs::read(&file.path).unwrap(), bytes);
    }

    #[test]
    fn failed_save_preserves_original_and_edits_for_retry() {
        let bytes = file_bytes(&[path_section("/old"), waveform()]);
        let (dir, mut file) = open(&bytes);
        file.set_path("/new").unwrap();
        let destination = dir.path().join("existing.EXT");
        std::fs::write(&destination, b"keep me").unwrap();
        // A mutable section's public tag and content must agree.
        file.get_mut_section(0).unwrap().unwrap().tag = AnlzTag::BeatGrid;
        assert!(file.contains(AnlzTag::BeatGrid)); // queries follow edits, not stale metadata
        assert!(!file.contains(AnlzTag::Path));
        assert!(file.dump_copy(&destination).is_err());
        assert_eq!(std::fs::read(&destination).unwrap(), b"keep me");
        assert_eq!(std::fs::read(&file.path).unwrap(), bytes);
        assert!(file.sections[0].potentially_modified);
        file.get_mut_section(0).unwrap().unwrap().tag = AnlzTag::Path;
        file.dump().unwrap();
        assert_eq!(
            Anlz::load(&file.path)
                .unwrap()
                .get_path()
                .unwrap()
                .as_deref(),
            Some("/new")
        );
    }
}