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
use super::{
ArchiveVersion, Ba2CompressionFormat, Error, FileHash, PayloadFormat, Result, hash_file, parser,
};
use crate::{BStr, BString, ByteSlice as _};
use crate::{
Copied,
dds::{self, DdsHeader},
extract::{ensure_parent_dir, output_path_into, write_file_atomically},
storage::Storage,
};
#[cfg(feature = "parallel")]
use rayon::prelude::*;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
/// Metadata read from the archive header.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ArchiveInfo {
pub format: PayloadFormat,
pub version: ArchiveVersion,
pub compression_format: Ba2CompressionFormat,
pub strings: bool,
}
/// Stable identifier for an entry within one parsed BA2 archive.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct EntryId(usize);
impl EntryId {
#[must_use]
pub const fn from_index(index: usize) -> Self {
Self(index)
}
#[must_use]
pub const fn index(self) -> usize {
self.0
}
}
impl Default for ArchiveInfo {
fn default() -> Self {
Self {
format: PayloadFormat::GNRL,
version: ArchiveVersion::v1,
compression_format: Ba2CompressionFormat::Zip,
strings: false,
}
}
}
/// Texture file header stored in DX10 BA2 archives.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct TextureHeader {
pub height: u16,
pub width: u16,
pub mip_count: u8,
/// DXGI format number stored by BA2.
pub format: u8,
/// Low byte of the BA2 texture flags field. Bit 0 marks cubemaps.
pub flags: u8,
/// High byte of the BA2 texture flags field. `OpenMW` treats this as tile mode.
pub tile_mode: u8,
}
impl TextureHeader {
fn dds_header(self) -> DdsHeader {
DdsHeader {
height: self.height,
width: self.width,
mip_count: self.mip_count,
format: self.format,
flags: self.flags,
}
}
}
/// Per-file metadata.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub enum FileHeader {
#[default]
GNRL,
DX10(TextureHeader),
/// Sony GNM (`.gnf`) texture metadata.
///
/// Metadata is exposed for identification only. GNMF extraction/writing is
/// intentionally unsupported because correct output requires console texture
/// swizzle/unswizzle semantics.
GNMF([u32; 8]),
}
/// A file entry in the archive index.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Entry {
name: BString,
hash: FileHash,
file: ArchiveFile,
}
impl Entry {
/// Stored string-table name for this entry.
///
/// This is empty when the archive did not store a string table. Use
/// [`Archive::get_by_hash`] or the entry hash in that case; an empty string
/// here is missing path text, not a real empty filename.
#[must_use]
pub fn name(&self) -> &BStr {
self.name.as_bstr()
}
#[must_use]
pub fn hash(&self) -> FileHash {
self.hash
}
#[must_use]
pub fn file(&self) -> &ArchiveFile {
&self.file
}
}
/// Chunked file stored in a BA2 archive.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ArchiveFile {
pub header: FileHeader,
pub chunks: Vec<super::Chunk>,
}
impl ArchiveFile {
#[must_use]
pub fn len(&self) -> usize {
self.chunks.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.chunks.is_empty()
}
#[must_use]
pub fn chunks(&self) -> &[super::Chunk] {
&self.chunks
}
}
/// Parsed BA2 archive. The archive bytes are immutable, so extraction can be
/// performed through shared references.
#[derive(Clone, Debug)]
pub struct Archive {
storage: Storage,
info: ArchiveInfo,
entries: Vec<Entry>,
lookup: HashMap<FileHash, usize>,
name_lookup: HashMap<BString, usize>,
}
impl Archive {
/// Read an archive from an owned byte buffer.
///
/// # Errors
///
/// Returns an error when the buffer is not a valid supported BA2 archive.
pub fn from_vec(bytes: Vec<u8>) -> Result<Self> {
parser::parse(Storage::from_vec(bytes))
}
/// Read an archive from a byte slice, copying the archive data.
///
/// # Errors
///
/// Returns an error when the slice is not a valid supported BA2 archive.
pub fn from_slice(bytes: &[u8]) -> Result<Self> {
Self::from_vec(bytes.to_vec())
}
/// Read an archive from a filesystem path.
///
/// # Errors
///
/// Returns an I/O error if the path can not be read, or a parse error when
/// the file is not a valid supported BA2 archive.
pub fn open_path(path: impl AsRef<Path>) -> Result<Self> {
parser::parse(Storage::open_path(path)?)
}
/// Metadata read from the archive header.
#[must_use]
pub fn info(&self) -> ArchiveInfo {
self.info
}
/// All entries, in archive table order.
#[must_use]
pub fn entries(&self) -> &[Entry] {
&self.entries
}
pub fn entries_with_ids(&self) -> impl Iterator<Item = (EntryId, &Entry)> {
self.entries
.iter()
.enumerate()
.map(|(index, entry)| (EntryId(index), entry))
}
#[must_use]
pub fn entry_by_id(&self, id: EntryId) -> Option<&Entry> {
self.entries.get(id.0)
}
/// Get an entry by stable id, returning an error when it is absent.
///
/// # Errors
///
/// Returns [`Error::OutOfBounds`] when `id` does not identify an entry in this archive.
pub fn entry_by_id_required(&self, id: EntryId) -> Result<&Entry> {
self.entry_by_id(id).ok_or(Error::OutOfBounds)
}
/// Return the decoded size that extraction would write for an entry.
///
/// # Errors
///
/// Returns an error if entry metadata is invalid or size metadata overflows
/// the public return type.
pub fn extracted_len(&self, entry: &Entry) -> Result<u64> {
let chunks_size = u64::try_from(entry.file.decompressed_size()?)?;
match entry.file.header {
FileHeader::GNRL => Ok(chunks_size),
FileHeader::DX10(texture) => {
let mut header = Vec::new();
dds::write_dds_header(&mut header, texture.dds_header())?;
u64::try_from(header.len())?
.checked_add(chunks_size)
.ok_or(Error::OutOfBounds)
}
FileHeader::GNMF(_) => Err(Error::NotImplemented("BA2 GNMF extraction")),
}
}
/// Return the decoded size that extraction would write for an entry id.
///
/// # Errors
///
/// Returns [`Error::OutOfBounds`] for an invalid id, or size overflow errors.
pub fn extracted_len_by_id(&self, id: EntryId) -> Result<u64> {
self.extracted_len(self.entry_by_id_required(id)?)
}
/// Extract an entry selected by stable id into a writer.
///
/// # Errors
///
/// Returns [`Error::OutOfBounds`] for an invalid id, or the same errors as entry extraction.
pub fn extract_entry_by_id(&self, id: EntryId, out: impl std::io::Write) -> Result<u64> {
self.extract_entry(self.entry_by_id_required(id)?, out)
}
/// Number of files in the archive.
#[must_use]
pub fn len(&self) -> usize {
self.entries.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
/// Get an entry by BA2 hash. Names are not required for this lookup.
#[must_use]
pub fn get_by_hash(&self, hash: FileHash) -> Option<&Entry> {
self.lookup.get(&hash).map(|&index| &self.entries[index])
}
/// Get an entry by path. The path is normalized using BA2 rules.
#[must_use]
pub fn get(&self, path: impl AsRef<[u8]>) -> Option<&Entry> {
let (hash, normalized) = hash_file(path.as_ref().as_bstr());
let index = if self.name_lookup.is_empty() {
self.lookup.get(&hash)
} else {
self.name_lookup.get(&normalized)
}?;
Some(&self.entries[*index])
}
/// Get an entry by path, returning an error when it is absent.
///
/// # Errors
///
/// Returns [`Error::FileNotFound`] when the normalized path is not present.
pub fn get_required(&self, path: impl AsRef<[u8]>) -> Result<&Entry> {
let path = path.as_ref();
self.get(path)
.ok_or_else(|| Error::FileNotFound(BString::from(path)))
}
/// Whether a path exists in this archive.
#[must_use]
pub fn contains(&self, path: impl AsRef<[u8]>) -> bool {
self.get(path).is_some()
}
/// Size in bytes of the mapped or owned archive data.
#[must_use]
pub fn archive_size(&self) -> usize {
self.storage.as_bytes().len()
}
/// Extract an entry into `out`.
///
/// # Errors
///
/// Returns an error if chunk offsets are invalid, decompression fails, the
/// declared decompressed size does not match, or the file format is not yet
/// implemented.
pub fn read_entry_into(&self, entry: &Entry, out: &mut Vec<u8>) -> Result<()> {
let before = out.len();
let result = match entry.file.header {
FileHeader::GNRL => self.extract_chunks(&entry.file, out),
FileHeader::DX10(texture) => dds::write_dds_header(out, texture.dds_header())
.and_then(|()| self.extract_chunks(&entry.file, out)),
FileHeader::GNMF(_) => Err(Error::NotImplemented("BA2 GNMF extraction")),
};
if result.is_err() {
out.truncate(before);
}
result
}
/// Extract an entry into a writer.
///
/// Compressed chunks are decompressed into a temporary buffer before they are
/// written so that malformed compressed data does not leave partial bytes in
/// arbitrary caller-owned writers. Use [`Self::extract_entry_to_path`] for
/// streaming filesystem extraction with temporary-file rollback.
///
/// # Errors
///
/// Returns an error if chunk offsets are invalid, decompression fails, the
/// declared decompressed size does not match, writing fails, or the file
/// format is not yet implemented.
pub fn extract_entry(&self, entry: &Entry, mut out: impl std::io::Write) -> Result<u64> {
match entry.file.header {
FileHeader::GNRL => self.extract_chunks_to_writer(&entry.file, &mut out),
FileHeader::DX10(texture) => {
let mut header = Vec::new();
dds::write_dds_header(&mut header, texture.dds_header())?;
out.write_all(&header)?;
Ok(u64::try_from(header.len())?
+ self.extract_chunks_to_writer(&entry.file, &mut out)?)
}
FileHeader::GNMF(_) => Err(Error::NotImplemented("BA2 GNMF extraction")),
}
}
/// Extract an entry to a filesystem path atomically.
///
/// The payload is written to a temporary file in the destination directory
/// and renamed into place only after extraction succeeds. For compressed
/// entries this avoids buffering the full decompressed payload while still
/// preserving the existing destination on failure.
///
/// # Errors
///
/// Returns the same errors as [`Self::extract_entry`], plus filesystem
/// errors for creating, writing, or renaming the output file.
pub fn extract_entry_to_path(&self, entry: &Entry, path: impl AsRef<Path>) -> Result<u64> {
write_file_atomically(path.as_ref(), |file| {
self.extract_entry_streaming(entry, file)
})
}
/// Extract an entry into a new vector.
///
/// # Errors
///
/// Returns the same errors as [`Self::read_entry_into`].
pub fn read_entry(&self, entry: &Entry) -> Result<Vec<u8>> {
let mut out = Vec::new();
out.try_reserve_exact(entry.extraction_capacity_hint()?)?;
self.read_entry_into(entry, &mut out)?;
Ok(out)
}
/// Extract a path into a new vector.
///
/// # Errors
///
/// Returns the same errors as [`Self::read_entry_into`] if the path exists.
pub fn read_file(&self, path: impl AsRef<[u8]>) -> Result<Option<Vec<u8>>> {
self.get(path)
.map(|entry| self.read_entry(entry))
.transpose()
}
/// Extract a required path into a new vector.
///
/// # Errors
///
/// Returns [`Error::FileNotFound`] if the path does not exist, or the same
/// errors as [`Self::read_entry`] when it does.
pub fn read_file_required(&self, path: impl AsRef<[u8]>) -> Result<Vec<u8>> {
self.read_entry(self.get_required(path)?)
}
/// Extract a path into a writer.
///
/// # Errors
///
/// Returns the same errors as [`Self::extract_entry`] if the path exists.
pub fn extract_file(
&self,
path: impl AsRef<[u8]>,
out: impl std::io::Write,
) -> Result<Option<u64>> {
self.get(path)
.map(|entry| self.extract_entry(entry, out))
.transpose()
}
/// Extract a required path into a writer.
///
/// # Errors
///
/// Returns [`Error::FileNotFound`] if the path does not exist, or the same
/// errors as [`Self::extract_entry`] when it does.
pub fn extract_file_required(
&self,
path: impl AsRef<[u8]>,
out: impl std::io::Write,
) -> Result<u64> {
self.extract_entry(self.get_required(path)?, out)
}
/// Extract every named entry to `target_dir`, preserving archive paths.
///
/// Returns the number of bytes written to file contents. BA2 archives
/// without a string table can still be queried by hash, but they can not be
/// dumped to a directory because there are no filenames to create.
///
/// # Errors
///
/// Returns an error if an archive entry has no safe output path, directory
/// or file creation fails, or entry extraction fails.
pub fn extract_to(&self, target_dir: impl AsRef<Path>) -> Result<u64> {
let target_dir = target_dir.as_ref();
#[cfg(feature = "parallel")]
{
self.extract_to_parallel(target_dir)
}
#[cfg(not(feature = "parallel"))]
{
self.extract_to_sequential(target_dir)
}
}
fn extract_to_sequential(&self, target_dir: &Path) -> Result<u64> {
let mut written = 0u64;
let mut path = PathBuf::new();
let mut last_parent = PathBuf::new();
for entry in &self.entries {
output_path_into(&mut path, target_dir, entry.name())?;
ensure_parent_dir(&path, &mut last_parent)?;
written += self.extract_entry_to_path(entry, &path)?;
}
Ok(written)
}
#[cfg(feature = "parallel")]
fn extract_to_parallel(&self, target_dir: &Path) -> Result<u64> {
let paths = self.extract_output_paths(target_dir)?;
if crate::extract::has_duplicate_paths(&paths) {
return self.extract_to_sequential(target_dir);
}
crate::extract::ensure_parent_dirs(&paths)?;
self.entries
.par_iter()
.zip(paths.par_iter())
.map(|(entry, path)| self.extract_entry_to_path(entry, path))
.try_reduce(|| 0, |left, right| Ok(left + right))
}
#[cfg(feature = "parallel")]
fn extract_output_paths(&self, target_dir: &Path) -> Result<Vec<PathBuf>> {
let mut paths = Vec::new();
paths.try_reserve_exact(self.entries.len())?;
for entry in &self.entries {
let mut path = PathBuf::new();
output_path_into(&mut path, target_dir, entry.name())?;
paths.push(path);
}
Ok(paths)
}
fn extract_chunks(&self, file: &ArchiveFile, out: &mut Vec<u8>) -> Result<()> {
for chunk in &file.chunks {
chunk.extract(self.storage.as_bytes(), self.info.compression_format, out)?;
}
Ok(())
}
fn extract_chunks_to_writer(
&self,
file: &ArchiveFile,
out: &mut impl std::io::Write,
) -> Result<u64> {
let mut written = 0u64;
for chunk in &file.chunks {
written += chunk.extract_to_writer(
self.storage.as_bytes(),
self.info.compression_format,
out,
)?;
}
Ok(written)
}
fn extract_entry_streaming(&self, entry: &Entry, mut out: impl std::io::Write) -> Result<u64> {
match entry.file.header {
FileHeader::GNRL => self.extract_chunks_to_writer_streaming(&entry.file, &mut out),
FileHeader::DX10(texture) => {
let mut header = Vec::new();
dds::write_dds_header(&mut header, texture.dds_header())?;
out.write_all(&header)?;
Ok(u64::try_from(header.len())?
+ self.extract_chunks_to_writer_streaming(&entry.file, &mut out)?)
}
FileHeader::GNMF(_) => Err(Error::NotImplemented("BA2 GNMF extraction")),
}
}
fn extract_chunks_to_writer_streaming(
&self,
file: &ArchiveFile,
out: &mut impl std::io::Write,
) -> Result<u64> {
let mut written = 0u64;
for chunk in &file.chunks {
written += chunk.extract_to_writer_streaming(
self.storage.as_bytes(),
self.info.compression_format,
out,
)?;
}
Ok(written)
}
pub(super) fn from_parts(storage: Storage, info: ArchiveInfo, entries: Vec<Entry>) -> Self {
let mut lookup = HashMap::with_capacity(entries.len());
let mut name_lookup = HashMap::with_capacity(entries.len());
for (index, entry) in entries.iter().enumerate() {
lookup.entry(entry.hash).or_insert(index);
if !entry.name.is_empty() {
let (_, normalized) = hash_file(entry.name.as_bstr());
name_lookup.entry(normalized).or_insert(index);
}
}
Self {
storage,
info,
entries,
lookup,
name_lookup,
}
}
}
impl Entry {
pub(super) fn new(hash: FileHash, file: ArchiveFile) -> Self {
Self {
name: BString::new(Vec::new()),
hash,
file,
}
}
pub(super) fn set_name(&mut self, name: BString) {
self.name = name;
}
fn extraction_capacity_hint(&self) -> Result<usize> {
let chunks_size = self.file.decompressed_size()?;
if matches!(self.file.header, FileHeader::DX10(_)) {
chunks_size
.checked_add(dds::MAX_HEADER_SIZE)
.ok_or(Error::OutOfBounds)
} else {
Ok(chunks_size)
}
}
}
impl ArchiveFile {
fn decompressed_size(&self) -> Result<usize> {
self.chunks.iter().try_fold(0usize, |sum, chunk| {
let size: usize = chunk.size().try_into()?;
sum.checked_add(size).ok_or(Error::OutOfBounds)
})
}
}
impl TryFrom<Copied<'_>> for Archive {
type Error = Error;
fn try_from(value: Copied<'_>) -> Result<Self> {
Self::from_slice(value.0)
}
}