-
Notifications
You must be signed in to change notification settings - Fork 125
Expand file tree
/
Copy pathAssetBundleFile.cs
More file actions
922 lines (796 loc) · 36.4 KB
/
AssetBundleFile.cs
File metadata and controls
922 lines (796 loc) · 36.4 KB
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
using AssetsTools.NET.Extra;
using AssetsTools.NET.Extra.Decompressors.LZ4;
using LZ4ps;
using SevenZip.Compression.LZMA;
using System;
using System.Collections.Generic;
using System.IO;
#if !NET35
using System.Threading.Tasks;
#endif
namespace AssetsTools.NET
{
public class AssetBundleFile
{
/// <summary>
/// Bundle header. Contains bundle engine version.
/// </summary>
public AssetBundleHeader Header { get; set; }
/// <summary>
/// List of compression blocks and file info (file names, address in file, etc.)
/// </summary>
public AssetBundleBlockAndDirInfo BlockAndDirInfo { get; set; }
/// <summary>
/// Reader for data block of bundle
/// </summary>
public AssetsFileReader DataReader { get; set; }
/// <summary>
/// Is data reader reading compressed data? Only LZMA bundles set this to true.
/// </summary>
public bool DataIsCompressed { get; set; }
private static int _lz4ParallelPackBatchSize = 32;
/// <summary>
/// Number of 0x20000 blocks processed per parallel batch in LZ4/LZ4Fast Pack/Unpack.
/// Used on non-NET35 targets only. Values less than 1 are treated as 1.
/// </summary>
public static int Lz4ParallelPackBatchSize
{
get => _lz4ParallelPackBatchSize;
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(nameof(value), "Lz4ParallelPackBatchSize must be greater than 0.");
}
_lz4ParallelPackBatchSize = value;
}
}
public AssetsFileReader Reader;
/// <summary>
/// Closes the reader.
/// </summary>
public void Close()
{
Reader.Close();
DataReader.Close();
}
/// <summary>
/// Read the <see cref="AssetBundleFile"/> with the provided reader.
/// </summary>
/// <param name="reader">The reader to use.</param>
public void Read(AssetsFileReader reader)
{
Reader = reader;
Reader.Position = 0;
Reader.BigEndian = true;
string magic = reader.ReadNullTerminated(); // skipped and read by header
uint version = reader.ReadUInt32();
if (version >= 6 || version <= 8)
{
Reader.Position = 0;
Header = new AssetBundleHeader();
Header.Read(reader);
if (Header.Version >= 7)
{
reader.Align16();
}
if (Header.Signature == "UnityFS")
{
UnpackInfoOnly();
}
else
{
new NotImplementedException("Non UnityFS bundles are not supported yet.");
}
}
else
{
new NotImplementedException($"Version {version} bundles are not supported yet.");
}
}
/// <summary>
/// Write the <see cref="AssetBundleFile"/> with the provided writer.
/// </summary>
/// <param name="writer">The writer to use.</param>
/// <param name="filePos">Where in the stream to start writing. Use -1 to start writing at the current stream position.</param>
public void Write(AssetsFileWriter writer, long filePos = 0)
{
if (Header == null)
throw new Exception("Header must be loaded! (Did you forget to call bundle.Read?)");
if (Header.Signature != "UnityFS")
throw new NotImplementedException("Non UnityFS bundles are not supported yet.");
if (DataIsCompressed)
throw new Exception("Bundles must be decompressed before writing.");
long writeStart = filePos;
if (filePos == -1)
writeStart = writer.Position;
else
writer.Position = filePos;
List<AssetBundleDirectoryInfo> directoryInfos = BlockAndDirInfo.DirectoryInfos;
Header.Write(writer);
if (Header.Version >= 7)
{
writer.Align16();
}
long blockDataLength = 0;
int blockDataCount = 1;
foreach (AssetBundleDirectoryInfo dirInfo in directoryInfos)
{
if (dirInfo.Replacer != null)
{
blockDataLength += dirInfo.Replacer.GetSize();
}
else
{
blockDataLength += dirInfo.DecompressedSize;
}
while (blockDataLength >= uint.MaxValue)
{
blockDataLength -= uint.MaxValue;
blockDataCount++;
}
}
AssetBundleBlockAndDirInfo newBundleInf = new AssetBundleBlockAndDirInfo()
{
Hash = new Hash128(),
BlockInfos = new AssetBundleBlockInfo[blockDataCount]
};
for (int i = 0; i < blockDataCount; i++)
{
newBundleInf.BlockInfos[i] = new AssetBundleBlockInfo
{
CompressedSize = 0,
DecompressedSize = 0,
Flags = 0x40
};
}
List<AssetBundleDirectoryInfo> dirInfos = new List<AssetBundleDirectoryInfo>();
// write all original file infos and skip those to be removed
int dirCount = directoryInfos.Count;
for (int i = 0; i < dirCount; i++)
{
AssetBundleDirectoryInfo dirInfo = directoryInfos[i];
ContentReplacerType replacerType = dirInfo.ReplacerType;
if (replacerType == ContentReplacerType.Remove)
continue;
dirInfos.Add(new AssetBundleDirectoryInfo()
{
// offset and size to be edited later
Offset = dirInfo.Offset,
DecompressedSize = dirInfo.DecompressedSize,
Flags = dirInfo.Flags,
Name = dirInfo.Name,
Replacer = dirInfo.Replacer,
});
}
// write the listings
long bundleInfPos = writer.Position;
// this is only here to allocate enough space so it's fine if it's inaccurate
newBundleInf.DirectoryInfos = dirInfos;
newBundleInf.Write(writer);
if ((Header.FileStreamHeader.Flags & AssetBundleFSHeaderFlags.BlockInfoNeedPaddingAtStart) != 0)
{
writer.Align16();
}
long assetDataPos = writer.Position;
// write the updated directory infos
for (int i = 0; i < dirInfos.Count; i++)
{
AssetBundleDirectoryInfo dirInfo = dirInfos[i];
long startPosition = writer.Position;
long newOffset = startPosition - assetDataPos;
ContentReplacerType replacerType = dirInfo.ReplacerType;
if (replacerType == ContentReplacerType.AddOrModify)
{
dirInfo.Replacer.Write(writer, true);
}
else
{
DataReader.Position = dirInfo.Offset;
DataReader.BaseStream.CopyToCompat(writer.BaseStream, dirInfo.DecompressedSize);
}
dirInfo.Offset = newOffset;
dirInfo.DecompressedSize = writer.Position - startPosition;
}
// now that we know what the sizes are of the written files, let's go back and fix them
long finalSize = writer.Position;
long assetSize = finalSize - assetDataPos;
// is it okay to have blocks of zero size in case we overshoot?
long remainingAssetSize = assetSize;
for (int i = 0; i < newBundleInf.BlockInfos.Length; i++)
{
AssetBundleBlockInfo blockInfo = newBundleInf.BlockInfos[i];
uint take = (uint)Math.Min(remainingAssetSize, uint.MaxValue);
blockInfo.DecompressedSize = take;
blockInfo.CompressedSize = take;
remainingAssetSize -= take;
}
newBundleInf.DirectoryInfos = dirInfos;
writer.Position = bundleInfPos;
newBundleInf.Write(writer);
uint infoSize = (uint)(assetDataPos - bundleInfPos);
writer.Position = writeStart;
AssetBundleHeader newBundleHeader = new AssetBundleHeader
{
Signature = Header.Signature,
Version = Header.Version,
GenerationVersion = Header.GenerationVersion,
EngineVersion = Header.EngineVersion,
FileStreamHeader = new AssetBundleFSHeader
{
TotalFileSize = finalSize,
CompressedSize = infoSize,
DecompressedSize = infoSize,
// unset "info at end" flag and compression value
Flags = Header.FileStreamHeader.Flags & ~AssetBundleFSHeaderFlags.BlockAndDirAtEnd & ~AssetBundleFSHeaderFlags.CompressionMask
}
};
newBundleHeader.Write(writer);
}
/// <summary>
/// Unpack and write the uncompressed <see cref="AssetBundleFile"/> with the provided writer. <br/>
/// You must write to a new file or stream when calling this method.
/// </summary>
/// <param name="writer">The writer to use.</param>
public void Unpack(AssetsFileWriter writer)
{
if (Header == null)
new Exception("Header must be loaded! (Did you forget to call bundle.Read?)");
if (Header.Signature != "UnityFS")
new NotImplementedException("Non UnityFS bundles are not supported yet.");
AssetBundleFSHeader fsHeader = Header.FileStreamHeader;
AssetsFileReader reader = DataReader;
AssetBundleBlockInfo[] blockInfos = BlockAndDirInfo.BlockInfos;
List<AssetBundleDirectoryInfo> directoryInfos = BlockAndDirInfo.DirectoryInfos;
AssetBundleHeader newBundleHeader = new AssetBundleHeader()
{
Signature = Header.Signature,
Version = Header.Version,
GenerationVersion = Header.GenerationVersion,
EngineVersion = Header.EngineVersion,
FileStreamHeader = new AssetBundleFSHeader
{
TotalFileSize = 0,
CompressedSize = fsHeader.DecompressedSize,
DecompressedSize = fsHeader.DecompressedSize,
Flags = AssetBundleFSHeaderFlags.HasDirectoryInfo |
(
(fsHeader.Flags & AssetBundleFSHeaderFlags.BlockInfoNeedPaddingAtStart) != AssetBundleFSHeaderFlags.None ?
AssetBundleFSHeaderFlags.BlockInfoNeedPaddingAtStart :
AssetBundleFSHeaderFlags.None
)
}
};
long fileSize = newBundleHeader.GetFileDataOffset();
for (int i = 0; i < blockInfos.Length; i++)
{
fileSize += blockInfos[i].DecompressedSize;
}
newBundleHeader.FileStreamHeader.TotalFileSize = fileSize;
AssetBundleBlockAndDirInfo newBundleInf = new AssetBundleBlockAndDirInfo()
{
Hash = new Hash128(),
BlockInfos = new AssetBundleBlockInfo[blockInfos.Length],
DirectoryInfos = new List<AssetBundleDirectoryInfo>(directoryInfos.Count)
};
// todo: we should just use one block here
for (int i = 0; i < blockInfos.Length; i++)
{
newBundleInf.BlockInfos[i] = new AssetBundleBlockInfo()
{
CompressedSize = blockInfos[i].DecompressedSize,
DecompressedSize = blockInfos[i].DecompressedSize,
// Set compression to none
Flags = (ushort)(blockInfos[i].Flags & (~0x3f))
};
}
for (int i = 0; i < directoryInfos.Count; i++)
{
newBundleInf.DirectoryInfos.Add(new AssetBundleDirectoryInfo()
{
Offset = directoryInfos[i].Offset,
DecompressedSize = directoryInfos[i].DecompressedSize,
Flags = directoryInfos[i].Flags,
Name = directoryInfos[i].Name
});
}
newBundleHeader.Write(writer);
if (newBundleHeader.Version >= 7)
{
writer.Align16();
}
newBundleInf.Write(writer);
if ((newBundleHeader.FileStreamHeader.Flags & AssetBundleFSHeaderFlags.BlockInfoNeedPaddingAtStart) != 0)
{
writer.Align16();
}
reader.Position = 0;
if (DataIsCompressed)
{
for (int i = 0; i < newBundleInf.BlockInfos.Length; i++)
{
AssetBundleBlockInfo info = blockInfos[i];
switch (info.GetCompressionType())
{
case 0:
{
reader.BaseStream.CopyToCompat(writer.BaseStream, info.CompressedSize);
break;
}
case 1:
{
SevenZipHelper.StreamDecompress(reader.BaseStream, writer.BaseStream, info.CompressedSize, info.DecompressedSize);
break;
}
case 2:
case 3:
{
using (MemoryStream tempMs = new MemoryStream())
{
reader.BaseStream.CopyToCompat(tempMs, info.CompressedSize);
tempMs.Position = 0;
using (Lz4DecoderStream decoder = new Lz4DecoderStream(tempMs))
{
decoder.CopyToCompat(writer.BaseStream, info.DecompressedSize);
}
}
break;
}
}
}
}
else
{
for (int i = 0; i < newBundleInf.BlockInfos.Length; i++)
{
AssetBundleBlockInfo info = blockInfos[i];
reader.BaseStream.CopyToCompat(writer.BaseStream, info.DecompressedSize);
}
}
}
/// <summary>
/// Pack and write the compressed <see cref="AssetBundleFile"/> with the provided writer. <br/>
/// You must write to a new file or stream when calling this method.
/// </summary>
/// <param name="writer">The writer to use.</param>
/// <param name="compType">The compression type to use. LZ4 compresses worse but faster, LZMA compresses better but slower.</param>
/// <param name="blockDirAtEnd">Put block and directory list at end? This skips creating temporary files, but is not officially used.</param>
/// <param name="progress">Optional callback for compression progress.</param>
public void Pack(AssetsFileWriter writer, AssetBundleCompressionType compType,
bool blockDirAtEnd = true, IAssetBundleCompressProgress progress = null)
{
if (Header == null)
throw new Exception("Header must be loaded! (Did you forget to call bundle.Read?)");
if (Header.Signature != "UnityFS")
throw new NotImplementedException("Non UnityFS bundles are not supported yet.");
if (DataIsCompressed)
throw new Exception("Bundles must be decompressed before writing.");
Reader.Position = 0;
writer.Position = 0;
AssetBundleFSHeader newFsHeader = new AssetBundleFSHeader
{
TotalFileSize = 0,
CompressedSize = 0,
DecompressedSize = 0,
Flags = AssetBundleFSHeaderFlags.LZ4HCCompressed | AssetBundleFSHeaderFlags.HasDirectoryInfo |
(blockDirAtEnd ? AssetBundleFSHeaderFlags.BlockAndDirAtEnd : AssetBundleFSHeaderFlags.None)
};
AssetBundleHeader newHeader = new AssetBundleHeader()
{
Signature = Header.Signature,
Version = Header.Version,
GenerationVersion = Header.GenerationVersion,
EngineVersion = Header.EngineVersion,
FileStreamHeader = newFsHeader
};
AssetBundleBlockAndDirInfo newBlockAndDirList = new AssetBundleBlockAndDirInfo()
{
Hash = new Hash128(),
BlockInfos = null,
DirectoryInfos = BlockAndDirInfo.DirectoryInfos
};
// write header now and overwrite it later
long startPos = writer.Position;
newHeader.Write(writer);
if (newHeader.Version >= 7)
writer.Align16();
int headerSize = (int)(writer.Position - startPos);
long totalCompressedSize = 0;
List<AssetBundleBlockInfo> newBlocks = new List<AssetBundleBlockInfo>();
List<Stream> newStreams = new List<Stream>(); // used if blockDirAtEnd == false
Stream bundleDataStream = DataReader.BaseStream;
bundleDataStream.Position = 0;
int fileDataLength = (int)bundleDataStream.Length;
switch (compType)
{
case AssetBundleCompressionType.LZMA:
{
// write to one large lzma block
Stream writeStream;
if (blockDirAtEnd)
writeStream = writer.BaseStream;
else
writeStream = GetTempFileStream();
var lzmaProgress = new AssetBundleLZMAProgress(progress, bundleDataStream.Length);
long writeStreamStart = writeStream.Position;
SevenZipHelper.Compress(bundleDataStream, writeStream, lzmaProgress);
uint writeStreamLength = (uint)(writeStream.Position - writeStreamStart);
AssetBundleBlockInfo blockInfo = new AssetBundleBlockInfo()
{
CompressedSize = writeStreamLength,
DecompressedSize = (uint)fileDataLength,
Flags = 0x41
};
totalCompressedSize += blockInfo.CompressedSize;
newBlocks.Add(blockInfo);
if (!blockDirAtEnd)
newStreams.Add(writeStream);
if (progress != null)
{
progress.SetProgress(1.0f);
}
break;
}
case AssetBundleCompressionType.LZ4:
case AssetBundleCompressionType.LZ4Fast:
{
// compress into 0x20000 blocks
const int blockSize = 0x20000;
BinaryReader bundleDataReader = new BinaryReader(bundleDataStream);
Stream writeStream;
if (blockDirAtEnd)
writeStream = writer.BaseStream;
else
writeStream = GetTempFileStream();
#if !NET35
int totalBlockCount = (int)((bundleDataReader.BaseStream.Length + blockSize - 1) / blockSize);
int completedBlockCount = 0;
while (true)
{
List<byte[]> uncompressedBlocks = new List<byte[]>(_lz4ParallelPackBatchSize);
for (int i = 0; i < _lz4ParallelPackBatchSize; i++)
{
byte[] block = bundleDataReader.ReadBytes(blockSize);
if (block.Length == 0)
break;
uncompressedBlocks.Add(block);
}
if (uncompressedBlocks.Count == 0)
break;
// each outputBlock is a byte[]
byte[][] outputBlocks = new byte[uncompressedBlocks.Count][];
AssetBundleBlockInfo[] outputBlockInfos = new AssetBundleBlockInfo[uncompressedBlocks.Count];
Parallel.For(0, uncompressedBlocks.Count, i =>
{
byte[] uncompressedBlock = uncompressedBlocks[i];
byte[] compressedBlock = compType == AssetBundleCompressionType.LZ4Fast
? LZ4Codec.Encode32(uncompressedBlock, 0, uncompressedBlock.Length)
: LZ4Codec.Encode32HC(uncompressedBlock, 0, uncompressedBlock.Length);
if (compressedBlock.Length > uncompressedBlock.Length)
{
outputBlocks[i] = uncompressedBlock;
outputBlockInfos[i] = new AssetBundleBlockInfo()
{
CompressedSize = (uint)uncompressedBlock.Length,
DecompressedSize = (uint)uncompressedBlock.Length,
Flags = 0x00
};
}
else
{
outputBlocks[i] = compressedBlock;
outputBlockInfos[i] = new AssetBundleBlockInfo()
{
CompressedSize = (uint)compressedBlock.Length,
DecompressedSize = (uint)uncompressedBlock.Length,
Flags = 0x03
};
}
});
for (int i = 0; i < outputBlocks.Length; i++)
{
byte[] outputBlock = outputBlocks[i];
AssetBundleBlockInfo blockInfo = outputBlockInfos[i];
writeStream.Write(outputBlock, 0, outputBlock.Length);
totalCompressedSize += blockInfo.CompressedSize;
newBlocks.Add(blockInfo);
}
completedBlockCount += outputBlocks.Length;
if (progress != null && totalBlockCount > 0)
{
progress.SetProgress((float)completedBlockCount / totalBlockCount);
}
}
#else
byte[] uncompressedBlock = bundleDataReader.ReadBytes(blockSize);
while (uncompressedBlock.Length != 0)
{
byte[] compressedBlock = compType == AssetBundleCompressionType.LZ4Fast
? LZ4Codec.Encode32(uncompressedBlock, 0, uncompressedBlock.Length)
: LZ4Codec.Encode32HC(uncompressedBlock, 0, uncompressedBlock.Length);
if (progress != null)
{
progress.SetProgress((float)bundleDataReader.BaseStream.Position / bundleDataReader.BaseStream.Length);
}
if (compressedBlock.Length > uncompressedBlock.Length)
{
writeStream.Write(uncompressedBlock, 0, uncompressedBlock.Length);
AssetBundleBlockInfo blockInfo = new AssetBundleBlockInfo()
{
CompressedSize = (uint)uncompressedBlock.Length,
DecompressedSize = (uint)uncompressedBlock.Length,
Flags = 0x00
};
totalCompressedSize += blockInfo.CompressedSize;
newBlocks.Add(blockInfo);
}
else
{
writeStream.Write(compressedBlock, 0, compressedBlock.Length);
AssetBundleBlockInfo blockInfo = new AssetBundleBlockInfo()
{
CompressedSize = (uint)compressedBlock.Length,
DecompressedSize = (uint)uncompressedBlock.Length,
Flags = 0x03
};
totalCompressedSize += blockInfo.CompressedSize;
newBlocks.Add(blockInfo);
}
uncompressedBlock = bundleDataReader.ReadBytes(blockSize);
}
#endif
if (!blockDirAtEnd)
newStreams.Add(writeStream);
if (progress != null)
{
progress.SetProgress(1.0f);
}
break;
}
case AssetBundleCompressionType.None:
{
AssetBundleBlockInfo blockInfo = new AssetBundleBlockInfo()
{
CompressedSize = (uint)fileDataLength,
DecompressedSize = (uint)fileDataLength,
Flags = 0x00
};
totalCompressedSize += blockInfo.CompressedSize;
newBlocks.Add(blockInfo);
if (blockDirAtEnd)
bundleDataStream.CopyToCompat(writer.BaseStream);
else
newStreams.Add(bundleDataStream);
break;
}
}
newBlockAndDirList.BlockInfos = newBlocks.ToArray();
byte[] bundleInfoBytes;
using (MemoryStream memStream = new MemoryStream())
{
AssetsFileWriter infoWriter = new AssetsFileWriter(memStream);
infoWriter.BigEndian = writer.BigEndian;
newBlockAndDirList.Write(infoWriter);
bundleInfoBytes = memStream.ToArray();
}
// listing is usually lz4 even if the data blocks are lzma
byte[] bundleInfoBytesCom = compType == AssetBundleCompressionType.LZ4Fast
? LZ4Codec.Encode32(bundleInfoBytes, 0, bundleInfoBytes.Length)
: LZ4Codec.Encode32HC(bundleInfoBytes, 0, bundleInfoBytes.Length);
long totalFileSize = headerSize + bundleInfoBytesCom.Length + totalCompressedSize;
newFsHeader.TotalFileSize = totalFileSize;
newFsHeader.DecompressedSize = (uint)bundleInfoBytes.Length;
newFsHeader.CompressedSize = (uint)bundleInfoBytesCom.Length;
if (!blockDirAtEnd)
{
writer.Write(bundleInfoBytesCom);
foreach (Stream newStream in newStreams)
{
newStream.Position = 0;
newStream.CopyToCompat(writer.BaseStream);
newStream.Close();
}
}
else
{
writer.Write(bundleInfoBytesCom);
}
writer.Position = 0;
newHeader.Write(writer);
if (newHeader.Version >= 7)
writer.Align16();
}
private void UnpackInfoOnly()
{
if (Header == null)
throw new Exception("Header must be loaded! (Did you forget to call bundle.Read?)");
MemoryStream blocksInfoStream;
AssetsFileReader memReader;
Reader.Position = Header.GetBundleInfoOffset();
if (Header.GetCompressionType() == 0)
{
BlockAndDirInfo = new AssetBundleBlockAndDirInfo();
BlockAndDirInfo.Read(Reader);
}
else
{
int compressedSize = (int)Header.FileStreamHeader.CompressedSize;
int decompressedSize = (int)Header.FileStreamHeader.DecompressedSize;
switch (Header.GetCompressionType())
{
case 1:
{
using (MemoryStream mstream = new MemoryStream(Reader.ReadBytes(compressedSize)))
{
blocksInfoStream = new MemoryStream();
SevenZipHelper.StreamDecompress(mstream, blocksInfoStream, compressedSize, decompressedSize);
}
break;
}
case 2:
case 3:
{
byte[] uncompressedBytes = new byte[Header.FileStreamHeader.DecompressedSize];
using (MemoryStream mstream = new MemoryStream(Reader.ReadBytes(compressedSize)))
{
var decoder = new Lz4DecoderStream(mstream);
decoder.Read(uncompressedBytes, 0, (int)Header.FileStreamHeader.DecompressedSize);
decoder.Dispose();
}
blocksInfoStream = new MemoryStream(uncompressedBytes);
break;
}
default:
{
blocksInfoStream = null;
break;
}
}
using (memReader = new AssetsFileReader(blocksInfoStream))
{
memReader.Position = 0;
memReader.BigEndian = Reader.BigEndian;
BlockAndDirInfo = new AssetBundleBlockAndDirInfo();
BlockAndDirInfo.Read(memReader);
}
}
// it hasn't been seen but it's possible we
// find mixed lz4 and lzma. if so, that's bad news.
switch (GetCompressionType())
{
case AssetBundleCompressionType.None:
{
SegmentStream dataStream = new SegmentStream(Reader.BaseStream, Header.GetFileDataOffset());
DataReader = new AssetsFileReader(dataStream);
DataIsCompressed = false;
break;
}
case AssetBundleCompressionType.LZMA:
{
SegmentStream dataStream = new SegmentStream(Reader.BaseStream, Header.GetFileDataOffset());
DataReader = new AssetsFileReader(dataStream);
DataIsCompressed = true;
break;
}
case AssetBundleCompressionType.LZ4:
{
LZ4BlockStream dataStream = new LZ4BlockStream(Reader.BaseStream, Header.GetFileDataOffset(), BlockAndDirInfo.BlockInfos);
DataReader = new AssetsFileReader(dataStream);
DataIsCompressed = false;
break;
}
}
}
/// <summary>
/// Returns the main compression type the bundle uses (the first uncompressed block type).
/// </summary>
/// <returns>The compression type</returns>
public AssetBundleCompressionType GetCompressionType()
{
AssetBundleBlockInfo[] blockInfos = BlockAndDirInfo.BlockInfos;
for (int i = 0; i < blockInfos.Length; i++)
{
byte compType = blockInfos[i].GetCompressionType();
if (compType == 2 || compType == 3)
{
return AssetBundleCompressionType.LZ4;
}
else if (compType == 1)
{
return AssetBundleCompressionType.LZMA;
}
}
return AssetBundleCompressionType.None;
}
/// <summary>
/// Is the file at the index an <see cref="AssetsFile"/>?
/// Note: this checks by reading the first bit of the file instead of reading the directory flag.
/// </summary>
/// <param name="index">Index of the file in the directory info list.</param>
/// <returns>True if the file at the index is an <see cref="AssetsFile"/>.</returns>
public bool IsAssetsFile(int index)
{
GetFileRange(index, out long offset, out long length);
return AssetsFile.IsAssetsFile(DataReader, offset, length);
}
/// <summary>
/// Returns the index of the file in the directory list with the given name.
/// </summary>
/// <param name="name">The name to search for.</param>
/// <returns>The index of the file in the directory list or -1 if no file is found.</returns>
public int GetFileIndex(string name)
{
if (Header == null)
throw new Exception("Header must be loaded! (Did you forget to call bundle.Read?)");
for (int i = 0; i < BlockAndDirInfo.DirectoryInfos.Count; i++)
{
if (BlockAndDirInfo.DirectoryInfos[i].Name == name)
return i;
}
return -1;
}
/// <summary>
/// Returns the name of the file at the index in the directory list.
/// </summary>
/// <param name="index">The index to look at.</param>
/// <returns>The name of the file in the directory list or null if the index is out of bounds.</returns>
public string GetFileName(int index)
{
if (Header == null)
throw new Exception("Header must be loaded! (Did you forget to call bundle.Read?)");
if (index < 0 || index >= BlockAndDirInfo.DirectoryInfos.Count)
return null;
return BlockAndDirInfo.DirectoryInfos[index].Name;
}
/// <summary>
/// Returns the file range of a file.
/// Use <see cref="DataReader"/> instead of <see cref="Reader"/> to read data.
/// </summary>
/// <param name="index">The index to look at.</param>
/// <param name="offset">The offset in the data stream, or -1 if the index is out of bounds.</param>
/// <param name="length">The length of the file, or 0 if the index is out of bounds.</param>
public void GetFileRange(int index, out long offset, out long length)
{
if (Header == null)
throw new Exception("Header must be loaded! (Did you forget to call bundle.Read?)");
if (index < 0 || index >= BlockAndDirInfo.DirectoryInfos.Count)
{
offset = -1;
length = 0;
return;
}
AssetBundleDirectoryInfo entry = BlockAndDirInfo.DirectoryInfos[index];
offset = entry.Offset;
length = entry.DecompressedSize;
}
/// <summary>
/// Returns a list of file names in the bundle.
/// </summary>
/// <returns>The file names in the bundle.</returns>
public List<string> GetAllFileNames()
{
if (Header == null)
throw new Exception("Header must be loaded! (Did you forget to call bundle.Read?)");
List<string> names = new List<string>();
List<AssetBundleDirectoryInfo> dirInfos = BlockAndDirInfo.DirectoryInfos;
foreach (AssetBundleDirectoryInfo dirInfo in dirInfos)
{
names.Add(dirInfo.Name);
}
return names;
}
private FileStream GetTempFileStream()
{
string tempFilePath = Path.GetTempFileName();
FileStream tempFileStream = new FileStream(tempFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read, 4096, FileOptions.DeleteOnClose);
return tempFileStream;
}
}
public enum AssetBundleCompressionType
{
None,
LZMA,
LZ4,
LZ4Fast
}
}