Repository navigation
Expand file tree
/
Copy pathArithmeticScanDecoder.cs
More file actions
1255 lines (1073 loc) · 42.9 KB
/
Copy pathArithmeticScanDecoder.cs
File metadata and controls
1255 lines (1073 loc) · 42.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
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
#nullable disable
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using SixLabors.ImageSharp.IO;
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
namespace SixLabors.ImageSharp.Formats.Jpeg.Components.Decoder;
/// <summary>
/// Decodes a arithmetic encoded spectral scan.
/// Based on https://github.com/yigolden/JpegLibrary/blob/main/src/JpegLibrary/ScanDecoder/JpegArithmeticScanDecoder.cs
/// </summary>
internal class ArithmeticScanDecoder : IJpegScanDecoder
{
private readonly BufferedReadStream stream;
private int c;
private int a;
private int ct;
/// <summary>
/// <see cref="JpegFrame"/> instance containing decoding-related information.
/// </summary>
private JpegFrame frame;
/// <summary>
/// Shortcut for <see cref="frame"/>.Components.
/// </summary>
private IJpegComponent[] components;
/// <summary>
/// Number of component in the current scan.
/// </summary>
private int scanComponentCount;
/// <summary>
/// The reset interval determined by RST markers.
/// </summary>
private int restartInterval;
/// <summary>
/// How many mcu's are left to do.
/// </summary>
private int todo;
private readonly SpectralConverter spectralConverter;
private JpegBitReader scanBuffer;
private ArithmeticDecodingTable[] dcDecodingTables;
private ArithmeticDecodingTable[] acDecodingTables;
// Don't make this a ReadOnlySpan<byte>, as the values need to get updated.
private InlineArray4<byte> fixedBin;
private readonly CancellationToken cancellationToken;
private static readonly int[] ArithmeticTable =
[
Pack(0x5a1d, 1, 1, 1),
Pack(0x2586, 14, 2, 0),
Pack(0x1114, 16, 3, 0),
Pack(0x080b, 18, 4, 0),
Pack(0x03d8, 20, 5, 0),
Pack(0x01da, 23, 6, 0),
Pack(0x00e5, 25, 7, 0),
Pack(0x006f, 28, 8, 0),
Pack(0x0036, 30, 9, 0),
Pack(0x001a, 33, 10, 0),
Pack(0x000d, 35, 11, 0),
Pack(0x0006, 9, 12, 0),
Pack(0x0003, 10, 13, 0),
Pack(0x0001, 12, 13, 0),
Pack(0x5a7f, 15, 15, 1),
Pack(0x3f25, 36, 16, 0),
Pack(0x2cf2, 38, 17, 0),
Pack(0x207c, 39, 18, 0),
Pack(0x17b9, 40, 19, 0),
Pack(0x1182, 42, 20, 0),
Pack(0x0cef, 43, 21, 0),
Pack(0x09a1, 45, 22, 0),
Pack(0x072f, 46, 23, 0),
Pack(0x055c, 48, 24, 0),
Pack(0x0406, 49, 25, 0),
Pack(0x0303, 51, 26, 0),
Pack(0x0240, 52, 27, 0),
Pack(0x01b1, 54, 28, 0),
Pack(0x0144, 56, 29, 0),
Pack(0x00f5, 57, 30, 0),
Pack(0x00b7, 59, 31, 0),
Pack(0x008a, 60, 32, 0),
Pack(0x0068, 62, 33, 0),
Pack(0x004e, 63, 34, 0),
Pack(0x003b, 32, 35, 0),
Pack(0x002c, 33, 9, 0),
Pack(0x5ae1, 37, 37, 1),
Pack(0x484c, 64, 38, 0),
Pack(0x3a0d, 65, 39, 0),
Pack(0x2ef1, 67, 40, 0),
Pack(0x261f, 68, 41, 0),
Pack(0x1f33, 69, 42, 0),
Pack(0x19a8, 70, 43, 0),
Pack(0x1518, 72, 44, 0),
Pack(0x1177, 73, 45, 0),
Pack(0x0e74, 74, 46, 0),
Pack(0x0bfb, 75, 47, 0),
Pack(0x09f8, 77, 48, 0),
Pack(0x0861, 78, 49, 0),
Pack(0x0706, 79, 50, 0),
Pack(0x05cd, 48, 51, 0),
Pack(0x04de, 50, 52, 0),
Pack(0x040f, 50, 53, 0),
Pack(0x0363, 51, 54, 0),
Pack(0x02d4, 52, 55, 0),
Pack(0x025c, 53, 56, 0),
Pack(0x01f8, 54, 57, 0),
Pack(0x01a4, 55, 58, 0),
Pack(0x0160, 56, 59, 0),
Pack(0x0125, 57, 60, 0),
Pack(0x00f6, 58, 61, 0),
Pack(0x00cb, 59, 62, 0),
Pack(0x00ab, 61, 63, 0),
Pack(0x008f, 61, 32, 0),
Pack(0x5b12, 65, 65, 1),
Pack(0x4d04, 80, 66, 0),
Pack(0x412c, 81, 67, 0),
Pack(0x37d8, 82, 68, 0),
Pack(0x2fe8, 83, 69, 0),
Pack(0x293c, 84, 70, 0),
Pack(0x2379, 86, 71, 0),
Pack(0x1edf, 87, 72, 0),
Pack(0x1aa9, 87, 73, 0),
Pack(0x174e, 72, 74, 0),
Pack(0x1424, 72, 75, 0),
Pack(0x119c, 74, 76, 0),
Pack(0x0f6b, 74, 77, 0),
Pack(0x0d51, 75, 78, 0),
Pack(0x0bb6, 77, 79, 0),
Pack(0x0a40, 77, 48, 0),
Pack(0x5832, 80, 81, 1),
Pack(0x4d1c, 88, 82, 0),
Pack(0x438e, 89, 83, 0),
Pack(0x3bdd, 90, 84, 0),
Pack(0x34ee, 91, 85, 0),
Pack(0x2eae, 92, 86, 0),
Pack(0x299a, 93, 87, 0),
Pack(0x2516, 86, 71, 0),
Pack(0x5570, 88, 89, 1),
Pack(0x4ca9, 95, 90, 0),
Pack(0x44d9, 96, 91, 0),
Pack(0x3e22, 97, 92, 0),
Pack(0x3824, 99, 93, 0),
Pack(0x32b4, 99, 94, 0),
Pack(0x2e17, 93, 86, 0),
Pack(0x56a8, 95, 96, 1),
Pack(0x4f46, 101, 97, 0),
Pack(0x47e5, 102, 98, 0),
Pack(0x41cf, 103, 99, 0),
Pack(0x3c3d, 104, 100, 0),
Pack(0x375e, 99, 93, 0),
Pack(0x5231, 105, 102, 0),
Pack(0x4c0f, 106, 103, 0),
Pack(0x4639, 107, 104, 0),
Pack(0x415e, 103, 99, 0),
Pack(0x5627, 105, 106, 1),
Pack(0x50e7, 108, 107, 0),
Pack(0x4b85, 109, 103, 0),
Pack(0x5597, 110, 109, 0),
Pack(0x504f, 111, 107, 0),
Pack(0x5a10, 110, 111, 1),
Pack(0x5522, 112, 109, 0),
Pack(0x59eb, 112, 111, 1),
// This last entry is used for fixed probability estimate of 0.5
// as suggested in Section 10.3 Table 5 of ITU-T Rec. T.851.
Pack(0x5a1d, 113, 113, 0)
];
private readonly List<ArithmeticStatistics> statistics = [];
/// <summary>
/// Initializes a new instance of the <see cref="ArithmeticScanDecoder"/> class.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="converter">Spectral to pixel converter.</param>
/// <param name="cancellationToken">The token to monitor cancellation.</param>
public ArithmeticScanDecoder(BufferedReadStream stream, SpectralConverter converter, CancellationToken cancellationToken)
{
this.stream = stream;
this.spectralConverter = converter;
this.cancellationToken = cancellationToken;
// Inline storage is zero-initialized with the decoder; only the arithmetic probability state starts nonzero.
this.fixedBin[0] = 113;
this.c = 0;
this.a = 0;
this.ct = -16; // Force reading 2 initial bytes to fill C.
}
/// <inheritdoc/>
public SegmentIntegrityHandling SegmentIntegrityHandling { get; set; }
/// <inheritdoc/>
public int ResetInterval
{
set
{
this.restartInterval = value;
this.todo = value;
}
}
/// <inheritdoc/>
public int SpectralStart { get; set; }
/// <inheritdoc/>
public int SpectralEnd { get; set; }
/// <inheritdoc/>
public int SuccessiveHigh { get; set; }
/// <inheritdoc/>
public int SuccessiveLow { get; set; }
public void InitDecodingTables(List<ArithmeticDecodingTable> arithmeticDecodingTables)
{
for (int i = 0; i < this.components.Length; i++)
{
ArithmeticDecodingComponent component = this.components[i] as ArithmeticDecodingComponent;
this.dcDecodingTables[i] = GetArithmeticTable(arithmeticDecodingTables, true, component.DcTableId);
component.DcStatistics = this.CreateOrGetStatisticsBin(true, component.DcTableId);
this.acDecodingTables[i] = GetArithmeticTable(arithmeticDecodingTables, false, component.AcTableId);
component.AcStatistics = this.CreateOrGetStatisticsBin(false, component.AcTableId);
}
}
private ref byte GetFixedBinReference() => ref this.fixedBin[0];
/// <inheritdoc/>
public void ParseEntropyCodedData(int scanComponentCount, IccProfile iccProfile)
{
this.cancellationToken.ThrowIfCancellationRequested();
this.scanComponentCount = scanComponentCount;
this.scanBuffer = new JpegBitReader(this.stream);
this.frame.AllocateComponents();
if (this.frame.Progressive)
{
this.ParseProgressiveData();
}
else
{
this.ParseBaselineData(iccProfile);
}
if (this.scanBuffer.HasBadMarker())
{
this.stream.Position = this.scanBuffer.MarkerPosition;
}
}
/// <inheritdoc/>
public void InjectFrameData(JpegFrame frame, IRawJpegData jpegData)
{
this.frame = frame;
this.components = frame.Components;
this.dcDecodingTables = new ArithmeticDecodingTable[this.components.Length];
this.acDecodingTables = new ArithmeticDecodingTable[this.components.Length];
this.spectralConverter.InjectFrameData(frame, jpegData);
}
/// <summary>
/// Gets the declared conditioning table or stores the JPEG defaults for an undeclared table.
/// </summary>
/// <param name="arithmeticDecodingTables">The conditioning tables for this image.</param>
/// <param name="isDcTable">True for a DC table. False for an AC table.</param>
/// <param name="identifier">The table identifier selected by the component.</param>
/// <returns>The declared table or a table with the standard default values.</returns>
private static ArithmeticDecodingTable GetArithmeticTable(List<ArithmeticDecodingTable> arithmeticDecodingTables, bool isDcTable, int identifier)
{
int tableClass = isDcTable ? 0 : 1;
foreach (ArithmeticDecodingTable item in arithmeticDecodingTables)
{
if (item.TableClass == tableClass && item.Identifier == identifier)
{
return item;
}
}
// Omitted DAC entries are valid. Cache the defaults so later scans reuse the table without another allocation.
// A later DAC segment replaces this entry through the existing table-update path.
ArithmeticDecodingTable table = new((byte)tableClass, (byte)identifier);
arithmeticDecodingTables.Add(table);
return table;
}
private ArithmeticStatistics CreateOrGetStatisticsBin(bool dc, int identifier, bool reset = false)
{
foreach (ArithmeticStatistics item in this.statistics)
{
if (item.IsDcStatistics == dc && item.Identifier == identifier)
{
if (reset)
{
item.Reset();
}
return item;
}
}
ArithmeticStatistics statistic = new(dc, identifier);
this.statistics.Add(statistic);
return statistic;
}
private void ParseBaselineData(IccProfile iccProfile)
{
for (int i = 0; i < this.components.Length; i++)
{
ArithmeticDecodingComponent component = (ArithmeticDecodingComponent)this.components[i];
component.DcPredictor = 0;
component.DcContext = 0;
component.DcStatistics?.Reset();
component.AcStatistics?.Reset();
}
this.Reset();
if (this.scanComponentCount != 1)
{
this.spectralConverter.PrepareForDecoding();
this.ParseBaselineDataInterleaved(iccProfile);
this.spectralConverter.CommitConversion();
}
else if (this.frame.ComponentCount == 1)
{
this.spectralConverter.PrepareForDecoding();
this.ParseBaselineDataSingleComponent(iccProfile);
this.spectralConverter.CommitConversion();
}
else
{
this.ParseBaselineDataNonInterleaved();
}
}
private void ParseProgressiveData()
{
this.CheckProgressiveData();
for (int i = 0; i < this.components.Length; i++)
{
ArithmeticDecodingComponent component = (ArithmeticDecodingComponent)this.components[i];
if (this.SpectralStart == 0 && this.SuccessiveHigh == 0)
{
component.DcPredictor = 0;
component.DcContext = 0;
component.DcStatistics?.Reset();
}
if (this.SpectralStart != 0)
{
component.AcStatistics?.Reset();
}
}
this.Reset();
if (this.scanComponentCount == 1)
{
this.ParseProgressiveDataNonInterleaved();
}
else
{
this.ParseProgressiveDataInterleaved();
}
}
private void CheckProgressiveData()
{
// Validate successive scan parameters.
// Logic has been adapted from libjpeg.
// See Table B.3 – Scan header parameter size and values. itu-t81.pdf
bool invalid = false;
if (this.SpectralStart == 0)
{
if (this.SpectralEnd != 0)
{
invalid = true;
}
}
else
{
// Need not check Ss/Se < 0 since they came from unsigned bytes.
if (this.SpectralEnd < this.SpectralStart || this.SpectralEnd > 63)
{
invalid = true;
}
// AC scans may have only one component.
if (this.scanComponentCount != 1)
{
invalid = true;
}
}
if (this.SuccessiveHigh != 0)
{
// Successive approximation refinement scan: must have Al = Ah-1.
if (this.SuccessiveHigh - 1 != this.SuccessiveLow)
{
invalid = true;
}
}
// TODO: How does this affect 12bit jpegs.
// According to libjpeg the range covers 8bit only?
if (this.SuccessiveLow > 13)
{
invalid = true;
}
if (invalid)
{
JpegThrowHelper.ThrowBadProgressiveScan(this.SpectralStart, this.SpectralEnd, this.SuccessiveHigh, this.SuccessiveLow);
}
}
private void ParseBaselineDataInterleaved(IccProfile iccProfile)
{
int mcu = 0;
int mcusPerColumn = this.frame.McusPerColumn;
int mcusPerLine = this.frame.McusPerLine;
ref JpegBitReader reader = ref this.scanBuffer;
for (int j = 0; j < mcusPerColumn; j++)
{
this.cancellationToken.ThrowIfCancellationRequested();
// Decode from binary to spectral.
for (int i = 0; i < mcusPerLine; i++)
{
// Scan an interleaved mcu... process components in order.
int mcuCol = mcu % mcusPerLine;
for (int k = 0; k < this.scanComponentCount; k++)
{
int order = this.frame.ComponentOrder[k];
ArithmeticDecodingComponent component = this.components[order] as ArithmeticDecodingComponent;
ref ArithmeticDecodingTable dcDecodingTable = ref this.dcDecodingTables[component.DcTableId];
ref ArithmeticDecodingTable acDecodingTable = ref this.acDecodingTables[component.AcTableId];
int h = component.HorizontalSamplingFactor;
int v = component.VerticalSamplingFactor;
// Scan out an mcu's worth of this component; that's just determined
// by the basic H and V specified for the component.
int mcuColMulh = mcuCol * h;
for (int y = 0; y < v; y++)
{
Span<Block8x8> blockSpan = component.SpectralBlocks.DangerousGetRowSpan(y);
ref Block8x8 blockRef = ref MemoryMarshal.GetReference(blockSpan);
for (int x = 0; x < h; x++)
{
if (reader.NoData)
{
// It is very likely that some spectral data was decoded before we've encountered 'end of scan'
// so we need to decode what's left and return (or maybe throw?)
this.spectralConverter.ConvertStrideBaseline(iccProfile);
return;
}
int blockCol = mcuColMulh + x;
this.DecodeBlockBaseline(
component,
ref Unsafe.Add(ref blockRef, (uint)blockCol),
ref acDecodingTable,
ref dcDecodingTable);
}
}
}
// After all interleaved components, that's an interleaved MCU,
// so now count down the restart interval.
mcu++;
this.HandleRestart();
}
// Convert from spectral to actual pixels via given converter.
this.spectralConverter.ConvertStrideBaseline(iccProfile);
}
}
private void ParseBaselineDataSingleComponent(IccProfile iccProfile)
{
ArithmeticDecodingComponent component = this.frame.Components[0] as ArithmeticDecodingComponent;
int mcuLines = this.frame.McusPerColumn;
int w = component.WidthInBlocks;
int h = component.SamplingFactors.Height;
ref ArithmeticDecodingTable dcDecodingTable = ref this.dcDecodingTables[component.DcTableId];
ref ArithmeticDecodingTable acDecodingTable = ref this.acDecodingTables[component.AcTableId];
ref JpegBitReader reader = ref this.scanBuffer;
for (int i = 0; i < mcuLines; i++)
{
this.cancellationToken.ThrowIfCancellationRequested();
// Decode from binary to spectral.
for (int j = 0; j < h; j++)
{
Span<Block8x8> blockSpan = component.SpectralBlocks.DangerousGetRowSpan(j);
ref Block8x8 blockRef = ref MemoryMarshal.GetReference(blockSpan);
for (int k = 0; k < w; k++)
{
if (reader.NoData)
{
// It is very likely that some spectral data was decoded before we've encountered 'end of scan'
// so we need to decode what's left and return (or maybe throw?)
this.spectralConverter.ConvertStrideBaseline(iccProfile);
return;
}
this.DecodeBlockBaseline(
component,
ref Unsafe.Add(ref blockRef, (uint)k),
ref acDecodingTable,
ref dcDecodingTable);
this.HandleRestart();
}
}
// Convert from spectral to actual pixels via given converter.
this.spectralConverter.ConvertStrideBaseline(iccProfile);
}
}
private void ParseBaselineDataNonInterleaved()
{
ArithmeticDecodingComponent component = (ArithmeticDecodingComponent)this.components[this.frame.ComponentOrder[0]];
ref JpegBitReader reader = ref this.scanBuffer;
int w = component.WidthInBlocks;
int h = component.HeightInBlocks;
ref ArithmeticDecodingTable dcDecodingTable = ref this.dcDecodingTables[component.DcTableId];
ref ArithmeticDecodingTable acDecodingTable = ref this.acDecodingTables[component.AcTableId];
for (int j = 0; j < h; j++)
{
this.cancellationToken.ThrowIfCancellationRequested();
Span<Block8x8> blockSpan = component.SpectralBlocks.DangerousGetRowSpan(j);
ref Block8x8 blockRef = ref MemoryMarshal.GetReference(blockSpan);
for (int i = 0; i < w; i++)
{
if (reader.NoData)
{
return;
}
this.DecodeBlockBaseline(
component,
ref Unsafe.Add(ref blockRef, (uint)i),
ref acDecodingTable,
ref dcDecodingTable);
this.HandleRestart();
}
}
}
private void ParseProgressiveDataInterleaved()
{
int mcu = 0;
int mcusPerColumn = this.frame.McusPerColumn;
int mcusPerLine = this.frame.McusPerLine;
ref JpegBitReader reader = ref this.scanBuffer;
for (int j = 0; j < mcusPerColumn; j++)
{
for (int i = 0; i < mcusPerLine; i++)
{
// Scan an interleaved mcu... process components in order.
int mcuRow = Math.DivRem(mcu, mcusPerLine, out int mcuCol);
for (int k = 0; k < this.scanComponentCount; k++)
{
int order = this.frame.ComponentOrder[k];
ArithmeticDecodingComponent component = this.components[order] as ArithmeticDecodingComponent;
ref ArithmeticDecodingTable dcDecodingTable = ref this.dcDecodingTables[component.DcTableId];
int h = component.HorizontalSamplingFactor;
int v = component.VerticalSamplingFactor;
// Scan out an mcu's worth of this component; that's just determined
// by the basic H and V specified for the component.
int mcuColMulh = mcuCol * h;
for (int y = 0; y < v; y++)
{
int blockRow = (mcuRow * v) + y;
Span<Block8x8> blockSpan = component.SpectralBlocks.DangerousGetRowSpan(blockRow);
ref Block8x8 blockRef = ref MemoryMarshal.GetReference(blockSpan);
for (int x = 0; x < h; x++)
{
if (reader.NoData)
{
return;
}
int blockCol = mcuColMulh + x;
this.DecodeBlockProgressiveDc(
component,
ref Unsafe.Add(ref blockRef, (uint)blockCol),
ref dcDecodingTable);
}
}
}
// After all interleaved components, that's an interleaved MCU,
// so now count down the restart interval.
mcu++;
this.HandleRestart();
}
}
}
private void ParseProgressiveDataNonInterleaved()
{
ArithmeticDecodingComponent component = this.components[this.frame.ComponentOrder[0]] as ArithmeticDecodingComponent;
ref JpegBitReader reader = ref this.scanBuffer;
int w = component.WidthInBlocks;
int h = component.HeightInBlocks;
if (this.SpectralStart == 0)
{
ref ArithmeticDecodingTable dcDecodingTable = ref this.dcDecodingTables[component.DcTableId];
for (int j = 0; j < h; j++)
{
this.cancellationToken.ThrowIfCancellationRequested();
Span<Block8x8> blockSpan = component.SpectralBlocks.DangerousGetRowSpan(j);
ref Block8x8 blockRef = ref MemoryMarshal.GetReference(blockSpan);
for (int i = 0; i < w; i++)
{
if (reader.NoData)
{
return;
}
this.DecodeBlockProgressiveDc(
component,
ref Unsafe.Add(ref blockRef, (uint)i),
ref dcDecodingTable);
this.HandleRestart();
}
}
}
else
{
ref ArithmeticDecodingTable acDecodingTable = ref this.acDecodingTables[component.AcTableId];
for (int j = 0; j < h; j++)
{
this.cancellationToken.ThrowIfCancellationRequested();
Span<Block8x8> blockSpan = component.SpectralBlocks.DangerousGetRowSpan(j);
ref Block8x8 blockRef = ref MemoryMarshal.GetReference(blockSpan);
for (int i = 0; i < w; i++)
{
if (reader.NoData)
{
return;
}
this.DecodeBlockProgressiveAc(
component,
ref Unsafe.Add(ref blockRef, (uint)i),
ref acDecodingTable);
this.HandleRestart();
}
}
}
}
private void DecodeBlockProgressiveDc(ArithmeticDecodingComponent component, ref Block8x8 block, ref ArithmeticDecodingTable dcTable)
{
if (dcTable == null)
{
JpegThrowHelper.ThrowInvalidImageContentException("DC table is missing");
}
ref JpegBitReader reader = ref this.scanBuffer;
ref short blockDataRef = ref Unsafe.As<Block8x8, short>(ref block);
if (this.SuccessiveHigh == 0)
{
// First scan
// Sections F.2.4.1 & F.1.4.4.1: Decoding of DC coefficients.
// Table F.4: Point to statistics bin S0 for DC coefficient coding.
ref byte st = ref Unsafe.Add(ref component.DcStatistics.GetReference(), (uint)component.DcContext);
// Figure F.19: Decode_DC_DIFF
if (this.DecodeBinaryDecision(ref reader, ref st) == 0)
{
component.DcContext = 0;
}
else
{
// Figure F.21: Decoding nonzero value v.
// Figure F.22: Decoding the sign of v.
int sign = this.DecodeBinaryDecision(ref reader, ref Unsafe.Add(ref st, 1));
st = ref Unsafe.Add(ref st, (uint)(2 + sign));
// Figure F.23: Decoding the magnitude category of v.
int m = this.DecodeBinaryDecision(ref reader, ref st);
if (m != 0)
{
st = ref component.DcStatistics.GetReference(20);
while (this.DecodeBinaryDecision(ref reader, ref st) != 0)
{
if ((m <<= 1) == 0x8000)
{
JpegThrowHelper.ThrowInvalidImageContentException("Invalid arithmetic code.");
}
st = ref Unsafe.Add(ref st, 1);
}
}
// Section F.1.4.4.1.2: Establish dc_context conditioning category.
if (m < (int)((1L << dcTable.DcL) >> 1))
{
component.DcContext = 0; // Zero diff category.
}
else if (m > (int)((1L << dcTable.DcU) >> 1))
{
component.DcContext = 12 + (sign * 4); // Large diff category.
}
else
{
component.DcContext = 4 + (sign * 4); // Small diff category.
}
int v = m;
// Figure F.24: Decoding the magnitude bit pattern of v.
st = ref Unsafe.Add(ref st, 14);
while ((m >>= 1) != 0)
{
if (this.DecodeBinaryDecision(ref reader, ref st) != 0)
{
v |= m;
}
}
v++;
if (sign != 0)
{
v = -v;
}
component.DcPredictor = (short)(component.DcPredictor + v);
}
blockDataRef = (short)(component.DcPredictor << this.SuccessiveLow);
}
else
{
// Refinement scan.
ref byte st = ref this.GetFixedBinReference();
blockDataRef |= (short)(this.DecodeBinaryDecision(ref reader, ref st) << this.SuccessiveLow);
}
}
private void DecodeBlockProgressiveAc(ArithmeticDecodingComponent component, ref Block8x8 block, ref ArithmeticDecodingTable acTable)
{
ref JpegBitReader reader = ref this.scanBuffer;
ref short blockDataRef = ref Unsafe.As<Block8x8, short>(ref block);
ArithmeticStatistics acStatistics = component.AcStatistics;
if (acStatistics == null || acTable == null)
{
JpegThrowHelper.ThrowInvalidImageContentException("AC table is missing");
}
if (this.SuccessiveHigh == 0)
{
// Sections F.2.4.2 & F.1.4.4.2: Decoding of AC coefficients.
// Figure F.20: Decode_AC_coefficients.
int start = this.SpectralStart;
int end = this.SpectralEnd;
int low = this.SuccessiveLow;
for (int k = start; k <= end; k++)
{
ref byte st = ref acStatistics.GetReference(3 * (k - 1));
if (this.DecodeBinaryDecision(ref reader, ref st) != 0)
{
break;
}
while (this.DecodeBinaryDecision(ref reader, ref Unsafe.Add(ref st, 1)) == 0)
{
st = ref Unsafe.Add(ref st, 3);
k++;
if (k > 63)
{
JpegThrowHelper.ThrowInvalidImageContentException("Invalid arithmetic code.");
}
}
// Figure F.21: Decoding nonzero value v.
// Figure F.22: Decoding the sign of v.
int sign = this.DecodeBinaryDecision(ref reader, ref this.GetFixedBinReference());
st = ref Unsafe.Add(ref st, 2);
// Figure F.23: Decoding the magnitude category of v.
int m = this.DecodeBinaryDecision(ref reader, ref st);
if (m != 0)
{
if (this.DecodeBinaryDecision(ref reader, ref st) != 0)
{
m <<= 1;
st = ref acStatistics.GetReference(k <= acTable.AcKx ? 189 : 217);
while (this.DecodeBinaryDecision(ref reader, ref st) != 0)
{
if ((m <<= 1) == 0x8000)
{
JpegThrowHelper.ThrowInvalidImageContentException("Invalid arithmetic code.");
}
st = ref Unsafe.Add(ref st, 1);
}
}
}
int v = m;
// Figure F.24: Decoding the magnitude bit pattern of v.
st = ref Unsafe.Add(ref st, 14);
while ((m >>= 1) != 0)
{
if (this.DecodeBinaryDecision(ref reader, ref st) != 0)
{
v |= m;
}
}
v++;
if (sign != 0)
{
v = -v;
}
Unsafe.Add(ref blockDataRef, ZigZag.TransposingOrder[k]) = (short)(v << low);
}
}
else
{
// Refinement scan.
this.ReadBlockProgressiveAcRefined(acStatistics, ref blockDataRef);
}
}
private void ReadBlockProgressiveAcRefined(ArithmeticStatistics acStatistics, ref short blockDataRef)
{
ref JpegBitReader reader = ref this.scanBuffer;
int start = this.SpectralStart;
int end = this.SpectralEnd;
int p1 = 1 << this.SuccessiveLow;
int m1 = -1 << this.SuccessiveLow;
// Establish EOBx (previous stage end-of-block) index.
int kex = end;
for (; kex > 0; kex--)
{
if (Unsafe.Add(ref blockDataRef, ZigZag.TransposingOrder[kex]) != 0)
{
break;
}
}
for (int k = start; k <= end; k++)
{
ref byte st = ref acStatistics.GetReference(3 * (k - 1));
if (k > kex)
{
if (this.DecodeBinaryDecision(ref reader, ref st) != 0)
{
break;
}
}
while (true)
{
ref short coef = ref Unsafe.Add(ref blockDataRef, ZigZag.TransposingOrder[k]);
if (coef != 0)
{
if (this.DecodeBinaryDecision(ref reader, ref Unsafe.Add(ref st, 2)) != 0)
{
coef = (short)(coef + (coef < 0 ? m1 : p1));
}
break;
}
if (this.DecodeBinaryDecision(ref reader, ref Unsafe.Add(ref st, 1)) != 0)
{
bool flag = this.DecodeBinaryDecision(ref reader, ref this.GetFixedBinReference()) != 0;
coef = (short)(coef + (flag ? m1 : p1));
break;
}
st = ref Unsafe.Add(ref st, 3);
k++;
if (k > end)
{
JpegThrowHelper.ThrowInvalidImageContentException("Invalid arithmetic code.");
}
}
}
}
private void DecodeBlockBaseline(
ArithmeticDecodingComponent component,
ref Block8x8 destinationBlock,
ref ArithmeticDecodingTable acTable,
ref ArithmeticDecodingTable dcTable)
{
if (acTable is null)
{
JpegThrowHelper.ThrowInvalidImageContentException("AC table is missing.");
}
if (dcTable is null)
{
JpegThrowHelper.ThrowInvalidImageContentException("DC table is missing.");
}
ref JpegBitReader reader = ref this.scanBuffer;
ref short destinationRef = ref Unsafe.As<Block8x8, short>(ref destinationBlock);
// Sections F.2.4.1 & F.1.4.4.1: Decoding of DC coefficients.
// Table F.4: Point to statistics bin S0 for DC coefficient coding.
ref byte st = ref Unsafe.Add(ref component.DcStatistics.GetReference(), (uint)component.DcContext);
/* Figure F.19: Decode_DC_DIFF */
if (this.DecodeBinaryDecision(ref reader, ref st) == 0)
{
component.DcContext = 0;
}
else
{
// Figure F.21: Decoding nonzero value v
// Figure F.22: Decoding the sign of v
int sign = this.DecodeBinaryDecision(ref reader, ref Unsafe.Add(ref st, 1));
st = ref Unsafe.Add(ref st, (uint)(2 + sign));
// Figure F.23: Decoding the magnitude category of v.
int m = this.DecodeBinaryDecision(ref reader, ref st);
if (m != 0)
{
// Table F.4: X1 = 20
st = ref component.DcStatistics.GetReference(20);
while (this.DecodeBinaryDecision(ref reader, ref st) != 0)
{
if ((m <<= 1) == 0x8000)
{
JpegThrowHelper.ThrowInvalidImageContentException("Invalid arithmetic code.");
}