diff --git a/Archive/ArchiveRepacker.cs b/Archive/ArchiveRepacker.cs new file mode 100644 index 0000000..0d5dc81 --- /dev/null +++ b/Archive/ArchiveRepacker.cs @@ -0,0 +1,645 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Security.Cryptography; +using K4os.Compression.LZ4; +using UnityDataTools.BinaryFormat; +using UnityDataTools.FileSystem; + +namespace UnityDataTools.Archive; + +public enum RepackCompression +{ + None, + Lz4, + Lz4HC, +} + +/// +/// Settings for how the repacked archive splits its content into blocks. +/// +public class RepackOptions +{ + public const int DefaultBlockSize = 128 * 1024; + public const int MinBlockSize = 1024; + public const int MaxBlockSize = 64 * 1024 * 1024; + + public RepackCompression Compression { get; set; } = RepackCompression.Lz4HC; + + /// Largest amount of uncompressed data in one block. Unity always uses 128 KB. + public int BlockSize { get; set; } = DefaultBlockSize; + + /// + /// Largest size a block may take in the file, after compression. When a full block would compress + /// to more than this, the block is made shorter. Null means no limit. + /// + public int? MaxCompressedBlockSize { get; set; } + + /// + /// Start a new block at the start of every file, so that no block holds data from two files. + /// Unity lets blocks span file boundaries. + /// + public bool SplitAtFileBoundaries { get; set; } + + /// + /// Alignment of the start of each file within the uncompressed data. The gap is filled with zeros. + /// 1 means files are packed back to back. + /// + public int FileAlignment { get; set; } = 1; + + /// + /// Alignment of each block's position within the data section, as the Unity 6.7 writer does with + /// 16 bytes. Only possible from archive format version 9, where each block records its own offset. + /// 1 means blocks are stored back to back. + /// + public int BlockAlignment { get; set; } = 1; + + /// + /// A block is only stored compressed if uncompressed size / compressed size reaches this ratio; + /// otherwise it is stored uncompressed, which saves the decompression work for data that is + /// already compressed (for example textures in a compressed GPU format, or audio). + /// + public double MinCompressionRatio { get; set; } = 1.0; + + /// + /// Returns an error message for the first invalid setting, or null when all of them are valid. + /// + public string Validate() + { + if (BlockSize < MinBlockSize || BlockSize > MaxBlockSize) + return $"Block size must be between {MinBlockSize:N0} and {MaxBlockSize:N0} bytes."; + if (MaxCompressedBlockSize.HasValue && (MaxCompressedBlockSize.Value < MinBlockSize || MaxCompressedBlockSize.Value > MaxBlockSize)) + return $"Max compressed block size must be between {MinBlockSize:N0} and {MaxBlockSize:N0} bytes."; + if (FileAlignment < 1 || FileAlignment > MaxBlockSize || (FileAlignment & (FileAlignment - 1)) != 0) + return "File alignment must be a power of two (1 for no alignment)."; + if (BlockAlignment < 1 || BlockAlignment > MaxBlockSize || (BlockAlignment & (BlockAlignment - 1)) != 0) + return "Block alignment must be a power of two (1 for no alignment)."; + if (double.IsNaN(MinCompressionRatio) || MinCompressionRatio < 1.0) + return "Minimum compression ratio must be 1.0 or more."; + return null; + } +} + +/// +/// Layout statistics of an archive, computed from its header and metadata. They describe the +/// trade-off a block layout makes between file size and the cost of reading the content. +/// +public class ArchiveLayoutStats +{ + public long FileSize { get; set; } + public string Compression { get; set; } + public int BlockCount { get; set; } + + /// Blocks stored without compression (in an archive that otherwise uses compression). + public int UncompressedBlockCount { get; set; } + public long LargestBlockSize { get; set; } + public long DataSize { get; set; } + public long UncompressedDataSize { get; set; } + + /// + /// Uncompressed size of the blocks that must be read (and decompressed) to load every file once, + /// on its own, divided by the total size of the files. 1.0 means no block is shared between files; + /// a single LZMA block holding several files is far above 1. + /// + public double ReadAmplification { get; set; } +} + +public class RepackResult +{ + public ArchiveLayoutStats Original { get; set; } + public ArchiveLayoutStats Repacked { get; set; } + public int FileCount { get; set; } + public bool Verified { get; set; } +} + +/// +/// Rewrites an existing Unity Archive (for example an AssetBundle) into a new archive with the same +/// files, compressed with a configurable LZ4/LZ4HC block layout. +/// +/// Unity writes chunk-based archives with fixed 128 KB blocks that span file boundaries. The format +/// itself records the size and compression of every block, so other layouts load as well; this lets +/// a team measure what a different layout does to download size, patch size and random-access cost +/// on their target platform. The file content is read through UnityFileSystemApi, so any archive it +/// can mount (including LZMA ones) can be repacked. +/// +public static class ArchiveRepacker +{ + const string SourceMountPoint = "repack:/"; + + public static RepackResult Repack(string inputPath, string outputPath, RepackOptions options, bool verify = true) + { + var error = options.Validate(); + if (error != null) + throw new ArgumentException(error); + + if (string.Equals(Path.GetFullPath(inputPath), Path.GetFullPath(outputPath), StringComparison.Ordinal)) + throw new ArgumentException("The output path must be different from the input archive."); + + var header = ReadHeader(inputPath); + var metadata = ReadMetadata(inputPath, header); + + const uint knownFlags = ArchiveFlags.BlocksAndDirectoryInfoCombined | ArchiveFlags.BlocksInfoAtTheEnd + | ArchiveFlags.OldWebPluginCompatibility | ArchiveFlags.BlockInfoNeedPaddingAtStart; + if ((header.ArchiveFlagBits & ~knownFlags) != 0) + throw new NotSupportedException($"The archive uses unknown header flags (0x{header.ArchiveFlagBits & ~knownFlags:X}), so it cannot be repacked safely."); + + var sourceNodes = metadata.DirectoryInfo.Nodes; + var outputNodes = LayOutNodes(sourceNodes, options.FileAlignment); + + var writeBlockOffsets = header.HasStorageBlockOffsets; + if (options.BlockAlignment > 1 && !writeBlockOffsets) + throw new NotSupportedException($"Block alignment needs archive format version 9 or later (Unity 6.7), where blocks record their own offsets. This archive is version {header.Version}."); + var tempDataPath = outputPath + ".data.tmp"; + List blocks; + + try + { + using (var dataStream = new FileStream(tempDataPath, FileMode.Create, FileAccess.Write)) + { + blocks = new List(); + if (sourceNodes.Length > 0) + { + using var archive = UnityFileSystem.MountArchive(Path.GetFullPath(inputPath), SourceMountPoint); + var mountedNodes = archive.Nodes; + if (mountedNodes.Count != sourceNodes.Length) + throw new InvalidDataException("The archive directory and the mounted archive disagree on the number of files."); + + using var source = new ArchiveContentReader(mountedNodes, outputNodes); + blocks = WriteBlocks(source, outputNodes, options, dataStream); + } + } + + WriteArchive(outputPath, header, blocks, outputNodes, writeBlockOffsets, tempDataPath); + } + finally + { + if (File.Exists(tempDataPath)) + File.Delete(tempDataPath); + } + + var result = new RepackResult + { + Original = ComputeStats(inputPath), + Repacked = ComputeStats(outputPath), + FileCount = sourceNodes.Length, + }; + + if (verify) + { + try + { + VerifySameContent(inputPath, outputPath); + } + catch + { + // Do not leave an archive behind that does not match its source. + File.Delete(outputPath); + throw; + } + result.Verified = true; + } + + return result; + } + + /// + /// Reads both archives through UnityFileSystemApi and checks that they hold the same files, with + /// the same flags and byte-for-byte identical content. Throws InvalidDataException on a mismatch. + /// + public static void VerifySameContent(string originalPath, string repackedPath) + { + // The archives are mounted one after the other rather than side by side. With both mounted + // (under different mount points, holding files with the same names), reading the repacked + // archive's files returned the original's content, so a tampered archive passed the check. + var original = HashArchiveContent(originalPath); + var repacked = HashArchiveContent(repackedPath); + + if (original.Count != repacked.Count) + throw new InvalidDataException($"The repacked archive has {repacked.Count} files, the original has {original.Count}."); + + for (int i = 0; i < original.Count; i++) + { + var a = original[i]; + var b = repacked[i]; + if (a.Node.Path != b.Node.Path || a.Node.Size != b.Node.Size || a.Node.Flags != b.Node.Flags) + throw new InvalidDataException($"File {i} differs: \"{a.Node.Path}\" ({a.Node.Size} bytes, {a.Node.Flags}) vs \"{b.Node.Path}\" ({b.Node.Size} bytes, {b.Node.Flags})."); + if (!a.Hash.AsSpan().SequenceEqual(b.Hash)) + throw new InvalidDataException($"The content of \"{a.Node.Path}\" differs from the original."); + } + } + + static List<(ArchiveNode Node, byte[] Hash)> HashArchiveContent(string path) + { + var result = new List<(ArchiveNode, byte[])>(); + + // UnityArchive.Nodes cannot represent an archive without files. + if (ReadMetadata(path, ReadHeader(path)).DirectoryInfo.Nodes.Length == 0) + return result; + + using var archive = UnityFileSystem.MountArchive(Path.GetFullPath(path), SourceMountPoint); + const int chunkSize = 256 * 1024; + var buffer = new byte[chunkSize]; + + foreach (var node in archive.Nodes) + { + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using var file = UnityFileSystem.OpenFile(SourceMountPoint + node.Path); + long remaining = node.Size; + while (remaining > 0) + { + long size = Math.Min(chunkSize, remaining); + long read = file.Read(size, buffer); + if (read != size) + throw new InvalidDataException($"Could not read \"{node.Path}\" from {path}."); + hash.AppendData(buffer, 0, (int)size); + remaining -= size; + } + result.Add((node, hash.GetHashAndReset())); + } + + return result; + } + + public static ArchiveLayoutStats ComputeStats(string path) + { + var header = ReadHeader(path); + var metadata = ReadMetadata(path, header); + var blocks = metadata.BlocksInfo.Blocks; + var nodes = metadata.DirectoryInfo.Nodes; + + var stats = new ArchiveLayoutStats + { + FileSize = (long)header.Size, + BlockCount = blocks.Length, + Compression = "None", + }; + + bool anyCompressed = false; + foreach (var block in blocks) + { + stats.DataSize += block.CompressedSize; + stats.UncompressedDataSize += block.UncompressedSize; + stats.LargestBlockSize = Math.Max(stats.LargestBlockSize, block.UncompressedSize); + if (block.CompressionType != 0 && !anyCompressed) + { + anyCompressed = true; + stats.Compression = FormatCompression(block.CompressionType); + } + } + + if (anyCompressed) + { + foreach (var block in blocks) + { + if (block.CompressionType == 0) + stats.UncompressedBlockCount++; + } + } + + // For every file, add up the blocks that overlap it. Blocks are sorted by DataOffset, so a + // binary search finds the first one. + long fileBytes = 0; + long decompressedBytes = 0; + foreach (var node in nodes) + { + if (node.Size == 0) + continue; + long start = (long)node.DataOffset; + long end = start + (long)node.Size; + fileBytes += (long)node.Size; + + int i = FindBlock(blocks, start); + for (; i < blocks.Length && blocks[i].DataOffset < end; i++) + decompressedBytes += blocks[i].UncompressedSize; + } + stats.ReadAmplification = fileBytes > 0 ? (double)decompressedBytes / fileBytes : 0; + + return stats; + } + + static int FindBlock(ArchiveStorageBlock[] blocks, long dataOffset) + { + int lo = 0, hi = blocks.Length - 1, found = 0; + while (lo <= hi) + { + int mid = (lo + hi) / 2; + if (blocks[mid].DataOffset <= dataOffset) + { + found = mid; + lo = mid + 1; + } + else + { + hi = mid - 1; + } + } + return found; + } + + static ArchiveHeaderInfo ReadHeader(string path) + { + if (!ArchiveDetector.TryReadArchiveHeader(path, out var header, out var error)) + throw new NotSupportedException(error); + return header; + } + + static ArchiveMetadata ReadMetadata(string path, ArchiveHeaderInfo header) + { + if (!ArchiveDetector.TryReadArchiveMetadata(path, header, out var metadata, out var error)) + throw new NotSupportedException(error); + return metadata; + } + + static ArchiveDirectoryNode[] LayOutNodes(ArchiveDirectoryNode[] sourceNodes, int alignment) + { + var nodes = new ArchiveDirectoryNode[sourceNodes.Length]; + ulong offset = 0; + for (int i = 0; i < sourceNodes.Length; i++) + { + offset = (offset + (ulong)alignment - 1) & ~((ulong)alignment - 1); + nodes[i] = new ArchiveDirectoryNode + { + DataOffset = offset, + Size = sourceNodes[i].Size, + Flags = sourceNodes[i].Flags, + Path = sourceNodes[i].Path, + }; + offset += sourceNodes[i].Size; + } + return nodes; + } + + // Splits the uncompressed data into blocks, compresses them and writes the stored bytes to + // dataStream back to back. Returns the block list for the metadata. + static List WriteBlocks(ArchiveContentReader source, ArchiveDirectoryNode[] nodes, RepackOptions options, Stream dataStream) + { + var blocks = new List(); + var encoder = new BlockEncoder(options); + var window = new byte[options.BlockSize]; + int windowCount = 0; + long position = 0; + + foreach (var (_, segmentEnd) in GetSegments(nodes, options.SplitAtFileBoundaries)) + { + while (position < segmentEnd) + { + int chunkLength = (int)Math.Min(options.BlockSize, segmentEnd - position); + while (windowCount < chunkLength) + { + int read = source.Read(window, windowCount, chunkLength - windowCount); + if (read == 0) + throw new InvalidDataException("The archive content ended earlier than its directory says."); + windowCount += read; + } + + var encoded = encoder.EncodeLargestFittingPrefix(window, chunkLength); + + long blockStart = (dataStream.Position + options.BlockAlignment - 1) & ~((long)options.BlockAlignment - 1); + ArchiveWriter.WritePadding(dataStream, blockStart - dataStream.Position); + dataStream.Write(encoded.Data, 0, encoded.StoredSize); + blocks.Add(new ArchiveStorageBlock + { + UncompressedSize = (uint)encoded.Length, + CompressedSize = (uint)encoded.StoredSize, + Flags = (ushort)encoded.CompressionType, + Offset = blockStart, + }); + + // Keep whatever the block did not take for the next block. + windowCount -= encoded.Length; + Buffer.BlockCopy(window, encoded.Length, window, 0, windowCount); + position += encoded.Length; + } + } + + return blocks; + } + + // The ranges of the uncompressed data that blocks must not cross. With spanning there is only one; + // with splitting each file starts a range, and alignment padding belongs to the file before it. + static IEnumerable<(long start, long end)> GetSegments(ArchiveDirectoryNode[] nodes, bool splitAtFileBoundaries) + { + if (nodes.Length == 0) + yield break; + + long totalSize = (long)(nodes[^1].DataOffset + nodes[^1].Size); + if (!splitAtFileBoundaries) + { + yield return (0, totalSize); + yield break; + } + + for (int i = 0; i < nodes.Length; i++) + { + long start = (long)nodes[i].DataOffset; + long end = i + 1 < nodes.Length ? (long)nodes[i + 1].DataOffset : totalSize; + if (end > start) + yield return (start, end); + } + } + + static void WriteArchive(string outputPath, ArchiveHeaderInfo sourceHeader, List blocks, + ArchiveDirectoryNode[] nodes, bool writeBlockOffsets, string dataPath) + { + var metadata = ArchiveWriter.SerializeMetadata(blocks, nodes, writeBlockOffsets); + + // Unity compresses the metadata with LZ4HC. Keep it uncompressed if that does not help. + var compressedMetadata = new byte[LZ4Codec.MaximumOutputSize(metadata.Length)]; + int compressedLength = LZ4Codec.Encode(metadata, 0, metadata.Length, compressedMetadata, 0, compressedMetadata.Length, LZ4Level.L09_HC); + uint metadataCompression = 3; + byte[] storedMetadata; + if (compressedLength > 0 && compressedLength < metadata.Length) + { + storedMetadata = compressedMetadata.AsSpan(0, compressedLength).ToArray(); + } + else + { + storedMetadata = metadata; + metadataCompression = 0; + } + + // The metadata is always written directly after the header. Keep the padding flag of the + // source, since it is what its Unity version writes. + uint flags = ArchiveFlags.BlocksAndDirectoryInfoCombined + | (sourceHeader.ArchiveFlagBits & ArchiveFlags.BlockInfoNeedPaddingAtStart) + | metadataCompression; + + long dataOffset = ArchiveWriter.GetDataOffset(sourceHeader.Version, sourceHeader.UnityVersion, (uint)storedMetadata.Length, flags); + long dataLength = new FileInfo(dataPath).Length; + ulong fileSize = (ulong)(dataOffset + dataLength); + + var header = ArchiveWriter.SerializeHeader(sourceHeader.Version, sourceHeader.UnityVersion, fileSize, + (uint)storedMetadata.Length, (uint)metadata.Length, flags); + + using var output = new FileStream(outputPath, FileMode.Create, FileAccess.Write); + output.Write(header); + output.Write(storedMetadata); + ArchiveWriter.WritePadding(output, dataOffset - output.Position); + using (var data = new FileStream(dataPath, FileMode.Open, FileAccess.Read)) + data.CopyTo(output); + } + + internal static string FormatCompression(int compressionType) + { + return compressionType switch + { + 0 => "None", + 1 => "Lzma", + 2 => "Lz4", + 3 => "Lz4HC", + _ => compressionType.ToString(), + }; + } + + struct EncodedBlock + { + public byte[] Data; + public int Length; + public int StoredSize; + public int CompressionType; + } + + // Compresses one block and applies the compression-ratio fallback and the compressed size limit. + class BlockEncoder + { + // When searching for a block length that fits MaxCompressedBlockSize, stop once the range is + // this small. It bounds the number of extra compressions per block to about log2(BlockSize / 1 KB). + const int SearchGranularity = 1024; + + readonly RepackOptions m_Options; + readonly byte[] m_Compressed; + + public BlockEncoder(RepackOptions options) + { + m_Options = options; + m_Compressed = new byte[LZ4Codec.MaximumOutputSize(options.BlockSize)]; + } + + public EncodedBlock EncodeLargestFittingPrefix(byte[] data, int length) + { + var full = Encode(data, length); + if (!m_Options.MaxCompressedBlockSize.HasValue || full.StoredSize <= m_Options.MaxCompressedBlockSize.Value) + return full; + + // A block stored uncompressed is never larger than its input, so a prefix as long as the + // limit always fits. Binary search for a longer prefix that still fits. + int limit = m_Options.MaxCompressedBlockSize.Value; + int lo = Math.Min(length, limit); + int hi = length; + while (hi - lo > SearchGranularity) + { + int mid = lo + (hi - lo) / 2; + if (Encode(data, mid).StoredSize <= limit) + lo = mid; + else + hi = mid; + } + return Encode(data, lo); + } + + EncodedBlock Encode(byte[] data, int length) + { + if (m_Options.Compression != RepackCompression.None) + { + var level = m_Options.Compression == RepackCompression.Lz4HC ? LZ4Level.L09_HC : LZ4Level.L00_FAST; + int compressedLength = LZ4Codec.Encode(data, 0, length, m_Compressed, 0, m_Compressed.Length, level); + if (compressedLength > 0 && compressedLength < length + && (double)length / compressedLength >= m_Options.MinCompressionRatio) + { + return new EncodedBlock + { + Data = m_Compressed, + Length = length, + StoredSize = compressedLength, + CompressionType = m_Options.Compression == RepackCompression.Lz4HC ? 3 : 2, + }; + } + } + + return new EncodedBlock { Data = data, Length = length, StoredSize = length, CompressionType = 0 }; + } + } + + // Reads the uncompressed data of the new archive in order: the content of each file, with zero + // padding wherever the new layout aligns the start of a file. + class ArchiveContentReader : IDisposable + { + readonly IReadOnlyList m_MountedNodes; + readonly ArchiveDirectoryNode[] m_Layout; + readonly byte[] m_ReadBuffer = new byte[256 * 1024]; + int m_NodeIndex = -1; + UnityFile m_CurrentFile; + long m_Position; + long m_RemainingInFile; + + public ArchiveContentReader(IReadOnlyList mountedNodes, ArchiveDirectoryNode[] layout) + { + m_MountedNodes = mountedNodes; + m_Layout = layout; + } + + public int Read(byte[] buffer, int offset, int count) + { + int total = 0; + while (count > 0 && m_NodeIndex < m_Layout.Length) + { + if (m_NodeIndex < 0 || (m_RemainingInFile == 0 && m_Position >= (long)m_Layout[m_NodeIndex].DataOffset)) + { + OpenNextFile(); + continue; + } + + // Padding before the current file. + long fileStart = (long)m_Layout[m_NodeIndex].DataOffset; + if (m_Position < fileStart) + { + int padding = (int)Math.Min(count, fileStart - m_Position); + Array.Clear(buffer, offset, padding); + offset += padding; + count -= padding; + total += padding; + m_Position += padding; + continue; + } + + int toRead = (int)Math.Min(Math.Min(count, m_RemainingInFile), m_ReadBuffer.Length); + long read = m_CurrentFile.Read(toRead, m_ReadBuffer); + if (read <= 0) + throw new InvalidDataException($"Could not read \"{m_MountedNodes[m_NodeIndex].Path}\" from the archive."); + Buffer.BlockCopy(m_ReadBuffer, 0, buffer, offset, (int)read); + offset += (int)read; + count -= (int)read; + total += (int)read; + m_Position += read; + m_RemainingInFile -= read; + } + return total; + } + + void OpenNextFile() + { + m_CurrentFile?.Dispose(); + m_CurrentFile = null; + m_RemainingInFile = 0; + + if (++m_NodeIndex >= m_Layout.Length) + return; + + var mounted = m_MountedNodes[m_NodeIndex]; + if ((ulong)mounted.Size != m_Layout[m_NodeIndex].Size) + throw new InvalidDataException($"The size of \"{mounted.Path}\" differs between the archive directory and the mounted archive."); + + // Empty files take no space in the data, so there is nothing to open. + if (mounted.Size > 0) + { + m_CurrentFile = UnityFileSystem.OpenFile(SourceMountPoint + mounted.Path); + m_RemainingInFile = mounted.Size; + } + } + + public void Dispose() + { + m_CurrentFile?.Dispose(); + } + } +} diff --git a/Archive/ArchiveTool.cs b/Archive/ArchiveTool.cs index 0766c1b..107f6c2 100644 --- a/Archive/ArchiveTool.cs +++ b/Archive/ArchiveTool.cs @@ -232,6 +232,104 @@ public static int PrintSummary(FileInfo filename, OutputFormat format) return 0; } + public static int Repack(FileInfo filename, FileInfo output, RepackOptions options, bool skipVerify, OutputFormat format) + { + var path = filename.ToString(); + + if (WebBundleHelper.IsWebBundle(path)) + { + Console.Error.WriteLine("Web bundle files (.data, .data.gz, .data.br) use a different format. The repack command is only supported for Unity Archive files."); + return 1; + } + + var optionsError = options.Validate(); + if (optionsError != null) + { + Console.Error.WriteLine(optionsError); + return 1; + } + + if (options.MaxCompressedBlockSize.HasValue && options.Compression == RepackCompression.None) + { + Console.Error.WriteLine("--max-compressed-block-size has no effect without compression."); + return 1; + } + + RepackResult result; + try + { + result = ArchiveRepacker.Repack(filename.FullName, output.FullName, options, verify: !skipVerify); + } + catch (Exception err) when ( + err is ArgumentException + || err is NotSupportedException + || err is InvalidDataException + || err is IOException + || err is UnauthorizedAccessException) + { + Console.Error.WriteLine($"Error repacking archive: {err.Message}"); + return 1; + } + + if (format == OutputFormat.Json) + OutputRepackJson(output, result); + else + OutputRepackText(filename, output, result); + + return 0; + } + + static void OutputRepackText(FileInfo input, FileInfo output, RepackResult result) + { + var a = result.Original; + var b = result.Repacked; + double change = a.FileSize > 0 ? 100.0 * (b.FileSize - a.FileSize) / a.FileSize : 0; + + Console.WriteLine($"Repacked {input.Name} into {output.FullName}"); + Console.WriteLine(); + Console.WriteLine($"{"",-30} {"Original",15} {"Repacked",15}"); + Console.WriteLine($"{"File Size",-30} {a.FileSize,15:N0} {b.FileSize,15:N0} ({change:+0.0;-0.0;0.0}%)"); + Console.WriteLine($"{"Compression",-30} {a.Compression,15} {b.Compression,15}"); + Console.WriteLine($"{"Block Count",-30} {a.BlockCount,15:N0} {b.BlockCount,15:N0}"); + Console.WriteLine($"{"Uncompressed Blocks",-30} {a.UncompressedBlockCount,15:N0} {b.UncompressedBlockCount,15:N0}"); + Console.WriteLine($"{"Largest Block",-30} {a.LargestBlockSize,15:N0} {b.LargestBlockSize,15:N0}"); + Console.WriteLine($"{"Read Amplification",-30} {a.ReadAmplification,14:F2}x {b.ReadAmplification,14:F2}x"); + Console.WriteLine(); + if (result.Verified) + Console.WriteLine($"Verified: all {result.FileCount} files match the original byte for byte."); + else + Console.WriteLine("Not verified (--skip-verify)."); + } + + static void OutputRepackJson(FileInfo output, RepackResult result) + { + var jsonObject = new + { + output = output.FullName, + fileCount = result.FileCount, + verified = result.Verified, + original = StatsToJson(result.Original), + repacked = StatsToJson(result.Repacked), + }; + var json = JsonSerializer.Serialize(jsonObject, new JsonSerializerOptions { WriteIndented = true }); + Console.WriteLine(json); + } + + static object StatsToJson(ArchiveLayoutStats stats) + { + return new + { + fileSize = stats.FileSize, + compression = stats.Compression, + blockCount = stats.BlockCount, + uncompressedBlockCount = stats.UncompressedBlockCount, + largestBlockSize = stats.LargestBlockSize, + dataSize = stats.DataSize, + uncompressedDataSize = stats.UncompressedDataSize, + readAmplification = Math.Round(stats.ReadAmplification, 3), + }; + } + static void OutputHeaderText(ArchiveHeaderInfo info) { Console.WriteLine($"{"Signature",-30} {info.Signature}"); diff --git a/Documentation/command-archive.md b/Documentation/command-archive.md index 8e6b9f5..8f664c6 100644 --- a/Documentation/command-archive.md +++ b/Documentation/command-archive.md @@ -13,6 +13,7 @@ To inspect the serialized objects *inside* an archive, use the [`dump`](command- | [`blocks`](#blocks) | Display the data block list | Yes | — | | [`list`](#list) | List contents of an archive | Yes | Yes | | [`extract`](#extract) | Extract contents of an archive | Yes | Yes | +| [`repack`](#repack) | Rewrite an archive with a different LZ4/LZ4HC block layout | Yes | — | --- @@ -153,6 +154,72 @@ contents/BuildPlayer-Scene2 --- +## repack + +Rewrites a Unity Archive into a new archive that contains the same files, compressed with a block layout you choose. The original file is not modified. + +Unity writes chunk-based (LZ4/LZ4HC) archives with blocks of up to 128 KB of uncompressed data, and there is no build option to change that. The archive format records the size and compression of every block, so other layouts can be read as well. `repack` makes it possible to measure what a different layout does to the download size, the patch size and the cost of reading the content, for example to tune it to a platform's storage. The input can use any compression that UnityDataTool can read, including LZMA; the output is uncompressed, LZ4 or LZ4HC (LZMA output is not supported). + +The output keeps the archive format version and Unity version of the input, and by default it is checked after writing: both archives are read back through UnityFileSystemApi and every file must match the original byte for byte. If the check fails, the output is deleted. + +### Quick Reference + +``` +UnityDataTool archive repack -o [options] +``` + +| Option | Description | Default | +|--------|-------------|---------| +| `` | Path to the archive file | *(required)* | +| `-o, --output-file ` | Path of the repacked archive. Must differ from the input | *(required)* | +| `-c, --compression ` | Block compression | `Lz4HC` | +| `--block-size ` | Largest uncompressed size of a block (1 KB to 64 MB) | `131072` | +| `--max-compressed-block-size ` | Largest stored size of a block. A block that would compress to more is made shorter | *(no limit)* | +| `--split-at-file-boundaries` | Start a new block for each file, so that no block holds data from two files | *(blocks span files)* | +| `--file-alignment ` | Align the start of each file in the uncompressed data to a power of two, padding with zeros | `1` | +| `--block-alignment ` | Align the position of each block in the file to a power of two. Needs archive format version 9 (Unity 6.7 and later), where blocks record their own position | `1` | +| `--min-compression-ratio ` | Store a block uncompressed unless uncompressed size / compressed size reaches this ratio | `1.0` | +| `--skip-verify` | Do not read the output back to compare it with the input | | +| `-f, --format ` | Output format of the report | `Text` | + +A block is always stored uncompressed when compression does not make it smaller. A higher `--min-compression-ratio` extends that to data that only compresses a little (for example textures in a GPU compression format, or audio), which saves the decompression work when it is loaded. + +### Example + +```bash +UnityDataTool archive repack scenes.bundle -o scenes-512k.bundle --block-size 524288 +UnityDataTool archive repack scenes.bundle -o scenes-split.bundle --split-at-file-boundaries -f Json +``` + +**Output:** +``` +Repacked scenes into /path/to/scenes-split.bundle + + Original Repacked +File Size 362,352 364,873 (+0.7%) +Compression Lz4HC Lz4HC +Block Count 11 9 +Uncompressed Blocks 0 0 +Largest Block 131,072 131,072 +Read Amplification 1.00x 1.00x + +Verified: all 4 files match the original byte for byte. +``` + +The report compares the two layouts: + +| Field | Meaning | +|-------|---------| +| Uncompressed Blocks | Blocks stored without compression in an archive that otherwise uses compression | +| Largest Block | Largest uncompressed block size, which is roughly the memory needed to decompress one block | +| Read Amplification | Uncompressed size of the blocks that must be read to load each file on its own, divided by the total size of the files. 1.00x means no block is shared between two files. A single LZMA block that holds four files reports 4.00x | + +`archive info`, `archive blocks` and `archive list` work on the repacked file, and `dump` and `analyze` read it the same way as the original. + +> **Note:** The output is checked with UnityFileSystemApi, which comes from the Unity Editor. Test a repacked archive in a Player build on your target platform before you ship it. + +--- + ## Related: inspecting objects inside an archive The `archive` command works at the container level — it shows the archive structure and can extract the raw files. To inspect the serialized objects inside those files, use the [`dump`](command-dump.md#archive-support) command, which can open an archive directly and dump all SerializedFiles inside it without extracting first. diff --git a/Documentation/unitydatatool.md b/Documentation/unitydatatool.md index b4f73c0..a289e27 100644 --- a/Documentation/unitydatatool.md +++ b/Documentation/unitydatatool.md @@ -8,7 +8,7 @@ A command-line tool for analyzing and inspecting Unity build output—AssetBundl |---------|-------------| | [`analyze`](command-analyze.md) | Extract data from Unity files into a SQLite database | | [`dump`](command-dump.md) | Convert SerializedFiles to human-readable text | -| [`archive`](command-archive.md) | List or extract contents of Unity Archives | +| [`archive`](command-archive.md) | List, extract or repack the contents of Unity Archives | | [`serialized-file`](command-serialized-file.md) | Quick inspection of SerializedFile metadata | | [`find-refs`](command-find-refs.md) | Trace reference chains to objects *(experimental)* | diff --git a/UnityBinaryFormat/ArchiveWriter.cs b/UnityBinaryFormat/ArchiveWriter.cs new file mode 100644 index 0000000..d4a3295 --- /dev/null +++ b/UnityBinaryFormat/ArchiveWriter.cs @@ -0,0 +1,142 @@ +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace UnityDataTools.BinaryFormat; + +/// +/// Serializes the header and metadata sections of a "UnityFS" Unity Archive. +/// +/// This is the inverse of ArchiveDetector: every field is written in the order and byte order +/// (big-endian) that ArchiveDetector reads, so an archive written here can be inspected with the +/// archive header / blocks / list commands. Only the combined BlocksInfo+DirectoryInfo layout with +/// the metadata directly after the header is written, which is what Unity itself writes for +/// AssetBundles. +/// +public static class ArchiveWriter +{ + const string Signature = "UnityFS"; + + // Unity writes this fixed string in place of the old "UnityWebBundleVersion". + const string UnusedVersionString = "5.x.x"; + + /// + /// Serializes the BlocksInfo followed by the DirectoryInfo. Block offsets are only part of the + /// format from version 9, so writeBlockOffsets must match the version in the header. + /// + public static byte[] SerializeMetadata(IReadOnlyList blocks, IReadOnlyList nodes, bool writeBlockOffsets) + { + using var stream = new MemoryStream(); + + // The uncompressed data hash is not used by the runtime; Unity writes zeros as well. + stream.Write(new byte[16]); + WriteUInt32(stream, (uint)blocks.Count); + foreach (var block in blocks) + { + WriteUInt32(stream, block.UncompressedSize); + WriteUInt32(stream, block.CompressedSize); + WriteUInt16(stream, block.Flags); + if (writeBlockOffsets) + WriteUInt64(stream, (ulong)block.Offset); + } + + WriteUInt32(stream, (uint)nodes.Count); + foreach (var node in nodes) + { + WriteUInt64(stream, node.DataOffset); + WriteUInt64(stream, node.Size); + WriteUInt32(stream, node.Flags); + WriteNullTermString(stream, node.Path); + } + + return stream.ToArray(); + } + + /// + /// Serializes the archive header, including the trailing alignment that format version 7 and + /// later expect before the metadata section. + /// + public static byte[] SerializeHeader(uint version, string unityVersion, ulong fileSize, + uint compressedMetadataSize, uint uncompressedMetadataSize, uint flags) + { + using var stream = new MemoryStream(); + WriteNullTermString(stream, Signature); + WriteUInt32(stream, version); + WriteNullTermString(stream, UnusedVersionString); + WriteNullTermString(stream, unityVersion); + WriteUInt64(stream, fileSize); + WriteUInt32(stream, compressedMetadataSize); + WriteUInt32(stream, uncompressedMetadataSize); + WriteUInt32(stream, flags); + + if (version >= 7) + WritePadding(stream, AlignTo16(stream.Length) - stream.Length); + + return stream.ToArray(); + } + + /// + /// Size of the header that SerializeHeader would produce. It does not depend on the size fields, + /// which lets a writer compute the file layout before it knows the final file size. + /// + public static int GetHeaderSize(uint version, string unityVersion) + { + return SerializeHeader(version, unityVersion, 0, 0, 0, 0).Length; + } + + /// + /// Offset of the data section from the start of the file, for an archive with the metadata + /// directly after the header. Matches ArchiveDetector.GetDataOffset. + /// + public static long GetDataOffset(uint version, string unityVersion, uint compressedMetadataSize, uint flags) + { + long offset = GetHeaderSize(version, unityVersion); + if ((flags & ArchiveFlags.BlockInfoNeedPaddingAtStart) != 0) + offset += AlignTo16(compressedMetadataSize); + else + offset += compressedMetadataSize; + return offset; + } + + public static long AlignTo16(long value) + { + return (value + 15) & ~15L; + } + + public static void WritePadding(Stream stream, long count) + { + for (long i = 0; i < count; i++) + stream.WriteByte(0); + } + + static void WriteUInt16(Stream stream, ushort value) + { + Span buffer = stackalloc byte[2]; + BinaryPrimitives.WriteUInt16BigEndian(buffer, value); + stream.Write(buffer); + } + + static void WriteUInt32(Stream stream, uint value) + { + Span buffer = stackalloc byte[4]; + BinaryPrimitives.WriteUInt32BigEndian(buffer, value); + stream.Write(buffer); + } + + static void WriteUInt64(Stream stream, ulong value) + { + Span buffer = stackalloc byte[8]; + BinaryPrimitives.WriteUInt64BigEndian(buffer, value); + stream.Write(buffer); + } + + // BinaryFileHelper.ReadNullTermString maps each byte to one char, so Latin1 is its exact inverse + // and paths keep their original bytes (including any UTF-8 sequences) through a read and write. + static void WriteNullTermString(Stream stream, string value) + { + stream.Write(Encoding.Latin1.GetBytes(value)); + stream.WriteByte(0); + } +} diff --git a/UnityDataTool.Tests/ArchiveRepackTests.cs b/UnityDataTool.Tests/ArchiveRepackTests.cs new file mode 100644 index 0000000..cd4f658 --- /dev/null +++ b/UnityDataTool.Tests/ArchiveRepackTests.cs @@ -0,0 +1,430 @@ +using System; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Threading.Tasks; +using NUnit.Framework; +using UnityDataTools.Archive; +using UnityDataTools.BinaryFormat; +using UnityDataTools.FileSystem; + +namespace UnityDataTools.UnityDataTool.Tests; + +#pragma warning disable NUnit2005, NUnit2006 + +public class ArchiveRepackTests +{ + private string m_TestOutputFolder; + private string m_TestDataFolder; + + // A single LZMA block holding four SerializedFiles (format version 8). + private string m_LzmaArchivePath; + + // An LZ4HC chunk-based archive in format version 9, with per-block offsets. + private string m_Version9ArchivePath; + + // An LZ4 Player build archive with several blocks and no block offsets (format version 8). + private string m_PlayerArchivePath; + + // A larger LZMA AssetBundle that contains a texture's .resS data. + private string m_AssetBundlePath; + + [OneTimeSetUp] + public void OneTimeSetup() + { + m_TestOutputFolder = Path.Combine(TestContext.CurrentContext.TestDirectory, "test_folder_repack"); + m_TestDataFolder = Path.Combine(TestContext.CurrentContext.TestDirectory, "Data"); + m_LzmaArchivePath = Path.Combine(m_TestDataFolder, "AssetBundles", "2023.1.0a16", "scenes"); + m_Version9ArchivePath = Path.Combine(m_TestDataFolder, "LeadingEdgeBuilds", "AssetBundlesLz4", "scenes"); + m_PlayerArchivePath = Path.Combine(m_TestDataFolder, "PlayerDataCompressed", "data.unity3d"); + m_AssetBundlePath = Path.Combine(m_TestDataFolder, "AssetBundles", "2023.1.0a16", "assetbundle"); + Directory.CreateDirectory(m_TestOutputFolder); + } + + [TearDown] + public void Teardown() + { + var testDir = new DirectoryInfo(m_TestOutputFolder); + testDir.EnumerateFiles().ToList().ForEach(f => f.Delete()); + testDir.EnumerateDirectories().ToList().ForEach(d => d.Delete(true)); + } + + string OutputPath(string name) => Path.Combine(m_TestOutputFolder, name); + + static (ArchiveHeaderInfo header, ArchiveMetadata metadata) ReadArchive(string path) + { + Assert.IsTrue(ArchiveDetector.TryReadArchiveHeader(path, out var header, out var error), error); + Assert.IsTrue(ArchiveDetector.TryReadArchiveMetadata(path, header, out var metadata, out error), error); + return (header, metadata); + } + + // Extracts both archives with the 'archive extract' command and compares the files, so the content + // check does not depend on the verification inside repack. + async Task AssertSameExtractedContent(string originalPath, string repackedPath) + { + var originalDir = OutputPath("extract-original"); + var repackedDir = OutputPath("extract-repacked"); + var (exitA, _) = await ConsoleTestHelper.RunCapturingStdOut("archive", "extract", originalPath, "-o", originalDir); + var (exitB, _) = await ConsoleTestHelper.RunCapturingStdOut("archive", "extract", repackedPath, "-o", repackedDir); + Assert.AreEqual(0, exitA); + Assert.AreEqual(0, exitB); + + var originalFiles = Directory.GetFiles(originalDir, "*", SearchOption.AllDirectories) + .Select(f => Path.GetRelativePath(originalDir, f)).OrderBy(f => f, StringComparer.Ordinal).ToArray(); + var repackedFiles = Directory.GetFiles(repackedDir, "*", SearchOption.AllDirectories) + .Select(f => Path.GetRelativePath(repackedDir, f)).OrderBy(f => f, StringComparer.Ordinal).ToArray(); + CollectionAssert.AreEqual(originalFiles, repackedFiles); + Assert.Greater(originalFiles.Length, 0); + + foreach (var file in originalFiles) + { + var a = File.ReadAllBytes(Path.Combine(originalDir, file)); + var b = File.ReadAllBytes(Path.Combine(repackedDir, file)); + Assert.IsTrue(a.AsSpan().SequenceEqual(b), $"Content of {file} differs"); + } + } + + static void AssertSameDirectory(ArchiveMetadata original, ArchiveMetadata repacked) + { + var a = original.DirectoryInfo.Nodes; + var b = repacked.DirectoryInfo.Nodes; + Assert.AreEqual(a.Length, b.Length); + for (int i = 0; i < a.Length; i++) + { + Assert.AreEqual(a[i].Path, b[i].Path); + Assert.AreEqual(a[i].Size, b[i].Size); + Assert.AreEqual(a[i].Flags, b[i].Flags); + } + } + + [Test] + public async Task Repack_LzmaArchive_DefaultsToUnityLz4HCLayout() + { + var output = OutputPath("scenes.lz4hc"); + var (exitCode, stdOut) = await ConsoleTestHelper.RunCapturingStdOut("archive", "repack", m_LzmaArchivePath, "-o", output); + + Assert.AreEqual(0, exitCode, stdOut); + StringAssert.Contains("Verified: all 4 files match the original byte for byte.", stdOut); + + var (originalHeader, originalMetadata) = ReadArchive(m_LzmaArchivePath); + var (header, metadata) = ReadArchive(output); + + Assert.AreEqual(originalHeader.Version, header.Version); + Assert.AreEqual(originalHeader.UnityVersion, header.UnityVersion); + Assert.AreEqual(new FileInfo(output).Length, (long)header.Size); + Assert.AreEqual(originalHeader.ArchiveFlagBits, header.ArchiveFlagBits); + AssertSameDirectory(originalMetadata, metadata); + + // Every block is a full 128 KB except the last, and they are LZ4HC compressed. + var blocks = metadata.BlocksInfo.Blocks; + Assert.Greater(blocks.Length, 1); + for (int i = 0; i < blocks.Length - 1; i++) + Assert.AreEqual(RepackOptions.DefaultBlockSize, blocks[i].UncompressedSize); + Assert.IsTrue(blocks.All(b => b.CompressionType == 3 || b.CompressionType == 0)); + Assert.IsTrue(blocks.Any(b => b.CompressionType == 3)); + + // The files are packed back to back, as in the original. + for (int i = 0; i < metadata.DirectoryInfo.Nodes.Length; i++) + Assert.AreEqual(originalMetadata.DirectoryInfo.Nodes[i].DataOffset, metadata.DirectoryInfo.Nodes[i].DataOffset); + + await AssertSameExtractedContent(m_LzmaArchivePath, output); + } + + [Test] + public async Task Repack_DumpOutputIsUnchanged() + { + var output = OutputPath("assetbundle.repacked"); + Assert.AreEqual(0, (await ConsoleTestHelper.RunCapturingStdOut( + "archive", "repack", m_AssetBundlePath, "-o", output, "--block-size", "32768", "--split-at-file-boundaries")).exitCode); + + var (exitA, dumpA) = await ConsoleTestHelper.RunCapturingStdOut("dump", m_AssetBundlePath, "--stdout"); + var (exitB, dumpB) = await ConsoleTestHelper.RunCapturingStdOut("dump", output, "--stdout"); + Assert.AreEqual(0, exitA); + Assert.AreEqual(0, exitB); + Assert.Greater(dumpA.Length, 1000); + Assert.AreEqual(dumpA, dumpB); + } + + [Test] + public async Task Repack_Version9Archive_KeepsBlockOffsets() + { + var output = OutputPath("v9.repacked"); + Assert.AreEqual(0, (await ConsoleTestHelper.RunCapturingStdOut( + "archive", "repack", m_Version9ArchivePath, "-o", output, "--block-size", "16384")).exitCode); + + var (header, metadata) = ReadArchive(output); + Assert.AreEqual(9u, header.Version); + Assert.IsTrue(header.HasStorageBlockOffsets); + + var blocks = metadata.BlocksInfo.Blocks; + Assert.IsTrue(blocks.All(b => b.UncompressedSize <= 16384)); + + // Without alignment the blocks are stored back to back. + for (int i = 1; i < blocks.Length; i++) + Assert.AreEqual(blocks[i - 1].Offset + blocks[i - 1].CompressedSize, blocks[i].Offset); + + await AssertSameExtractedContent(m_Version9ArchivePath, output); + } + + [Test] + public async Task Repack_BlockAlignment_PadsBlockPositions() + { + var output = OutputPath("v9.aligned"); + Assert.AreEqual(0, (await ConsoleTestHelper.RunCapturingStdOut( + "archive", "repack", m_Version9ArchivePath, "-o", output, "--block-size", "16384", "--block-alignment", "4096")).exitCode); + + var (header, metadata) = ReadArchive(output); + var dataStart = ArchiveDetector.GetDataOffset(header); + var blocks = metadata.BlocksInfo.Blocks; + Assert.Greater(blocks.Length, 2); + foreach (var block in blocks) + { + Assert.AreEqual(0, block.Offset % 4096, $"Block at {block.Offset} is not aligned"); + Assert.AreEqual(dataStart + block.Offset, block.FileOffset); + } + + await AssertSameExtractedContent(m_Version9ArchivePath, output); + } + + [Test] + public async Task Repack_BlockAlignment_RejectsArchivesWithoutBlockOffsets() + { + var output = OutputPath("v8.aligned"); + var (exitCode, stdErr) = await ConsoleTestHelper.RunCapturingStdErr( + "archive", "repack", m_LzmaArchivePath, "-o", output, "--block-alignment", "16"); + + Assert.AreEqual(1, exitCode); + StringAssert.Contains("version 9", stdErr); + Assert.IsFalse(File.Exists(output)); + } + + [Test] + public async Task Repack_SplitAtFileBoundaries_NoBlockSpansTwoFiles() + { + var spanned = OutputPath("spanned"); + var split = OutputPath("split"); + Assert.AreEqual(0, (await ConsoleTestHelper.RunCapturingStdOut("archive", "repack", m_LzmaArchivePath, "-o", spanned)).exitCode); + Assert.AreEqual(0, (await ConsoleTestHelper.RunCapturingStdOut( + "archive", "repack", m_LzmaArchivePath, "-o", split, "--split-at-file-boundaries")).exitCode); + + var (_, metadata) = ReadArchive(split); + var nodes = metadata.DirectoryInfo.Nodes; + foreach (var block in metadata.BlocksInfo.Blocks) + { + long start = block.DataOffset; + long end = start + block.UncompressedSize; + int owners = nodes.Count(n => (long)n.DataOffset < end && (long)(n.DataOffset + n.Size) > start); + Assert.AreEqual(1, owners, $"Block at data offset {start} holds data from {owners} files"); + } + + // Each file can now be read on its own, which spanning blocks do not allow. + Assert.AreEqual(1.0, ArchiveRepacker.ComputeStats(split).ReadAmplification, 1e-9); + Assert.Greater(ArchiveRepacker.ComputeStats(spanned).ReadAmplification, 1.0); + + await AssertSameExtractedContent(m_LzmaArchivePath, split); + } + + [Test] + public async Task Repack_FileAlignment_AlignsFileOffsets() + { + var output = OutputPath("aligned"); + Assert.AreEqual(0, (await ConsoleTestHelper.RunCapturingStdOut( + "archive", "repack", m_LzmaArchivePath, "-o", output, "--file-alignment", "4096")).exitCode); + + var (_, metadata) = ReadArchive(output); + var nodes = metadata.DirectoryInfo.Nodes; + foreach (var node in nodes) + Assert.AreEqual(0ul, node.DataOffset % 4096, $"{node.Path} starts at {node.DataOffset}"); + + // The padding is added only where needed and never overlaps the previous file. + for (int i = 1; i < nodes.Length; i++) + { + Assert.GreaterOrEqual(nodes[i].DataOffset, nodes[i - 1].DataOffset + nodes[i - 1].Size); + Assert.Less(nodes[i].DataOffset, nodes[i - 1].DataOffset + nodes[i - 1].Size + 4096); + } + + await AssertSameExtractedContent(m_LzmaArchivePath, output); + } + + [Test] + public async Task Repack_MaxCompressedBlockSize_LimitsStoredBlockSize() + { + var output = OutputPath("capped"); + Assert.AreEqual(0, (await ConsoleTestHelper.RunCapturingStdOut( + "archive", "repack", m_AssetBundlePath, "-o", output, "-c", "Lz4", "--block-size", "262144", "--max-compressed-block-size", "8192")).exitCode); + + var (_, metadata) = ReadArchive(output); + var blocks = metadata.BlocksInfo.Blocks; + Assert.IsTrue(blocks.All(b => b.CompressedSize <= 8192), "A block exceeds the compressed size limit"); + + // Well-compressing data still gets blocks longer than the limit. + Assert.IsTrue(blocks.Any(b => b.UncompressedSize > 8192)); + Assert.IsTrue(blocks.All(b => b.UncompressedSize <= 262144)); + + await AssertSameExtractedContent(m_AssetBundlePath, output); + } + + [Test] + public async Task Repack_MinCompressionRatio_StoresPoorlyCompressingBlocksUncompressed() + { + var normal = OutputPath("normal"); + var strict = OutputPath("strict"); + Assert.AreEqual(0, (await ConsoleTestHelper.RunCapturingStdOut("archive", "repack", m_Version9ArchivePath, "-o", normal)).exitCode); + Assert.AreEqual(0, (await ConsoleTestHelper.RunCapturingStdOut( + "archive", "repack", m_Version9ArchivePath, "-o", strict, "--min-compression-ratio", "1.5")).exitCode); + + var normalBlocks = ReadArchive(normal).metadata.BlocksInfo.Blocks; + var strictBlocks = ReadArchive(strict).metadata.BlocksInfo.Blocks; + Assert.AreEqual(normalBlocks.Length, strictBlocks.Length); + + // Blocks that compress by less than 1.5x are stored as-is; the others are unchanged. + bool anyFallback = false; + for (int i = 0; i < normalBlocks.Length; i++) + { + var ratio = (double)normalBlocks[i].UncompressedSize / normalBlocks[i].CompressedSize; + if (normalBlocks[i].CompressionType != 0 && ratio < 1.5) + { + Assert.AreEqual(0, strictBlocks[i].CompressionType); + Assert.AreEqual(strictBlocks[i].UncompressedSize, strictBlocks[i].CompressedSize); + anyFallback = true; + } + else + { + Assert.AreEqual(normalBlocks[i].CompressionType, strictBlocks[i].CompressionType); + } + } + Assert.IsTrue(anyFallback, "The test data should contain a block that compresses poorly"); + + await AssertSameExtractedContent(m_Version9ArchivePath, strict); + } + + [Test] + public async Task Repack_NoCompression_StoresDataAsIs() + { + var output = OutputPath("uncompressed"); + Assert.AreEqual(0, (await ConsoleTestHelper.RunCapturingStdOut("archive", "repack", m_PlayerArchivePath, "-o", output, "-c", "None")).exitCode); + + var (header, metadata) = ReadArchive(output); + Assert.IsFalse(header.HasStorageBlockOffsets); + Assert.IsTrue(metadata.BlocksInfo.Blocks.All(b => b.CompressionType == 0 && b.CompressedSize == b.UncompressedSize)); + + var dataSize = metadata.BlocksInfo.Blocks.Sum(b => (long)b.UncompressedSize); + var lastNode = metadata.DirectoryInfo.Nodes[^1]; + Assert.AreEqual((long)(lastNode.DataOffset + lastNode.Size), dataSize); + + await AssertSameExtractedContent(m_PlayerArchivePath, output); + } + + [Test] + public async Task Repack_JsonFormat_ReportsBothLayouts() + { + var output = OutputPath("json"); + var (exitCode, stdOut) = await ConsoleTestHelper.RunCapturingStdOut( + "archive", "repack", m_LzmaArchivePath, "-o", output, "--split-at-file-boundaries", "-f", "Json"); + Assert.AreEqual(0, exitCode); + + var root = JsonDocument.Parse(stdOut).RootElement; + Assert.AreEqual(4, root.GetProperty("fileCount").GetInt32()); + Assert.IsTrue(root.GetProperty("verified").GetBoolean()); + + var original = root.GetProperty("original"); + var repacked = root.GetProperty("repacked"); + Assert.AreEqual("Lzma", original.GetProperty("compression").GetString()); + Assert.AreEqual(1, original.GetProperty("blockCount").GetInt32()); + Assert.AreEqual("Lz4HC", repacked.GetProperty("compression").GetString()); + Assert.AreEqual(new FileInfo(output).Length, repacked.GetProperty("fileSize").GetInt64()); + Assert.AreEqual(1.0, repacked.GetProperty("readAmplification").GetDouble(), 1e-9); + Assert.AreEqual(4.0, original.GetProperty("readAmplification").GetDouble(), 1e-9); + } + + [Test] + public async Task Repack_SkipVerify_IsReported() + { + var output = OutputPath("unverified"); + var (exitCode, stdOut) = await ConsoleTestHelper.RunCapturingStdOut("archive", "repack", m_LzmaArchivePath, "-o", output, "--skip-verify"); + Assert.AreEqual(0, exitCode); + StringAssert.Contains("Not verified", stdOut); + } + + [Test] + public async Task Repack_OutputSameAsInput_Fails() + { + var copy = OutputPath("copy"); + File.Copy(m_LzmaArchivePath, copy); + var before = File.ReadAllBytes(copy); + + var (exitCode, stdErr) = await ConsoleTestHelper.RunCapturingStdErr("archive", "repack", copy, "-o", copy); + Assert.AreEqual(1, exitCode); + StringAssert.Contains("different from the input", stdErr); + Assert.IsTrue(before.AsSpan().SequenceEqual(File.ReadAllBytes(copy))); + } + + [TestCase("--block-size", "100", "Block size")] + [TestCase("--block-size", "134217728", "Block size")] + [TestCase("--file-alignment", "3", "File alignment")] + [TestCase("--block-alignment", "0", "Block alignment")] + [TestCase("--min-compression-ratio", "0.5", "compression ratio")] + [TestCase("--max-compressed-block-size", "10", "Max compressed block size")] + public async Task Repack_InvalidOptions_Fail(string option, string value, string expectedMessage) + { + var output = OutputPath("invalid"); + var (exitCode, stdErr) = await ConsoleTestHelper.RunCapturingStdErr("archive", "repack", m_LzmaArchivePath, "-o", output, option, value); + Assert.AreEqual(1, exitCode); + StringAssert.Contains(expectedMessage, stdErr); + Assert.IsFalse(File.Exists(output)); + } + + [Test] + public async Task Repack_MaxCompressedBlockSizeWithoutCompression_Fails() + { + var (exitCode, stdErr) = await ConsoleTestHelper.RunCapturingStdErr( + "archive", "repack", m_LzmaArchivePath, "-o", OutputPath("x"), "-c", "None", "--max-compressed-block-size", "4096"); + Assert.AreEqual(1, exitCode); + StringAssert.Contains("no effect without compression", stdErr); + } + + [Test] + public async Task Repack_NotAnArchive_Fails() + { + var output = OutputPath("text"); + var (exitCode, stdErr) = await ConsoleTestHelper.RunCapturingStdErr( + "archive", "repack", Path.Combine(m_TestDataFolder, "TextFile.txt"), "-o", output); + Assert.AreEqual(1, exitCode); + StringAssert.Contains("not a Unity Archive", stdErr); + Assert.IsFalse(File.Exists(output)); + } + + [Test] + public async Task Repack_WebBundle_Fails() + { + var (exitCode, stdErr) = await ConsoleTestHelper.RunCapturingStdErr( + "archive", "repack", Path.Combine(m_TestDataFolder, "WebBundles", "HelloWorld.data"), "-o", OutputPath("web")); + Assert.AreEqual(1, exitCode); + StringAssert.Contains("only supported for Unity Archive files", stdErr); + } + + [Test] + public async Task VerifySameContent_DetectsChangedContent() + { + // An uncompressed repack lets the test change one byte of file content directly on disk. + var output = OutputPath("tampered"); + Assert.AreEqual(0, (await ConsoleTestHelper.RunCapturingStdOut("archive", "repack", m_LzmaArchivePath, "-o", output, "-c", "None")).exitCode); + + var (header, metadata) = ReadArchive(output); + var bytes = File.ReadAllBytes(output); + var position = ArchiveDetector.GetDataOffset(header) + (long)metadata.DirectoryInfo.Nodes[1].DataOffset + 100; + bytes[position] ^= 0xFF; + File.WriteAllBytes(output, bytes); + + UnityFileSystem.Init(); + try + { + var ex = Assert.Throws(() => ArchiveRepacker.VerifySameContent(m_LzmaArchivePath, output)); + StringAssert.Contains(metadata.DirectoryInfo.Nodes[1].Path, ex.Message); + } + finally + { + UnityFileSystem.Cleanup(); + } + } +} diff --git a/UnityDataTool/Program.cs b/UnityDataTool/Program.cs index a887973..53482c9 100644 --- a/UnityDataTool/Program.cs +++ b/UnityDataTool/Program.cs @@ -290,6 +290,52 @@ static Command BuildArchiveCommand() (FileInfo fi, ArchiveTool.OutputFormat f) => Task.FromResult(ArchiveTool.PrintSummary(fi, f)), pathArg, fOpt); + var repackOutOpt = new Option(aliases: new[] { "--output-file", "-o" }, description: "Path of the repacked archive") { IsRequired = true }; + var compressionOpt = new Option(aliases: new[] { "--compression", "-c" }, description: "Block compression", getDefaultValue: () => RepackCompression.Lz4HC); + var blockSizeOpt = new Option(aliases: new[] { "--block-size" }, description: "Largest uncompressed size of a block, in bytes. Unity uses 131072 (128 KB)", getDefaultValue: () => RepackOptions.DefaultBlockSize); + var maxCompressedOpt = new Option(aliases: new[] { "--max-compressed-block-size" }, description: "Largest size of a block after compression, in bytes. Blocks that would compress to more are made shorter"); + var splitOpt = new Option(aliases: new[] { "--split-at-file-boundaries" }, description: "Start a new block for each file instead of letting blocks span files"); + var alignOpt = new Option(aliases: new[] { "--file-alignment" }, description: "Align the start of each file in the uncompressed data to this many bytes (a power of two), padding with zeros", getDefaultValue: () => 1); + var blockAlignOpt = new Option(aliases: new[] { "--block-alignment" }, description: "Align the position of each block in the file to this many bytes (a power of two). Needs archive format version 9 (Unity 6.7)", getDefaultValue: () => 1); + var ratioOpt = new Option(aliases: new[] { "--min-compression-ratio" }, description: "Store a block uncompressed unless uncompressed/compressed size reaches this ratio", getDefaultValue: () => 1.0); + var skipVerifyOpt = new Option(aliases: new[] { "--skip-verify" }, description: "Do not check that the repacked archive has the same content as the original"); + + var repackArchiveCommand = new Command("repack", "Rewrite a Unity Archive with a different LZ4/LZ4HC block layout, keeping its content.") + { + pathArg, + repackOutOpt, + compressionOpt, + blockSizeOpt, + maxCompressedOpt, + splitOpt, + alignOpt, + blockAlignOpt, + ratioOpt, + skipVerifyOpt, + fOpt, + }; + // Bound via InvocationContext because the option count exceeds the strongly-typed SetHandler overloads. + repackArchiveCommand.SetHandler((InvocationContext context) => + { + var parse = context.ParseResult; + var options = new RepackOptions + { + Compression = parse.GetValueForOption(compressionOpt), + BlockSize = parse.GetValueForOption(blockSizeOpt), + MaxCompressedBlockSize = parse.GetValueForOption(maxCompressedOpt), + SplitAtFileBoundaries = parse.GetValueForOption(splitOpt), + FileAlignment = parse.GetValueForOption(alignOpt), + BlockAlignment = parse.GetValueForOption(blockAlignOpt), + MinCompressionRatio = parse.GetValueForOption(ratioOpt), + }; + context.ExitCode = ArchiveTool.Repack( + parse.GetValueForArgument(pathArg), + parse.GetValueForOption(repackOutOpt), + options, + parse.GetValueForOption(skipVerifyOpt), + parse.GetValueForOption(fOpt)); + }); + return new Command("archive", "Inspect or extract the contents of a Unity archive (AssetBundle or web platform .data file).") { extractArchiveCommand, @@ -297,6 +343,7 @@ static Command BuildArchiveCommand() headerArchiveCommand, blocksArchiveCommand, infoArchiveCommand, + repackArchiveCommand, }; }