Skip to content

Commit cfd288c

Browse files
committed
Clean up, use constants instead of magic numbers where possible
1 parent 91f6a15 commit cfd288c

32 files changed

Lines changed: 160 additions & 180 deletions

‎src/ImageSharp.Textures/Compression/Astc/AstcDecoder.cs‎

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,7 @@ private interface IBandSerializer<TElement>
4949

5050
/// <summary>
5151
/// Decodes ASTC blocks read from <paramref name="source"/> and writes the RGBA32 result to
52-
/// <paramref name="destination"/>, one block-row band at a time. Only a single band of
53-
/// compressed blocks and decoded pixels is held in memory, so peak usage is independent of
54-
/// the image height.
52+
/// <paramref name="destination"/>, one block-row band at a time.
5553
/// </summary>
5654
/// <param name="source">The stream containing ASTC-compressed block data.</param>
5755
/// <param name="destination">The stream to write RGBA32 pixels to, row-major.</param>
@@ -72,9 +70,7 @@ public static void DecompressImage(Stream source, Stream destination, int width,
7270

7371
/// <summary>
7472
/// Asynchronously decodes ASTC blocks read from <paramref name="source"/> and writes the
75-
/// RGBA32 result to <paramref name="destination"/>, one block-row band at a time. Only a
76-
/// single band is held in memory; <see cref="Stream.ReadAsync(Memory{byte}, CancellationToken)"/>
77-
/// and <see cref="Stream.WriteAsync(ReadOnlyMemory{byte}, CancellationToken)"/> drive the I/O.
73+
/// RGBA32 result to <paramref name="destination"/>, one block-row band at a time.
7874
/// </summary>
7975
/// <param name="source">The stream containing ASTC-compressed block data.</param>
8076
/// <param name="destination">The stream to write RGBA32 pixels to, row-major.</param>
@@ -99,8 +95,7 @@ public static Task DecompressImageAsync(
9995
/// <summary>
10096
/// Decodes ASTC blocks read from <paramref name="source"/> and writes the RGBA float result
10197
/// to <paramref name="destination"/> as little-endian IEEE-754 values, one block-row band at
102-
/// a time. Only a single band of compressed blocks and decoded pixels is held in memory, so
103-
/// peak usage is independent of the image height. For HDR content, values may exceed 1.0.
98+
/// a time. For HDR content, values may exceed 1.0.
10499
/// </summary>
105100
/// <param name="source">The stream containing ASTC-compressed block data.</param>
106101
/// <param name="destination">The stream to write little-endian RGBA float pixels to, row-major.</param>
@@ -122,7 +117,7 @@ public static void DecompressHdrImage(Stream source, Stream destination, int wid
122117
/// <summary>
123118
/// Asynchronously decodes ASTC blocks read from <paramref name="source"/> and writes the RGBA
124119
/// float result to <paramref name="destination"/> as little-endian IEEE-754 values, one
125-
/// block-row band at a time. Only a single band is held in memory.
120+
/// block-row band at a time.
126121
/// </summary>
127122
/// <param name="source">The stream containing ASTC-compressed block data.</param>
128123
/// <param name="destination">The stream to write little-endian RGBA float pixels to, row-major.</param>
@@ -177,8 +172,7 @@ private static void DecodeBlockRow<TPipeline, T>(
177172
// in the LDR profile, must produce the error colour (magenta) for every texel.
178173
if (!info.IsValid || !pipeline.IsBlockLegal(in info))
179174
{
180-
pipeline.WriteErrorColorClipped(
181-
footprint, dest.DstBaseX, dest.DstBaseY, dest.CopyWidth, dest.CopyHeight, destinationWidth, destination);
175+
pipeline.WriteErrorColorClipped(footprint, dest.DstBaseX, dest.DstBaseY, dest.CopyWidth, dest.CopyHeight, destinationWidth, destination);
182176
continue;
183177
}
184178

@@ -191,8 +185,7 @@ private static void DecodeBlockRow<TPipeline, T>(
191185
/// non-void-extent blocks (the common shape per ASTC spec §C.2.10, §C.2.20, §C.2.23) take
192186
/// the fused fast path — directly to the band buffer when the block fits entirely inside
193187
/// the band, or to a scratch buffer at edges that need cropping. Everything else
194-
/// (void-extent, multi-partition, dual-plane) falls through to the general
195-
/// <see cref="LogicalBlock"/> pipeline.
188+
/// (void-extent, multi-partition, dual-plane) falls through to the general <see cref="LogicalBlock"/> pipeline.
196189
/// </summary>
197190
[MethodImpl(MethodImplOptions.AggressiveInlining)]
198191
private static void DecodeBlock<TPipeline, T>(
@@ -245,7 +238,7 @@ private static void ValidateStreamDecodeArgs(int width, int height)
245238
/// Streams a decode from <paramref name="source"/> to <paramref name="destination"/> one
246239
/// block-row band at a time, serialising each band with <typeparamref name="TSerializer"/>.
247240
/// Peak memory is one band of compressed blocks, one band of decoded pixels, one per-block
248-
/// scratch buffer, and one band of serialised output — all independent of the image height.
241+
/// scratch buffer, and one band of serialised output - all independent of the image height.
249242
/// </summary>
250243
private static void DecodeToStream<TPipeline, TElement, TSerializer>(
251244
Stream source, Stream destination, int width, int height, Footprint footprint)
@@ -353,6 +346,7 @@ private static BlockDestination ComputeBlockDestination(int blockX, int blockY,
353346
int copyWidth = Math.Min(footprint.Width, width - dstBaseX);
354347
int copyHeight = Math.Min(footprint.Height, height - dstBaseY);
355348
bool isFullInterior = copyWidth == footprint.Width && copyHeight == footprint.Height;
349+
356350
return new BlockDestination(dstBaseX, dstBaseY, copyWidth, copyHeight, isFullInterior);
357351
}
358352

‎src/ImageSharp.Textures/Compression/Astc/BiseEncoding/BitStream.cs‎

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -32,14 +32,14 @@ public BitStream(UInt128 data, uint dataSize)
3232

3333
public void PutBits(ulong value, int size)
3434
{
35-
if (this.dataSize + (uint)size > 128)
35+
if (this.dataSize + (uint)size > BlockInfo.SizeInBits)
3636
{
3737
throw new InvalidOperationException("Not enough space in BitStream");
3838
}
3939

40-
if (this.dataSize < 64)
40+
if (this.dataSize < UInt128Extensions.HalfBits)
4141
{
42-
int lowFree = (int)(64 - this.dataSize);
42+
int lowFree = (int)(UInt128Extensions.HalfBits - this.dataSize);
4343
if (size <= lowFree)
4444
{
4545
this.low |= (value & MaskFor(size)) << (int)this.dataSize;
@@ -52,7 +52,7 @@ public void PutBits(ulong value, int size)
5252
}
5353
else
5454
{
55-
int shift = (int)(this.dataSize - 64);
55+
int shift = (int)(this.dataSize - UInt128Extensions.HalfBits);
5656
this.high |= (value & MaskFor(size)) << shift;
5757
}
5858

@@ -67,6 +67,7 @@ public bool TryGetBits(int count, out UInt128 bits)
6767
{
6868
UInt128? result = this.GetBitsUInt128(count);
6969
bits = result ?? default;
70+
7071
return result is not null;
7172
}
7273

@@ -81,10 +82,11 @@ public bool TryGetBits(int count, out ulong bits)
8182
bits = count switch
8283
{
8384
0 => 0,
84-
<= 64 => this.low & MaskFor(count),
85+
<= UInt128Extensions.HalfBits => this.low & MaskFor(count),
8586
_ => this.low
8687
};
8788
this.ShiftBuffer(count);
89+
8890
return true;
8991
}
9092

@@ -99,15 +101,16 @@ public bool TryGetBits(int count, out uint bits)
99101
bits = (uint)(count switch
100102
{
101103
0 => 0UL,
102-
<= 64 => this.low & MaskFor(count),
104+
<= UInt128Extensions.HalfBits => this.low & MaskFor(count),
103105
_ => this.low
104106
});
105107
this.ShiftBuffer(count);
108+
106109
return true;
107110
}
108111

109112
private static ulong MaskFor(int bits)
110-
=> bits == 64
113+
=> bits == UInt128Extensions.HalfBits
111114
? ~0UL
112115
: ((1UL << bits) - 1UL);
113116

@@ -121,11 +124,9 @@ private static ulong MaskFor(int bits)
121124
UInt128 result = count switch
122125
{
123126
0 => UInt128.Zero,
124-
<= 64 => (UInt128)(this.low & MaskFor(count)),
125-
128 => new UInt128(this.high, this.low),
126-
_ => new UInt128(
127-
(count - 64 == 64) ? this.high : (this.high & MaskFor(count - 64)),
128-
this.low)
127+
<= UInt128Extensions.HalfBits => (UInt128)(this.low & MaskFor(count)),
128+
BlockInfo.SizeInBits => new UInt128(this.high, this.low),
129+
_ => new UInt128((count - UInt128Extensions.HalfBits == UInt128Extensions.HalfBits) ? this.high : (this.high & MaskFor(count - UInt128Extensions.HalfBits)), this.low)
129130
};
130131

131132
this.ShiftBuffer(count);
@@ -143,19 +144,19 @@ private void ShiftBuffer(int count)
143144
return;
144145
}
145146

146-
if (count < 64)
147+
if (count < UInt128Extensions.HalfBits)
147148
{
148-
this.low = (this.low >> count) | (this.high << (64 - count));
149+
this.low = (this.low >> count) | (this.high << (UInt128Extensions.HalfBits - count));
149150
this.high >>= count;
150151
}
151-
else if (count == 64)
152+
else if (count == UInt128Extensions.HalfBits)
152153
{
153154
this.low = this.high;
154155
this.high = 0;
155156
}
156-
else if (count < 128)
157+
else if (count < BlockInfo.SizeInBits)
157158
{
158-
this.low = this.high >> (count - 64);
159+
this.low = this.high >> (count - UInt128Extensions.HalfBits);
159160
this.high = 0;
160161
}
161162
else

‎src/ImageSharp.Textures/Compression/Astc/BiseEncoding/BoundedIntegerSequenceCodec.cs‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,8 +137,6 @@ public static (BiseEncodingMode Mode, int BitCount) GetPackingModeBitCount(int r
137137
/// <summary>
138138
/// Unchecked variant of <see cref="GetPackingModeBitCount"/> for hot-path use where
139139
/// <paramref name="range"/> is known to be in [1, 255] (the ASTC spec-valid range).
140-
/// Skips argument validation — about two branches per call, which add up on the ~500K
141-
/// BISE-decode calls a typical image requires.
142140
/// </summary>
143141
internal static (BiseEncodingMode Mode, int BitCount) GetPackingModeBitCountUnchecked(int range)
144142
=> PackingModeCache[range];

‎src/ImageSharp.Textures/Compression/Astc/BiseEncoding/BoundedIntegerSequenceDecoder.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// Licensed under the Six Labors Split License.
33

44
using System.Runtime.CompilerServices;
5+
using SixLabors.ImageSharp.Textures.Compression.Astc.Core;
56

67
namespace SixLabors.ImageSharp.Textures.Compression.Astc.BiseEncoding;
78

@@ -26,7 +27,7 @@ public static void Decode(BiseEncodingMode encoding, int bitCount, int valuesCou
2627
{
2728
int totalBitCount = BoundedIntegerSequenceCodec.GetBitCount(encoding, valuesCount, bitCount);
2829
int bitsPerBlock = BoundedIntegerSequenceCodec.GetEncodedBlockSize(encoding, bitCount);
29-
Guard.MustBeLessThan(bitsPerBlock, 64, nameof(bitsPerBlock));
30+
Guard.MustBeLessThan(bitsPerBlock, UInt128Extensions.HalfBits, nameof(bitsPerBlock));
3031

3132
// Fixed 5 ints (20 bytes) — one BISE block holds at most 5 trits or 3 quints (spec §C.2.12).
3233
Span<int> blockResult = stackalloc int[5];

‎src/ImageSharp.Textures/Compression/Astc/BlockDecoding/BlockModeDecoder.cs‎

Lines changed: 28 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,16 @@ namespace SixLabors.ImageSharp.Textures.Compression.Astc.BlockDecoding;
1616
/// </summary>
1717
internal static class BlockModeDecoder
1818
{
19+
// Spec §C.2.11: a block may encode at most 64 weights (grid width × height, doubled for
20+
// dual plane), and the packed weight bit count must fall within [24, 96].
21+
private const int MaxWeightCount = 64;
22+
private const int MinWeightBitCount = 24;
23+
private const int MaxWeightBitCount = 96;
24+
25+
// Void-extent texel coordinates (spec §C.2.23) are 13-bit values; all-ones is the sentinel
26+
// for "no constraint".
27+
private const int VoidExtentCoordinateBits = 13;
28+
1929
// Spec §C.2.10 Table C.2.7: weight range table indexed by r[2:0] + h. Entries marked -1
2030
// are reserved and reject the block. Two six-entry groups (low precision, high precision).
2131
private static ReadOnlySpan<int> WeightRanges
@@ -77,15 +87,15 @@ public static BlockInfo Decode(UInt128 bits)
7787
}
7888

7989
// Fixed 4 entries (max partition count per spec §C.2.10)
80-
Span<ColorEndpointMode> cems = stackalloc ColorEndpointMode[4];
90+
Span<ColorEndpointMode> cems = stackalloc ColorEndpointMode[BlockInfo.MaxPartitionCount];
8191
int colorValuesCount = DecodeEndpointModes(bits, lowBits, partitionCount, weightBitCount, cems, out int numExtraCEMBits);
82-
if (colorValuesCount is < 0 or > 18)
92+
if (colorValuesCount is < 0 or > BlockInfo.MaxColorValues)
8393
{
8494
return default;
8595
}
8696

8797
// Dual plane and color bit positions depend on weight + extra-CEM bit allocation.
88-
int dualPlaneBitStartPos = 128 - weightBitCount - numExtraCEMBits;
98+
int dualPlaneBitStartPos = BlockInfo.SizeInBits - weightBitCount - numExtraCEMBits;
8999
if (isDualPlane)
90100
{
91101
dualPlaneBitStartPos -= 2;
@@ -251,14 +261,14 @@ private static bool TryComputeWeightBitCount(
251261
}
252262

253263
// 4 partitions + dual plane is illegal per spec §C.2.11.
254-
if (numWeights > 64 || (partitionCount == 4 && isDualPlane))
264+
if (numWeights > MaxWeightCount || (partitionCount == BlockInfo.MaxPartitionCount && isDualPlane))
255265
{
256266
weightBitCount = 0;
257267
return false;
258268
}
259269

260270
weightBitCount = BoundedIntegerSequenceCodec.GetBitCountForRange(numWeights, weightRange);
261-
return weightBitCount is >= 24 and <= 96;
271+
return weightBitCount is >= MinWeightBitCount and <= MaxWeightBitCount;
262272
}
263273

264274
/// <summary>
@@ -274,9 +284,9 @@ private static int DecodeEndpointModes(
274284
int partitionCount,
275285
int weightBitCount,
276286
Span<ColorEndpointMode> cems,
277-
out int numExtraCEMBits)
287+
out int extraCEMBitCount)
278288
{
279-
numExtraCEMBits = 0;
289+
extraCEMBitCount = 0;
280290

281291
if (partitionCount == 1)
282292
{
@@ -300,10 +310,10 @@ private static int DecodeEndpointModes(
300310
return colorValuesCount;
301311
}
302312

303-
numExtraCEMBits = ExtraCemBitsForPartition[partitionCount - 1];
313+
extraCEMBitCount = ExtraCemBitsForPartition[partitionCount - 1];
304314

305-
int extraCemStartPos = 128 - numExtraCEMBits - weightBitCount;
306-
UInt128 extraCem = BitOperations.GetBits(bits, extraCemStartPos, numExtraCEMBits);
315+
int extraCemStartPos = BlockInfo.SizeInBits - extraCEMBitCount - weightBitCount;
316+
UInt128 extraCem = BitOperations.GetBits(bits, extraCemStartPos, extraCEMBitCount);
307317

308318
ulong cemval = (lowBits >> 23) & 0x3F;
309319
int baseCem = (int)(((cemval & 0x3) - 1) * 4);
@@ -312,7 +322,7 @@ private static int DecodeEndpointModes(
312322

313323
// 1 selector bit per partition (c[i]), then 2 mode bits per partition (m).
314324
// Fixed 4 ints (16 bytes) — max partition count per spec §C.2.10.
315-
Span<int> c = stackalloc int[4];
325+
Span<int> c = stackalloc int[BlockInfo.MaxPartitionCount];
316326
for (int i = 0; i < partitionCount; i++)
317327
{
318328
c[i] = (int)(cembits & 0x1);
@@ -383,14 +393,14 @@ private static bool IsVoidExtentWellFormed(UInt128 bits, ulong lowBits)
383393
return false;
384394
}
385395

386-
int c0 = (int)BitOperations.GetBits(lowBits, 12, 13);
387-
int c1 = (int)BitOperations.GetBits(lowBits, 25, 13);
388-
int c2 = (int)BitOperations.GetBits(lowBits, 38, 13);
389-
int c3 = (int)BitOperations.GetBits(lowBits, 51, 13);
396+
int c0 = (int)BitOperations.GetBits(lowBits, 12, VoidExtentCoordinateBits);
397+
int c1 = (int)BitOperations.GetBits(lowBits, 25, VoidExtentCoordinateBits);
398+
int c2 = (int)BitOperations.GetBits(lowBits, 38, VoidExtentCoordinateBits);
399+
int c3 = (int)BitOperations.GetBits(lowBits, 51, VoidExtentCoordinateBits);
390400

391-
const int all1s = (1 << 13) - 1;
392-
bool coordsAll1s = c0 == all1s && c1 == all1s && c2 == all1s && c3 == all1s;
401+
const int allOnes = (1 << VoidExtentCoordinateBits) - 1;
402+
bool allOnesCoordinates = c0 == allOnes && c1 == allOnes && c2 == allOnes && c3 == allOnes;
393403

394-
return coordsAll1s || (c0 < c1 && c2 < c3);
404+
return allOnesCoordinates || (c0 < c1 && c2 < c3);
395405
}
396406
}

‎src/ImageSharp.Textures/Compression/Astc/BlockDecoding/FusedBlockDecoder.cs‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ private static void DecodeBiseSequence(UInt128 source, int range, int count, Spa
107107
ulong lowBits = source.Low();
108108
int totalBits = count * bitsPerValue;
109109

110-
if (totalBits <= 64)
110+
if (totalBits <= UInt128Extensions.HalfBits)
111111
{
112112
for (int i = 0; i < count; i++)
113113
{
@@ -122,19 +122,19 @@ private static void DecodeBiseSequence(UInt128 source, int range, int count, Spa
122122
int bitPos = 0;
123123
for (int i = 0; i < count; i++)
124124
{
125-
if (bitPos < 64)
125+
if (bitPos < UInt128Extensions.HalfBits)
126126
{
127127
ulong val = (lowBits >> bitPos) & mask;
128-
if (bitPos + bitsPerValue > 64)
128+
if (bitPos + bitsPerValue > UInt128Extensions.HalfBits)
129129
{
130-
val |= (highBits << (64 - bitPos)) & mask;
130+
val |= (highBits << (UInt128Extensions.HalfBits - bitPos)) & mask;
131131
}
132132

133133
result[i] = (int)val;
134134
}
135135
else
136136
{
137-
result[i] = (int)((highBits >> (bitPos - 64)) & mask);
137+
result[i] = (int)((highBits >> (bitPos - UInt128Extensions.HalfBits)) & mask);
138138
}
139139

140140
bitPos += bitsPerValue;

0 commit comments

Comments
 (0)