forked from jzebedee/bsasharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BSAFile.cs
96 lines (81 loc) · 3.09 KB
/
BSAFile.cs
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
using BSAsharp.Format;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.IO.Compression;
namespace BSAsharp
{
/// <summary>
/// A managed representation of a BSA file record and its contents. BSAFile is not guaranteed to be valid after the BSAReader that created it is disposed.
/// </summary>
public class BSAFile
{
const uint FLAG_COMPRESS = 1 << 30;
public static bool DefaultCompressed { get; set; }
public static bool BStringPrefixed { get; set; }
public string Name { get; private set; }
public string Filename { get; private set; }
public bool IsCompressed { get; private set; }
public byte[] Data { get; private set; }
private readonly bool LeaveOpen;
internal BSAFile(string path, string name, FileRecord baseRec, BinaryReader reader, bool preSeek = true, bool leaveOpen = true)
: this(path, name, baseRec)
{
this.LeaveOpen = leaveOpen;
if (preSeek)
reader.BaseStream.Seek(baseRec.offset, SeekOrigin.Begin);
ReadFileBlock(reader, baseRec.size);
}
private BSAFile(string path, string name, FileRecord baseRec)
{
this.Name = name;
this.Filename = Path.Combine(path, name);
bool compressBitSet = (baseRec.size & FLAG_COMPRESS) != 0;
this.IsCompressed = DefaultCompressed ^ compressBitSet;
}
private void ReadFileBlock(BinaryReader reader, uint size)
{
if (BStringPrefixed)
{
throw new NotImplementedException();
//var name = reader.ReadBString();
}
if (size == 0 || (size <= 4 && IsCompressed))
{
this.Data = new byte[0];
return;
}
if (IsCompressed)
{
var originalSize = reader.ReadUInt32();
size -= sizeof(uint);
//Skips zlib descriptors
reader.BaseStream.Seek(2, SeekOrigin.Current);
var decompressedData = ZlibDecompress(reader.BaseStream, originalSize);
Trace.Assert(decompressedData.Length == originalSize);
this.Data = decompressedData;
}
else
{
this.Data = reader.ReadBytes((int)size);
Trace.Assert(this.Data.Length == size);
}
}
private byte[] ZlibDecompress(Stream compressedStream, uint originalSize)
{
using (MemoryStream msDecompressed = new MemoryStream((int)originalSize))
{
//DeflateStream closes the underlying stream when disposed
using (var defStream = new DeflateStream(compressedStream, CompressionMode.Decompress, LeaveOpen))
{
defStream.CopyTo(msDecompressed);
}
return msDecompressed.ToArray();
}
}
}
}