Repository navigation
Expand file tree
/
Copy pathCompressor.cs
More file actions
1961 lines (1620 loc) · 84.9 KB
/
Copy pathCompressor.cs
File metadata and controls
1961 lines (1620 loc) · 84.9 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
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
MIT License
Copyright (c) 2024 Dmitry Muravyev (youtube.com/@DmitryMuravyev)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
The description in the code body will be quite brief, so if you want more detailed information,
then please refer to the following links, where I talk about how this compression method works,
about problems that arose during the development and how I solved them:
Boosty (Russian):
Sprint 1 - https://boosty.to/muravyev/posts/9241e5a2-a490-4530-a376-e9cae0f9e9bf?share=post_link
Sprint 2 - https://boosty.to/muravyev/posts/dfdd0b1d-f27d-446a-ab38-d55cbc7cd580?share=post_link
Sprint 3 - https://boosty.to/muravyev/posts/bc58a9af-f075-4004-a98e-6535edab9925?share=post_link
Patreon (Eng subs):
Sprint 1 - https://www.patreon.com/posts/delta-encoding-1-106850934
Sprint 2 - https://www.patreon.com/posts/delta-encoding-2-108056837
Sprint 3 - https://www.patreon.com/posts/delta-encoding-3-108236064
*/
////////////////////////////////////////////////////////////////////////////////////////////////////
// Symbol definitions
////////////////////////////////////////////////////////////////////////////////////////////////////
// Depending on the microcontroller firmware compiler optimization parameters,
// this option may be more CPU-efficient.
// See the CompressBlock() method below.
#define SEQUENTIAL_METHODS_AND_INITIAL_VALUES_DECLARATION
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Channels;
using System.Runtime.Intrinsics.X86;
using System.Runtime.CompilerServices;
namespace DeltaComp
{
// Delta calculation options (please refer to the links in the header).
public enum DeltaOption
{
FixedWindowOnly = 0,
AdaptiveFloatingWindowOnly = 1,
FixedWindowFirst = 2,
AdaptiveFloatingWindowFirst = 3
}
// Stages of the compression process
public enum CompressionStage
{
None = 0,
Preparation = 1,
Analysis = 2,
Compression = 3,
Done = 4,
Cancelled = 5,
Failed = 6
}
// This class is designed for data compression using delta encoding.
public class Compressor
{
////////////////////////////////////////////////////////////////////////////////////////////////////
// Private constants/attributes/variables
////////////////////////////////////////////////////////////////////////////////////////////////////
// Some static constants
private static class Constants
{
public const byte DefaultBlockSizeBits = 8;
public const byte DefaultWidthOfSquare = 1;
public const int WaitForTasksSleepDuration = 100;
public const int WaitForBestBlockReadyEventTimeout = 1000;
public const double MinProgressIcrease = 0.1d;
public const int MaxStackallocMethods = 256;
public const int MaxBitsPerChannel = 32;
public const int AutoSearchGrowingSteps = 3;
}
// ATTENTION!!!
// If we want to use a block length of 32 bits, then we need to change the type
// of all variables associated with the length to UInt64! If we use the UInt32 type,
// then the maximum block length field should be no more than 31 bits!
// The structure defining a single compression method
private struct Method
{
public UInt32 Length;
public byte Index;
public UInt32 InitialValue;
}
// A structure defining a single block combining compression methods for all channels
private struct Block
{
public UInt32 StartFrame;
public UInt32 Length;
public byte[] Methods;
public UInt32[] InitialValues; // 0 for uncompressed data
public double Efficiency;
}
// This one is used to find the best blocks and analyze them in parallel
private struct DistributedBlock
{
public Block Block;
public volatile bool Ready;
}
// Source data channels list
private readonly List<Channel> _sourceChannels;
// Compression parameters
private byte _headerBits; // We'll set it in the Constructor
private byte _blockSizeBits; // We'll set it in the Constructor
private UInt32 _maxBlockSize = 0;
private DeltaOption _deltaCalculationOption = DeltaOption.FixedWindowFirst;
private byte _widthOfSquare = Constants.DefaultWidthOfSquare;
private UInt16 _squaresPerImageWidth = 0;
private UInt16 _squareSize = Constants.DefaultWidthOfSquare;
private readonly bool _bestBlocksArrayUsed = false;
// Compression global variables
private volatile DistributedBlock[] _bestBlocks = null!;
private UInt128 _bitsBuffer = 0;
private byte _bitsBufferCount = 0;
// Source data, read once and stored in the compression order (already split into squares, if used).
// Reading through the channels is relatively slow, and each frame is read many times during the analysis.
private UInt32[][] _frames = null!;
// Number of methods per channel, cached for the duration of the compression
private byte[] _methodsCount = null!;
// Handling multithreading and workflow operations
private EventWaitHandle _bestBlocksBufferEWH = null!;
private CancellationToken? _cancellationToken = null;
private bool _waitForTasksFinished = false;
private bool _fallIntoErrorRequested = false;
// Delegate methods
private readonly WriteCompressedByteDelegate _writeCompressedByteDelegate;
private readonly UpdateProgressDelegate _updateProgressDelegate;
////////////////////////////////////////////////////////////////////////////////////////////////////
// Public attributes/variables
////////////////////////////////////////////////////////////////////////////////////////////////////
// Source data parameters
public byte ChannelsCount = 0;
public byte BitsPerFrame = 0;
public byte[] BitsPerChannel;
public readonly UInt32 TotalFrames = 0;
public readonly UInt16 ImageWidth = 0;
public readonly UInt16 ImageHeight = 0;
// Compression parameters
public byte BlockSizeBits
{
get { return _blockSizeBits; }
set
{
_blockSizeBits = value;
_maxBlockSize = (UInt32)Math.Pow(2, _blockSizeBits);
CalculateHeaderBits();
}
}
public byte[] BitsPerMethodDeclaration;
public DeltaOption DeltaCalculationOption
{
get { return _deltaCalculationOption; }
set
{
_deltaCalculationOption = value;
CalculateHeaderBits();
}
}
// Build the chain of blocks with the minimum total size (dynamic programming).
// If false, the frame-by-frame efficiency analysis (sprint 2) is used. The output format is the same.
public bool UseOptimalBlockChain = true;
public bool SplitToSquares = false;
public byte WidthOfSquare
{
get { return _widthOfSquare; }
set
{
_widthOfSquare = value;
_squaresPerImageWidth = (UInt16)(ImageWidth / _widthOfSquare);
_squareSize = (UInt16)(_widthOfSquare * _widthOfSquare);
}
}
// Current status
public CompressionStage Stage = CompressionStage.None;
public double Progress = 0.0d;
// Delegate methods
public delegate void WriteCompressedByteDelegate(byte compressedByte);
public delegate void UpdateProgressDelegate(CompressionStage stage, double progress);
////////////////////////////////////////////////////////////////////////////////////////////////////
// Implementation
////////////////////////////////////////////////////////////////////////////////////////////////////
// Public methods
// Constructor for initialization in the context of an image
public Compressor(List<Channel> channels, UInt16 imageWidth, UInt16 imageHeight, bool multithreadedRead,
WriteCompressedByteDelegate writeCompressedByteDelegate, UpdateProgressDelegate updateProgressDelegate)
{
_sourceChannels = channels;
ChannelsUpdated();
ImageWidth = imageWidth;
ImageHeight = imageHeight;
TotalFrames = (UInt32)(ImageWidth * ImageHeight);
// The best blocks buffer is allocated when (and if) the frame-by-frame analysis runs
_bestBlocksArrayUsed = multithreadedRead;
BlockSizeBits = Constants.DefaultBlockSizeBits;
_writeCompressedByteDelegate = writeCompressedByteDelegate;
_updateProgressDelegate = updateProgressDelegate;
}
// Constructor for initialization in the context of a custom data
public Compressor(List<Channel> channels, UInt32 totalFrames, bool multithreadedRead,
WriteCompressedByteDelegate writeCompressedByteDelegate, UpdateProgressDelegate updateProgressDelegate)
{
_sourceChannels = channels;
ChannelsUpdated();
TotalFrames = totalFrames;
// The best blocks buffer is allocated when (and if) the frame-by-frame analysis runs
_bestBlocksArrayUsed = multithreadedRead;
BlockSizeBits = Constants.DefaultBlockSizeBits;
_writeCompressedByteDelegate = writeCompressedByteDelegate;
_updateProgressDelegate = updateProgressDelegate;
}
// Update the composition of channels and their target bit depth
// (in case if something changed after initialization).
[MemberNotNull(nameof(ChannelsCount)), MemberNotNull(nameof(BitsPerMethodDeclaration)),
MemberNotNull(nameof(BitsPerChannel)), MemberNotNull(nameof(BitsPerFrame))]
public void ChannelsUpdated()
{
ChannelsCount = (byte)_sourceChannels.Count;
BitsPerMethodDeclaration = new byte[ChannelsCount];
BitsPerChannel = new byte[ChannelsCount];
BitsPerFrame = 0;
for (byte c = 0; c < ChannelsCount; c++)
{
byte currentChannelTargetBitDepth = (byte)_sourceChannels[c].TargetBitDepth;
BitsPerChannel[c] = currentChannelTargetBitDepth;
BitsPerFrame += currentChannelTargetBitDepth;
}
}
// Compression settings chosen by AutoSelectSettings()
public sealed record AutoSettings(byte BlockSizeBits, DeltaOption DeltaCalculationOption, byte WidthOfSquare, UInt64 CompressedBits);
// Try the combinations of the given settings and apply the one that gives the smallest output
// (with the optimal chain of blocks). Squares widths are ignored for non-image data; 1 means no squares.
// All combinations of square sizes and delta options are tried (they interact strongly, so choosing
// them one after another gives noticeably worse results), each with its own block size search.
// The block size search stops early once the size has grown a few times in a row
// (the size as a function of the block size field has a single minimum in practice).
public AutoSettings AutoSelectSettings(IReadOnlyList<byte> blockSizeBitsOptions, IReadOnlyList<DeltaOption> deltaOptions,
IReadOnlyList<byte> squareWidths, CancellationToken? token)
{
_cancellationToken = token;
UpdateStatus(CompressionStage.Preparation, 0);
// Read the source data once (in the linear order)
bool splitToSquares = SplitToSquares;
SplitToSquares = false;
PrepareFrames();
SplitToSquares = splitToSquares;
UInt32[][] linearFrames = _frames;
bool isImage = (ImageWidth > 0) && (ImageHeight > 0);
var squares = isImage ? squareWidths.Where(w => (w > 0) && (ImageWidth % w == 0) && (ImageHeight % w == 0)).Distinct().ToList() : [];
if (squares.Count == 0) squares.Add(1);
var bitsOptions = blockSizeBitsOptions.OrderBy(b => b).ToList();
int trialsDone = 0;
object progressLock = new object();
var trials = (from square in squares from delta in deltaOptions select (square, delta)).ToList();
var results = RunAutoTrials(trials, linearFrames, bitsOptions, token, () =>
{
lock (progressLock) UpdateStatus(CompressionStage.Preparation, (UInt32)((UInt64)TotalFrames * (UInt64)(++trialsDone) / (UInt64)trials.Count));
});
// The smallest result (the first one in the order of the trials in case of a tie)
int best = 0;
for (int t = 1; t < trials.Count; t++) if (results[t].bits < results[best].bits) best = t;
byte bestSquare = trials[best].square;
if (isImage)
{
SplitToSquares = bestSquare > 1;
WidthOfSquare = bestSquare;
}
DeltaCalculationOption = trials[best].delta;
BlockSizeBits = results[best].blockSizeBits;
_frames = null!;
return (new AutoSettings(BlockSizeBits, DeltaCalculationOption, bestSquare, results[best].bits));
}
// Run the given trials (in parallel) and return the smallest size and its block size field for each
private (UInt64 bits, byte blockSizeBits)[] RunAutoTrials(List<(byte square, DeltaOption delta)> trials,
UInt32[][] linearFrames, List<byte> bitsOptions, CancellationToken? token, Action trialDone)
{
var results = new (UInt64 bits, byte blockSizeBits)[trials.Count];
try
{
Parallel.For(0, trials.Count, t =>
{
var (square, delta) = trials[t];
Compressor trial = CreateTrial(linearFrames, square, delta, token);
UInt64 minBits = UInt64.MaxValue;
byte minBlockSizeBits = 0;
int growing = 0;
foreach (byte blockSizeBits in bitsOptions)
{
trial.BlockSizeBits = blockSizeBits;
UInt64 bits = trial.FindOptimalChain(null, false);
if (bits < minBits)
{
minBits = bits;
minBlockSizeBits = blockSizeBits;
growing = 0;
}
else if (++growing >= Constants.AutoSearchGrowingSteps) break;
}
results[t] = (minBits, minBlockSizeBits);
trialDone();
});
}
catch (AggregateException ex) when (ex.InnerExceptions.All(e => e is OperationCanceledException))
{
throw ex.InnerExceptions[0];
}
return (results);
}
// A lightweight copy of this compressor for one combination of settings in AutoSelectSettings()
private Compressor CreateTrial(UInt32[][] linearFrames, byte square, DeltaOption delta, CancellationToken? token)
{
Compressor trial = (ImageWidth > 0)
? new Compressor(_sourceChannels, ImageWidth, ImageHeight, false, _ => { }, null!)
: new Compressor(_sourceChannels, TotalFrames, false, _ => { }, null!);
trial._cancellationToken = token;
trial.DeltaCalculationOption = delta;
trial.SplitToSquares = square > 1;
if (ImageWidth > 0) trial.WidthOfSquare = square;
trial._methodsCount = new byte[ChannelsCount];
trial._frames = new UInt32[ChannelsCount][];
for (byte c = 0; c < ChannelsCount; c++)
{
trial._methodsCount[c] = trial.GetMethodsCount(c);
if (!trial.SplitToSquares)
{
trial._frames[c] = linearFrames[c];
continue;
}
trial._frames[c] = new UInt32[TotalFrames];
for (UInt32 f = 0; f < TotalFrames; f++) trial._frames[c][f] = linearFrames[c][trial.GetPixelForSquares(f)];
}
return (trial);
}
// Since, in order to improve performance, we do not control
// read/write errors from the compression class, so external
// modules should be responsible for this,
// which may request an error termination.
public void RequestFallingIntoError()
{
_fallIntoErrorRequested = true;
}
public void Compress(CancellationToken? token)
{
// Some console outupt for the debugging purposes
/*
Debug.WriteLine("ChannelsCount: " + ChannelsCount.ToString());
Debug.WriteLine("BitsPerFrame: " + BitsPerFrame.ToString());
Debug.WriteLine("ImageWidth: " + ImageWidth.ToString());
Debug.WriteLine("ImageHeight: " + ImageHeight.ToString());
Debug.WriteLine("TotalFrames: " + TotalFrames.ToString());
Debug.WriteLine("_bestBlocksArrayUsed: " + _bestBlocksArrayUsed.ToString());
Debug.WriteLine("BlockSizeBits: " + BlockSizeBits.ToString());
Debug.WriteLine("DeltaOption: " + DeltaCalculationOption.ToString());
Debug.WriteLine("UseOptimalBlockChain: " + UseOptimalBlockChain.ToString());
Debug.WriteLine("SplitToSquares: " + SplitToSquares.ToString());
Debug.WriteLine("WidthOfSquare: " + WidthOfSquare.ToString());
Debug.WriteLine("Header bits: {0}", _headerBits);
*/
_cancellationToken = token;
_cancellationToken?.ThrowIfCancellationRequested();
// Let's start from the Preparation stage
UpdateStatus(CompressionStage.Preparation, 0);
// Read the source data and cache the parameters that don't change during the compression
PrepareFrames();
CheckCompressionCanceled();
if (CheckCompressionError()) return;
// I used this while optimizing the performance of the algorithms
//var watch = Stopwatch.StartNew();
// Multithreaded search for the best blocks
if (_bestBlocksArrayUsed && !UseOptimalBlockChain)
{
_bestBlocks = new DistributedBlock[TotalFrames];
_bestBlocksBufferEWH = new EventWaitHandle(false, EventResetMode.AutoReset);
// We could use Parallel.For for this purpose...
/*
UInt32 framesDone = 0;
List<Task> tasks = new List<Task>();
ParallelOptions parallelOptions = new ParallelOptions();
// We can limit the number of threads, but we don't have to:
//parallelOptions.MaxDegreeOfParallelism = Environment.ProcessorCount;
Parallel.For(0, TotalFrames, parallelOptions, i =>
{
FindBestBlock((UInt32)i);
//Interlocked.Increment(ref framesDone);
framesDone++;
UpdateStatus(CompressionStage.Preparation, framesDone);
});
*/
// But it is much more interesting (and a little faster) to run
// an async multithreaded search procedure and start building a chain of blocks in parallel!
_waitForTasksFinished = true;
FillBestBlocksArray();
}
// Сheck if the last operation was canceled or an error occurred
CheckCompressionCanceled();
if (CheckCompressionError()) return;
// Process data analysis (building a chain of blocks).
UpdateStatus(CompressionStage.Analysis, 0);
var mainBlockChain = UseOptimalBlockChain ? BuildOptimalBlocks() : SmartBuildBlocks(0, TotalFrames);
// Compressing stage
UpdateStatus(CompressionStage.Compression, 0);
for (int i = 0; i < mainBlockChain.Count; i++)
{
// First, check whether the compression cancellation has been requested
CheckCompressionCanceled();
if (CheckCompressionError()) return; // Or some read/write error happened
// Use this for debugging purposes
/*
for (int j = 0; j < ChannelsCount; j++)
{
bool afw = false;
byte realMethod = GetRealMethod(mainBlockChain[i].Methods[j], BitsPerChannel[j], ref afw);
Debug.Write(String.Format("{0}{1}, {3}, ", afw ? 'A' : 'F', realMethod,
mainBlockChain[i].Methods[j], mainBlockChain[i].InitialValues[j]));
}
Debug.WriteLine("Start: {0}, End: {1}, Length: {2}", mainBlockChain[i].StartFrame,
mainBlockChain[i].StartFrame + mainBlockChain[i].Length, mainBlockChain[i].Length);
*/
CompressBlock(mainBlockChain[i]);
UpdateStatus(CompressionStage.Compression, mainBlockChain[i].StartFrame + mainBlockChain[i].Length);
}
// Check if some read/write error happened
if (CheckCompressionError()) return;
// Flush the bits buffer
FinalizeCompressedData();
// Performance check
//Debug.WriteLine("\nTotal duration: {0:0.00}s", (double)watch.ElapsedMilliseconds / 1000.0d);
// Done!
UpdateStatus(CompressionStage.Done, TotalFrames);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Private methods
////////////////////////////////////////////////////////////////////////////////////////////////////
// Auxiliary functions
// Check if cancellation was requested and throw exception if so
private void CheckCompressionCanceled()
{
if ((_cancellationToken != null) && _cancellationToken.Value.IsCancellationRequested)
{
UpdateStatus(CompressionStage.Cancelled, 0);
// Let's wait until the tasks of searching for the best blocks are finished
while (_waitForTasksFinished)
{
Thread.Sleep(Constants.WaitForTasksSleepDuration);
}
_cancellationToken?.ThrowIfCancellationRequested();
}
}
private bool CheckCompressionError()
{
if (_fallIntoErrorRequested)
{
UpdateStatus(CompressionStage.Failed, 0);
return (true);
}
return (false);
}
// Calculate the size of the header fields in bits
private void CalculateHeaderBits()
{
// The header of the Method contains only its description w/o any real data
_headerBits = _blockSizeBits;
for (byte c = 0; c < ChannelsCount; c++)
{
BitsPerMethodDeclaration[c] = 0;
byte currentChannelMethodsCount = (byte)(GetMethodsCount(c) - 1);
do
{
BitsPerMethodDeclaration[c]++;
}
while ((currentChannelMethodsCount >>= 1) > 0);
_headerBits += BitsPerMethodDeclaration[c];
}
}
// Get the number of methods depending on the delta calculation options used
private byte GetMethodsCount(byte channel)
{
if ((DeltaCalculationOption == DeltaOption.FixedWindowFirst) ||
(DeltaCalculationOption == DeltaOption.AdaptiveFloatingWindowFirst))
{
return (byte)(BitsPerChannel[channel] * 2);
} else
{
return (byte)(BitsPerChannel[channel] + 1);
}
}
// Get the real method (windows width) and delta option
// depending on the delta calculation options used
// (please refer to the links in the header).
private byte GetRealMethod(byte method, byte bitDepth, ref bool afw)
{
afw = false;
if (method > bitDepth)
{
method -= bitDepth;
if (DeltaCalculationOption == DeltaOption.FixedWindowFirst) afw = true;
}
else if ((method > 0) && (method < bitDepth))
{
if ((DeltaCalculationOption == DeltaOption.AdaptiveFloatingWindowOnly) ||
(DeltaCalculationOption == DeltaOption.AdaptiveFloatingWindowFirst)) afw = true;
}
return (method);
}
// Update data analysis progress
private void UpdateStatus(CompressionStage currentStage, UInt32 frameProgress)
{
double newProgress = (double)frameProgress * 100.0d / (double)TotalFrames;
if ((Stage != currentStage) || ((newProgress - Progress) > Constants.MinProgressIcrease) || (frameProgress == TotalFrames))
{
Stage = currentStage;
if ((currentStage != CompressionStage.Cancelled) &&
(currentStage != CompressionStage.Failed)) Progress = newProgress;
// The delegate is responsible for marshalling the call to the UI thread (if needed)
_updateProgressDelegate?.Invoke(Stage, Progress);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Operations with methods and blocks
// Run a multithreaded search for the most effective blocks
// One worker per processor takes the next unprocessed position in turn, so the blocks
// are ready roughly in order and the chain building (which runs in parallel) rarely waits.
private void FillBestBlocksArray()
{
Int64 lastTakenPosition = -1;
int workersCount = Environment.ProcessorCount;
int workersRunning = workersCount;
for (int w = 0; w < workersCount; w++)
{
Task.Factory.StartNew(() =>
{
try
{
while (true)
{
// We have to check if cancellation was requested
if ((_fallIntoErrorRequested) ||
((_cancellationToken != null) && _cancellationToken.Value.IsCancellationRequested)) break;
Int64 position = Interlocked.Increment(ref lastTakenPosition);
if (position >= TotalFrames) break;
FindBestBlock((UInt32)position);
}
}
finally
{
if (Interlocked.Decrement(ref workersRunning) == 0) _waitForTasksFinished = false;
}
}, TaskCreationOptions.LongRunning);
}
}
// Build blocks for a frames range using serial efficiency analysis.
// This one is a little bit complicated, so I'm referring you once again
// to the links at the top of file.
private List<Block> SmartBuildBlocks(UInt32 startFrame, UInt32 boundary)
{
var mainBlockChain = new List<Block>();
var alterBlockChain = new List<Block>();
double alterBlockChainEfficiency = double.MinValue;
UInt32 currentPosition = startFrame;
Block mainBlock = new Block() { StartFrame = 0, Length = 0, Efficiency = double.MinValue };
Block alterBlock = mainBlock;
bool lastBlockFinished = true;
bool alterBlockFound = false;
while (currentPosition < boundary)
{
// First, check whether the compression cancellation has been requested
CheckCompressionCanceled();
// Instead of searching for the best block every time
//Block currentBlock = GetBestBlock(currentPosition, boundary);
// We will better use the best blocks prepared earlier (if any)
// Single-threaded version
//Block currentBlock = ((boundary == TotalFrames) && _bestBlocksArrayUsed) ?
// _bestBlocks[currentPosition].Block : GetBestBlock(currentPosition, boundary);
// Multithreaded version
Block currentBlock;
if ((boundary == TotalFrames) && (_bestBlocksArrayUsed))
{
while (!_bestBlocks[currentPosition].Ready)
{
_bestBlocksBufferEWH.WaitOne(Constants.WaitForBestBlockReadyEventTimeout);
CheckCompressionCanceled();
}
currentBlock = _bestBlocks[currentPosition].Block;
}
else
{
currentBlock = GetBestBlock(currentPosition, boundary);
}
if (lastBlockFinished)
{
mainBlock = currentBlock;
alterBlockChainEfficiency = currentBlock.Efficiency;
currentPosition++;
lastBlockFinished = false;
}
else
if (mainBlock.Efficiency < currentBlock.Efficiency)
{
alterBlockChain.Clear();
Block mainBlockHead = mainBlock;
mainBlockHead.Length = currentPosition - mainBlock.StartFrame;
alterBlockChain.Add(mainBlockHead);
alterBlockChain.Add(currentBlock);
if ((mainBlock.StartFrame + mainBlock.Length) > (currentBlock.StartFrame + currentBlock.Length))
{
Block mainBlockTail = mainBlock;
mainBlockTail.StartFrame = currentBlock.StartFrame + currentBlock.Length;
mainBlockTail.Length = mainBlock.StartFrame + mainBlock.Length - mainBlockTail.StartFrame;
alterBlockChain.Add(mainBlockTail);
/*
// Searching for a new block instead of the tail of the base block is a bad idea
Block bestTailBlock = GetBestBlock(currentBlock.StartFrame + currentBlock.Length,
mainBlock.StartFrame + mainBlock.Length);
alterBlockChain.Add(bestTailBlock);
*/
}
else
{ // This option also makes things worse.
//currentBlock.Length = mainBlock.StartFrame + mainBlock.Length - currentBlock.StartFrame;
//alterBlockChain[1] = currentBlock;
}
double currentBlockChainEfficiency = GetChainEfficiency(alterBlockChain);
if (currentBlockChainEfficiency > alterBlockChainEfficiency)
{
alterBlockChainEfficiency = currentBlockChainEfficiency;
alterBlock = alterBlockChain[0];
alterBlockFound = true;
}
}
currentPosition++;
if (currentPosition >= mainBlock.StartFrame + mainBlock.Length)
{
if (alterBlockFound)
{
currentPosition = alterBlock.StartFrame + alterBlock.Length;
mainBlockChain.AddRange(SmartBuildBlocks(alterBlock.StartFrame, currentPosition));
}
else
{
mainBlockChain.Add(mainBlock);
}
alterBlockFound = false;
lastBlockFinished = true;
UpdateStatus(CompressionStage.Analysis, currentPosition);
}
}
return (mainBlockChain);
}
// Build the chain of blocks with the minimum total size in bits.
//
// Let Best(p) be the smallest size of the data from frame p to the end. Then
// Best(p) = min over l of [ Bits(p, l) + Best(p + l) ],
// where Bits(p, l) is the smallest block of exactly l frames starting at p. Going backwards
// from the end gives the optimal chain for the chosen block size field and square size.
//
// Bits(p, l) is cheap: for each channel the cheapest method that lasts at least l frames is
// the narrowest Fixed window that still fits, the narrowest Adaptive window that still fits,
// or no compression, and the narrowest fitting window only grows with l.
// Since Bits(p, l) never decreases with l, the search over l stops as soon as Bits(p, l)
// alone is not smaller than the best total found so far.
private List<Block> BuildOptimalBlocks()
{
UInt32[] bestLength = new UInt32[TotalFrames];
FindOptimalChain(bestLength, true);
var lengths = new ChannelMethodLengths(this);
// Restore the chain
var chain = new List<Block>();
for (UInt32 position = 0; position < TotalFrames; position += bestLength[position])
{
UInt32 length = bestLength[position];
lengths.Calculate(position);
lengths.ResetCursors();
Block block = new Block()
{
StartFrame = position,
Length = length,
Methods = new byte[ChannelsCount],
InitialValues = new UInt32[ChannelsCount]
};
for (byte c = 0; c < ChannelsCount; c++)
{
lengths.GetMinCost(c, length, out byte method);
block.Methods[c] = method;
block.InitialValues[c] = lengths.GetInitialValue(c, method);
}
block.Efficiency = GetBlockEfficiency(length, block.Methods);
chain.Add(block);
}
return (chain);
}
// The dynamic programming pass of BuildOptimalBlocks(): returns the minimum total size of the
// compressed data in bits and (optionally) the length of the first block of the optimal chain
// for every position.
private UInt64 FindOptimalChain(UInt32[]? bestLength, bool reportProgress)
{
if (_frames == null) PrepareFrames();
UInt64[] best = new UInt64[TotalFrames + 1];
var lengths = new ChannelMethodLengths(this);
for (Int64 p = (Int64)TotalFrames - 1; p >= 0; p--)
{
if ((p & 0xFFF) == 0)
{
CheckCompressionCanceled();
if (reportProgress) UpdateStatus(CompressionStage.Analysis, (UInt32)(TotalFrames - p));
}
UInt32 position = (UInt32)p;
lengths.CalculateBackward(position);
UInt32 maxLength = (UInt32)Math.Min((UInt64)_maxBlockSize, (UInt64)TotalFrames - position);
UInt64 bestBits = UInt64.MaxValue;
UInt32 bestBlockLength = 0;
lengths.ResetCursors();
// Bits(p, l) is piecewise linear in l, so we go segment by segment: within a segment
// every channel keeps its cheapest method and Bits(p, l) = a + s * l.
UInt32 l = 1;
bool done = false;
while (!done && (l <= maxLength))
{
UInt64 a = _headerBits, slope = 0;
UInt32 segmentEnd = maxLength;
for (byte c = 0; c < ChannelsCount; c++)
{
lengths.GetCostLine(c, l, maxLength, out UInt64 channelA, out UInt64 channelSlope, out UInt32 channelEnd);
a += channelA;
slope += channelSlope;
if (channelEnd < segmentEnd) segmentEnd = channelEnd;
}
UInt64 bits = a + slope * l;
UInt32 index = position + l;
for (; l <= segmentEnd; l++, index++, bits += slope)
{
if (bits >= bestBits) { done = true; break; }
UInt64 total = bits + best[index];
if (total < bestBits)
{
bestBits = total;
bestBlockLength = l;
}
}
}
best[position] = bestBits;
if (bestLength != null) bestLength[position] = bestBlockLength;
}
return (best[0]);
}
// Lengths of all methods of all channels for one start position, plus the cheapest
// method lookup for a growing block length (see BuildOptimalBlocks()).
private sealed class ChannelMethodLengths
{
private readonly Compressor _compressor;
private readonly UInt32[][] _fixedLengths, _fixedInitialValues, _adaptiveLengths;
private readonly sbyte[][] _fixedMethodIndex, _adaptiveMethodIndex; // real window -> method index (-1 if unused)
private readonly byte[] _fixedCursor, _adaptiveCursor;
private UInt32 _position;
public ChannelMethodLengths(Compressor compressor)
{
_compressor = compressor;
int channels = compressor.ChannelsCount;
_fixedLengths = new UInt32[channels][];
_fixedInitialValues = new UInt32[channels][];
_adaptiveLengths = new UInt32[channels][];
_fixedMethodIndex = new sbyte[channels][];
_adaptiveMethodIndex = new sbyte[channels][];
_fixedCursor = new byte[channels];
_adaptiveCursor = new byte[channels];
for (byte c = 0; c < channels; c++)
{
byte bitDepth = compressor.BitsPerChannel[c];
_fixedLengths[c] = new UInt32[Constants.MaxBitsPerChannel];
_fixedInitialValues[c] = new UInt32[Constants.MaxBitsPerChannel];
_adaptiveLengths[c] = new UInt32[Constants.MaxBitsPerChannel];
_fixedMethodIndex[c] = Enumerable.Repeat((sbyte)-1, bitDepth).ToArray();
_adaptiveMethodIndex[c] = Enumerable.Repeat((sbyte)-1, bitDepth).ToArray();
for (byte m = 0; m < compressor._methodsCount[c]; m++)
{
bool afw = false;
byte realMethod = compressor.GetRealMethod(m, bitDepth, ref afw);
if (realMethod == bitDepth) continue; // no compression
if (afw) _adaptiveMethodIndex[c][realMethod] = (sbyte)m;
else _fixedMethodIndex[c][realMethod] = (sbyte)m;
}
}
}
// Incremental version of Calculate() for the backward pass: must be called for
// TotalFrames - 1, TotalFrames - 2, ..., 0 in turn. O(number of methods) per position (amortized)
// instead of scanning the data:
// - a Fixed window block [p, end) stays valid when p moves left only if the range still fits,
// so 'end' only moves left too, and the min/max of the block are kept in monotonic deques;
// - an Adaptive window block breaks at the first pair of neighboring frames that doesn't fit,
// so we only need to know where the next such pair is.
public void CalculateBackward(UInt32 position)
{
_position = position;
UInt32 totalFrames = _compressor.TotalFrames;
UInt32 maxBlockSize = _compressor._maxBlockSize;
if (_backward == null)
{
_backward = new BackwardState[_compressor.ChannelsCount];
for (byte c = 0; c < _compressor.ChannelsCount; c++) _backward[c] = new BackwardState(_compressor, c);
}
for (byte c = 0; c < _compressor.ChannelsCount; c++)
{
BackwardState state = _backward[c];
byte bitDepth = _compressor.BitsPerChannel[c];
ReadOnlySpan<UInt32> frames = _compressor._frames[c];