Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
Payload in segments compressed in parallel
KnifeLemon739a90835cbd
diff --git a/build/tools/make-setup.cs b/build/tools/make-setup.csindex b83dfe27..0936f4ce 100644--- a/build/tools/make-setup.cs+++ b/build/tools/make-setup.cs@@ -43,7 +43,7 @@ var engines = EngineDownloads.Packagesvar watch = Stopwatch.StartNew();var manifest = SetupPayload.Write(program, app, Path.GetFullPath(output), version, engines, marker,- quality: fast ? 5 : 11, window: 24);+ quality: fast ? 5 : 11, window: 24, log: Console.WriteLine);var size = new FileInfo(output).Length;Console.WriteLine($"{manifest.Files.Count} files, {manifest.TotalSize / 1_000_000} MB -> {output} ({size / 1_000_000} MB) in {watch.Elapsed.TotalSeconds:0} s; " +$"engines offered: {string.Join(", ", engines.Select(e => e.Suggested ? e.Id + "*" : e.Id))}");diff --git a/src/Filee.Setup/Installation/Installer.cs b/src/Filee.Setup/Installation/Installer.csindex 4e28327d..79341f4f 100644--- a/src/Filee.Setup/Installation/Installer.cs+++ b/src/Filee.Setup/Installation/Installer.cs@@ -274,14 +274,16 @@ public sealed class Installer(SetupContext context, SetupPayload payload)var cli = Path.Combine(folder, SetupNames.CliFolder);if (PathVariable.Set(Registry, choices.Scope, cli, choices.Tasks.Cli)){- undo.Push(("PATH", () =>- {- PathVariable.Set(Registry, choices.Scope, cli, !choices.Tasks.Cli);- System.BroadcastEnvironmentChange();- }));+ undo.Push(("PATH", UndoPath));System.BroadcastEnvironmentChange();Log.Info($"{(choices.Tasks.Cli ? "Added" : "Removed")} {cli} {(choices.Tasks.Cli ? "to" : "from")} PATH");}++ void UndoPath()+ {+ PathVariable.Set(Registry, choices.Scope, cli, !choices.Tasks.Cli);+ System.BroadcastEnvironmentChange();+ }}private void WriteUninstallEntry(Hive hive, string folder, InstallChoices choices)diff --git a/src/Filee.Setup/Payload/PayloadManifest.cs b/src/Filee.Setup/Payload/PayloadManifest.csindex bcf871c2..2c9e4f91 100644--- a/src/Filee.Setup/Payload/PayloadManifest.cs+++ b/src/Filee.Setup/Payload/PayloadManifest.cs@@ -7,18 +7,21 @@ using System.Text.Json;namespace Filee.Setup.Payload;/// <summary>One file of the app, relative to the install folder (backslashes).</summary>-public sealed record PayloadFile(string Path, long Size, string Sha256);+/// <param name="Segment">The Brotli stream it is in (files are in manifest order within it).</param>+public sealed record PayloadFile(string Path, long Size, string Sha256, int Segment = 0);/// <summary>An engine package of Settings → Engines, as Setup offers it on a fresh install.</summary>/// <param name="MarkerFolders">Folders under %LocalAppData%\Filee\engines that are all marked when it is installed.</param>public sealed record EngineOffer(string Id, IReadOnlyList<string> MarkerFolders, long DownloadSize, long InstalledSize, bool Suggested);+/// <param name="Segments">Compressed length of each Brotli stream, one after the other in the payload.</param>public sealed record PayloadManifest(string Version,IReadOnlyList<PayloadFile> Files,string CompressedSha256,IReadOnlyList<EngineOffer> Engines,- string EngineMarker)+ string EngineMarker,+ IReadOnlyList<long> Segments){/// <summary>Format of the payload; a Setup refuses a payload with another one.</summary>public const int CurrentFormat = 1;@@ -36,6 +39,10 @@ public sealed record PayloadManifest(writer.WriteString("compression", "brotli");writer.WriteString("compressedSha256", CompressedSha256);writer.WriteString("engineMarker", EngineMarker);+ writer.WriteStartArray("segments");+ foreach (var segment in Segments)+ writer.WriteNumberValue(segment);+ writer.WriteEndArray();writer.WriteStartArray("engines");foreach (var engine in Engines){@@ -58,6 +65,7 @@ public sealed record PayloadManifest(writer.WriteString("path", file.Path);writer.WriteNumber("size", file.Size);writer.WriteString("sha256", file.Sha256);+ writer.WriteNumber("segment", file.Segment);writer.WriteEndObject();}writer.WriteEndArray();@@ -75,9 +83,15 @@ public sealed record PayloadManifest(var root = document.RootElement;if (root.GetProperty("format").GetInt32() != CurrentFormat || root.GetProperty("compression").GetString() != "brotli")throw new InvalidDataException("Unknown payload format.");+ var segments = root.GetProperty("segments").EnumerateArray().Select(s => s.GetInt64()).ToList();var files = root.GetProperty("files").EnumerateArray()- .Select(f => new PayloadFile(f.GetProperty("path").GetString()!, f.GetProperty("size").GetInt64(), f.GetProperty("sha256").GetString()!))+ .Select(f => new PayloadFile(f.GetProperty("path").GetString()!, f.GetProperty("size").GetInt64(),+ f.GetProperty("sha256").GetString()!, f.GetProperty("segment").GetInt32())).ToList();+ if (segments.Count == 0 || segments.Any(s => s <= 0)+ || files.Any(f => f.Segment < 0 || f.Segment >= segments.Count)+ || files.Zip(files.Skip(1)).Any(p => p.Second.Segment < p.First.Segment))+ throw new InvalidDataException("The payload's segments don't add up.");foreach (var file in files)CheckPath(file.Path);if (files.Select(f => f.Path).Distinct(StringComparer.OrdinalIgnoreCase).Count() != files.Count)@@ -95,7 +109,8 @@ public sealed record PayloadManifest(files,root.GetProperty("compressedSha256").GetString()!,engines,- root.TryGetProperty("engineMarker", out var marker) ? marker.GetString() ?? "" : "");+ root.TryGetProperty("engineMarker", out var marker) ? marker.GetString() ?? "" : "",+ segments);}catch (Exception ex) when (ex is JsonException or KeyNotFoundException or InvalidOperationException or NullReferenceException){diff --git a/src/Filee.Setup/Payload/SetupPayload.cs b/src/Filee.Setup/Payload/SetupPayload.csindex 8c894c5a..fef87588 100644--- a/src/Filee.Setup/Payload/SetupPayload.cs+++ b/src/Filee.Setup/Payload/SetupPayload.cs@@ -1,12 +1,13 @@// The payload appended to Setup.exe://-// [Setup program][Brotli stream: every file of the app, one after the other][manifest JSON][trailer, 72 bytes]+// [Setup program][Brotli streams: the app's files, one after the other][manifest JSON][trailer, 72 bytes]// (then, once Setup is signed, the Authenticode signature: the trailer sits right before it)//// Trailer: "FILEE-PAYLOAD-01", payload offset, compressed length, manifest length (little-endian Int64 each) and the-// SHA-256 of the manifest. The manifest holds the SHA-256 of the compressed stream and of every file. One stream for-// all files compresses far better than a zip (the .NET assemblies share much). Setup checks the stream's hash before-// it changes anything and every file's hash while unpacking.+// SHA-256 of the manifest. The manifest holds the SHA-256 of the compressed data and of every file. Files are packed+// into a few large streams (segments, compressed in parallel) rather than one per file: similar files next to each+// other compress far better than a zip (the .NET assemblies share much). Setup checks the hash of the compressed data+// before it changes anything and every file's hash while unpacking.using System.Buffers;using System.Buffers.Binary;@@ -154,39 +155,44 @@ public sealed class SetupPayload : IDisposable/// </summary>public void ExtractTo(string folder, IProgress<long>? progress = null, CancellationToken cancellation = default){- _file.Position = Offset;- using var compressed = new BoundedReadStream(_file, CompressedLength);- using var brotli = new BrotliStream(compressed, CompressionMode.Decompress);var buffer = ArrayPool<byte>.Shared.Rent(BufferSize);long written = 0;+ var start = Offset;try{- foreach (var file in Manifest.Files)+ for (var segment = 0; segment < Manifest.Segments.Count; segment++){- cancellation.ThrowIfCancellationRequested();- var target = Path.Combine(folder, file.Path);- Directory.CreateDirectory(Path.GetDirectoryName(target)!);- using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);- using (var output = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None, BufferSize))+ _file.Position = start;+ start += Manifest.Segments[segment];+ using var compressed = new BoundedReadStream(_file, Manifest.Segments[segment]);+ using var brotli = new BrotliStream(compressed, CompressionMode.Decompress);+ foreach (var file in Manifest.Files.Where(f => f.Segment == segment)){- var left = file.Size;- while (left > 0)+ cancellation.ThrowIfCancellationRequested();+ var target = Path.Combine(folder, file.Path);+ Directory.CreateDirectory(Path.GetDirectoryName(target)!);+ using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);+ using (var output = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None, BufferSize)){- var read = brotli.Read(buffer, 0, (int)Math.Min(buffer.Length, left));- if (read == 0)- throw new InvalidDataException($"The payload ends inside {file.Path}.");- hash.AppendData(buffer, 0, read);- output.Write(buffer, 0, read);- left -= read;- written += read;- progress?.Report(written);+ var left = file.Size;+ while (left > 0)+ {+ var read = brotli.Read(buffer, 0, (int)Math.Min(buffer.Length, left));+ if (read == 0)+ throw new InvalidDataException($"The payload ends inside {file.Path}.");+ hash.AppendData(buffer, 0, read);+ output.Write(buffer, 0, read);+ left -= read;+ written += read;+ progress?.Report(written);+ }}+ if (PayloadManifest.Hex(hash.GetHashAndReset()) != file.Sha256)+ throw new InvalidDataException($"{file.Path} doesn't match its checksum.");}- if (PayloadManifest.Hex(hash.GetHashAndReset()) != file.Sha256)- throw new InvalidDataException($"{file.Path} doesn't match its checksum.");+ if (brotli.Read(buffer, 0, 1) != 0)+ throw new InvalidDataException("The payload has more data than its manifest lists.");}- if (brotli.Read(buffer, 0, 1) != 0)- throw new InvalidDataException("The payload has more data than its manifest lists.");}finally{@@ -205,9 +211,13 @@ public sealed class SetupPayload : IDisposablepublic void Dispose() => _file.Dispose();+ /// <summary>Raw size from which files start a new segment (each segment is compressed on its own core).</summary>+ public const long SegmentSize = 24L << 20;+/// <summary>/// Appends <paramref name="appFolder"/> to a copy of <paramref name="setupProgram"/>: writes <paramref name="output"/>,- /// the finished Setup. Brotli quality 11 with the largest window compresses best (and slowest).+ /// the finished Setup. Brotli quality 11 with the largest window compresses best (and slowest); the segments are+ /// compressed in parallel./// </summary>public static PayloadManifest Write(string setupProgram, string appFolder, string output, string version,IReadOnlyList<EngineOffer> engines, string engineMarker, int quality = 11, int window = 24, Action<string>? log = null)@@ -219,41 +229,75 @@ public sealed class SetupPayload : IDisposable.OrderBy(p => Path.GetExtension(p), StringComparer.OrdinalIgnoreCase).ThenBy(p => p, StringComparer.OrdinalIgnoreCase).ToList();- var files = new List<PayloadFile>();- var partial = output + ".partial";- using (var target = new FileStream(partial, FileMode.Create, FileAccess.ReadWrite, FileShare.None, BufferSize))+ foreach (var relative in paths)+ PayloadManifest.CheckPath(relative);++ // Consecutive files up to SegmentSize per segment.+ var groups = new List<List<string>>();+ long groupSize = SegmentSize;+ foreach (var relative in paths){- using (var program = File.OpenRead(setupProgram))+ var size = new FileInfo(Path.Combine(appFolder, relative)).Length;+ if (groupSize >= SegmentSize){- if (SetupPayload.OverlayEnd(program) != program.Length)- throw new InvalidOperationException("Sign Setup after appending the payload, not before.");- program.Position = 0;- program.CopyTo(target);+ groups.Add([]);+ groupSize = 0;}- var offset = target.Position;- using var compressedHash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);- using (var compressor = new BrotliWriteStream(target, quality, window, compressedHash))+ groups[^1].Add(relative);+ groupSize += size;+ }+ if (groups.Count == 0)+ groups.Add([]);++ var compressed = new byte[groups.Count][];+ var hashed = new PayloadFile[groups.Count][];+ Parallel.For(0, groups.Count, segment =>+ {+ using var buffer = new MemoryStream();+ var segmentFiles = new List<PayloadFile>();+ using (var compressor = new BrotliWriteStream(buffer, quality, window)){- foreach (var relative in paths)+ var chunk = new byte[BufferSize];+ foreach (var relative in groups[segment]){- PayloadManifest.CheckPath(relative);using var input = File.OpenRead(Path.Combine(appFolder, relative));using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);- var buffer = new byte[BufferSize];int read;long size = 0;- while ((read = input.Read(buffer)) > 0)+ while ((read = input.Read(chunk)) > 0){- hash.AppendData(buffer, 0, read);- compressor.Write(buffer, 0, read);+ hash.AppendData(chunk, 0, read);+ compressor.Write(chunk, 0, read);size += read;}- files.Add(new PayloadFile(relative, size, PayloadManifest.Hex(hash.GetHashAndReset())));- log?.Invoke(relative);+ segmentFiles.Add(new PayloadFile(relative, size, PayloadManifest.Hex(hash.GetHashAndReset()), segment));}}+ compressed[segment] = buffer.ToArray();+ hashed[segment] = [.. segmentFiles];+ log?.Invoke($"segment {segment + 1}/{groups.Count}: {groups[segment].Count} files, {compressed[segment].Length / 1_000_000} MB");+ });++ var partial = output + ".partial";+ using (var target = new FileStream(partial, FileMode.Create, FileAccess.ReadWrite, FileShare.None, BufferSize))+ {+ using (var program = File.OpenRead(setupProgram))+ {+ if (SetupPayload.OverlayEnd(program) != program.Length)+ throw new InvalidOperationException("Sign Setup after appending the payload, not before.");+ program.Position = 0;+ program.CopyTo(target);+ }+ var offset = target.Position;+ using var compressedHash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);+ foreach (var segment in compressed)+ {+ compressedHash.AppendData(segment);+ target.Write(segment);+ }var length = target.Position - offset;- var manifest = new PayloadManifest(version, files, PayloadManifest.Hex(compressedHash.GetHashAndReset()), engines, engineMarker);+ var manifest = new PayloadManifest(version, hashed.SelectMany(f => f).ToList(), PayloadManifest.Hex(compressedHash.GetHashAndReset()),+ engines, engineMarker, compressed.Select(c => (long)c.Length).ToList());var json = manifest.ToJson();target.Write(json);var trailer = new byte[TrailerLength];@@ -298,8 +342,8 @@ public sealed class SetupPayload : IDisposablepublic override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();}- /// <summary>Brotli with a chosen window (BrotliStream only takes the quality), hashing what it writes.</summary>- private sealed class BrotliWriteStream(Stream inner, int quality, int window, IncrementalHash hash) : Stream+ /// <summary>Brotli with a chosen window (BrotliStream only takes the quality).</summary>+ private sealed class BrotliWriteStream(Stream inner, int quality, int window) : Stream{private BrotliEncoder _encoder = new(quality, window);private readonly byte[] _output = new byte[BufferSize];@@ -316,11 +360,12 @@ public sealed class SetupPayload : IDisposablewhile (true){var status = _encoder.Compress(input, _output, out var consumed, out var produced, isFinalBlock: false);- Emit(produced);- input = input[consumed..];if (status == OperationStatus.InvalidData)throw new InvalidDataException("Brotli refused the data.");- if (input.IsEmpty && status == OperationStatus.Done)+ inner.Write(_output, 0, produced);+ input = input[consumed..];+ // DestinationTooSmall: more output is waiting; otherwise the encoder has taken all the input.+ if (status != OperationStatus.DestinationTooSmall && input.IsEmpty)return;}}@@ -332,23 +377,17 @@ public sealed class SetupPayload : IDisposablewhile (true){var status = _encoder.Compress(ReadOnlySpan<byte>.Empty, _output, out _, out var produced, isFinalBlock: true);- Emit(produced);+ inner.Write(_output, 0, produced);if (status == OperationStatus.Done)break;+ if (status == OperationStatus.InvalidData)+ throw new InvalidDataException("Brotli refused the data.");}_encoder.Dispose();}base.Dispose(disposing);}- private void Emit(int produced)- {- if (produced == 0)- return;- inner.Write(_output, 0, produced);- hash.AppendData(_output, 0, produced);- }-public override void Flush(){}diff --git a/src/Filee.Setup/Platform/SetupPaths.cs b/src/Filee.Setup/Platform/SetupPaths.csindex 664cb13e..96c6dbc0 100644--- a/src/Filee.Setup/Platform/SetupPaths.cs+++ b/src/Filee.Setup/Platform/SetupPaths.cs@@ -44,8 +44,8 @@ public sealed record SetupPaths(static string Folder(Environment.SpecialFolder folder) =>Environment.GetFolderPath(folder, Environment.SpecialFolderOption.DoNotVerify);var localAppData = Folder(Environment.SpecialFolder.LocalApplicationData);+ // A 64-bit process: ProgramFiles is "C:\Program Files", not the x86 one.return new SetupPaths(- // A 64-bit process: this is "C:\Program Files", not the x86 one.Folder(Environment.SpecialFolder.ProgramFiles),Path.Combine(localAppData, "Programs"),Folder(Environment.SpecialFolder.CommonPrograms),diff --git a/tests/Filee.Setup.Tests/PayloadTests.cs b/tests/Filee.Setup.Tests/PayloadTests.csindex 8d9b9864..c92d53f2 100644--- a/tests/Filee.Setup.Tests/PayloadTests.cs+++ b/tests/Filee.Setup.Tests/PayloadTests.cs@@ -36,6 +36,24 @@ public class PayloadTestsAssert.True(payload.CompressedLength < payload.Manifest.TotalSize / 10);}+ [Fact]+ public void Large_apps_are_packed_in_several_segments()+ {+ using var bench = new SetupBench(app: (temp, _) =>+ {+ temp.Write(@"app\a.bin", new string('a', (int)(SetupPayload.SegmentSize + 1000)));+ temp.Write(@"app\b.bin", new string('b', 2_000_000));+ });+ using var payload = SetupPayload.Open(bench.SetupExe)!;+ Assert.True(payload.Manifest.Segments.Count >= 2);+ Assert.Equal(payload.CompressedLength, payload.Manifest.Segments.Sum());+ payload.Verify(cancellation: TestContext.Current.CancellationToken);+ var target = bench.Temp.Sub("out");+ payload.ExtractTo(target, cancellation: TestContext.Current.CancellationToken);+ foreach (var file in Directory.EnumerateFiles(bench.AppFolder, "*", SearchOption.AllDirectories))+ Assert.Equal(File.ReadAllBytes(file), File.ReadAllBytes(Path.Combine(target, Path.GetRelativePath(bench.AppFolder, file))));+ }+[Fact]public void The_uninstaller_is_the_program_without_its_payload(){