Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
3 changes: 1 addition & 2 deletions src/ImageSharp/ColorProfiles/KnownXybTransforms.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ namespace SixLabors.ImageSharp.ColorProfiles;
/// </summary>
/// <remarks>
/// The standard coefficients are fixed. A JPEG XL image header can supply custom inverse coefficients and biases.
/// See the <see href="https://jpeg.org/jpegxl/workplan.html">JPEG XL specifications</see> and the
/// <see href="https://raw.githubusercontent.com/libjxl/libjxl/main/lib/jxl/cms/opsin_params.h">reference coefficients</see>.
/// See the <see href="https://jpeg.org/jpegxl/workplan.html">JPEG XL specifications</see>.
/// </remarks>
public static class KnownXybTransforms
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ public OotfOperator(float gamma, Vector3 luminance)
this.power = new(exponent);
this.luminance = luminance;

// The shared contract retains the identity tolerance and scale limit used by libjxl HlgOOTF_Base.
// The shared contract retains the identity tolerance and scale limit used by libjxl.
// Prepare this decision once; every RGB layout then applies the same luminance policy.
this.apply = MathF.Abs(exponent) > IdentityGammaTolerance;
}
Expand Down
4 changes: 2 additions & 2 deletions src/ImageSharp/ColorProfiles/WorkingSpaces/RgbWorkingSpace.cs
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,8 @@ private static Matrix4x4 CreateRgbToCieXyzMatrix(CieXyz referenceWhite, RgbPrima

// A primary defines the XYZ direction (x, y, 1-x-y), not an absolute luminance.
// Retain unit-Y rows for nonzero y so existing matrices keep their arithmetic.
// A zero-y primary still defines a valid direction, such as the X and Z basis
// primaries accepted by OpenEXR's RGBtoXYZ. Keep its homogeneous row instead of dividing by zero.
// A zero-y primary still defines a valid direction, such as the X and Z basis primaries that OpenEXR accepts.
// Keep its homogeneous row instead of dividing by zero.
float divisorR = yr == 0F ? 1F : yr;
float divisorG = yg == 0F ? 1F : yg;
float divisorB = yb == 0F ? 1F : yb;
Expand Down
26 changes: 21 additions & 5 deletions src/ImageSharp/ColorProfiles/Xyb.cs
Original file line number Diff line number Diff line change
Expand Up @@ -788,8 +788,8 @@ public InverseOperator(XybTransform transform, RgbWorkingSpace target, bool gray
RgbWorkingSpace source = KnownRgbWorkingSpaces.SRgb;
if (grayscale)
{
// libjxl dec_xyb.cc uses the BT.709 luminance row for D65 gray output. Repeat its
// column so the existing three-component inverse produces the same gray in X, Y and Z.
// D65 gray output uses the BT.709 luminance row, as in libjxl.
// Repeat its column so the existing three-component inverse produces the same gray in X, Y and Z.
Vector4 luminance = ColorNumerics.Bt709;
Matrix4x4 gray = new(
luminance.X,
Expand All @@ -813,14 +813,13 @@ public InverseOperator(XybTransform transform, RgbWorkingSpace target, bool gray
}
else if (!target.WhitePoint.Equals(source.WhitePoint) || !target.ChromaticityCoordinates.Equals(source.ChromaticityCoordinates))
{
// Both RGB spaces connect through D50-adapted XYZ, as in libjxl dec_xyb.cc.
// Both RGB spaces connect through D50-adapted XYZ, as in libjxl.
// Row vectors therefore use absorbance * sRGB-to-XYZ-D50 * XYZ-D50-to-target.
// Keep the default sRGB path above free of matrix products that would change its rounding.
Matrix4x4 adaptation = KnownChromaticAdaptationMatrices.Bradford;
_ = Matrix4x4.Invert(adaptation, out Matrix4x4 inverseAdaptation);
Matrix4x4 sourceToD50 = AdaptToD50(source, adaptation, inverseAdaptation);
Matrix4x4 targetToD50 = AdaptToD50(target, adaptation, inverseAdaptation);
if (!Matrix4x4.Invert(targetToD50, out Matrix4x4 d50ToTarget))
if (!TryGetD50ToTargetMatrix(target, out Matrix4x4 d50ToTarget))
{
throw new ArgumentException("The target RGB primaries must produce an invertible matrix.", nameof(target));
}
Expand All @@ -835,6 +834,23 @@ public InverseOperator(XybTransform transform, RgbWorkingSpace target, bool gray
this.cubeRootBiases = transform.CubeRootBiases;
}

/// <summary>
/// Gets the matrix from D50-adapted XYZ to the target RGB coordinates.
/// </summary>
/// <remarks>
/// The constructor for the selected linear RGB coordinates uses this matrix. A decoder can call this method first to find target primaries that do not
/// produce an invertible matrix, with the same arithmetic.
/// </remarks>
/// <param name="target">The target RGB working space.</param>
/// <param name="d50ToTarget">The matrix in row-vector order.</param>
/// <returns><see langword="true"/> if the target primaries produce an invertible matrix. Otherwise <see langword="false"/>.</returns>
public static bool TryGetD50ToTargetMatrix(RgbWorkingSpace target, out Matrix4x4 d50ToTarget)
{
Matrix4x4 adaptation = KnownChromaticAdaptationMatrices.Bradford;
_ = Matrix4x4.Invert(adaptation, out Matrix4x4 inverseAdaptation);
return Matrix4x4.Invert(AdaptToD50(target, adaptation, inverseAdaptation), out d50ToTarget);
}

/// <summary>
/// Adapts each RGB primary's XYZ contribution to the common D50 connection white.
/// </summary>
Expand Down
6 changes: 3 additions & 3 deletions src/ImageSharp/ColorProfiles/XybTransform.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,9 @@ private XybTransform(XybTransform source, Matrix4x4 rgbToXyz, Matrix4x4 xyzToRgb
// Public matrices contain row-major coefficients. Transpose them for System.Numerics row vectors,
// then scale relative RGB so one represents IntensityTarget nits. Compose the XYZ connection here,
// when options prepare the transform, rather than multiplying matrices for every scalar color or bulk block.
// libjxl dec_xyb.cc composes the output-space matrix before InitSIMDInverseMatrix applies
// the intensity factor. Scaling first rounds each inverse coefficient before cancellation
// in the matrix product. Keep that setup order while all arithmetic remains float.
// Compose the output-space matrix before the intensity factor applies, as libjxl does.
// Scaling first rounds each inverse coefficient before cancellation in the matrix product.
// Keep that setup order while all arithmetic remains float.
Matrix4x4 inverse = Matrix4x4.Transpose(source.Inverse);
this.Inverse = (inverse * rgbToXyz) * (ReferenceIntensity / source.IntensityTarget);

Expand Down
39 changes: 21 additions & 18 deletions src/ImageSharp/Compression/Ccitt/ModifiedHuffmanRowDecoder.cs
Original file line number Diff line number Diff line change
@@ -1,32 +1,39 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.

using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.IO;

namespace SixLabors.ImageSharp.Compression.Ccitt;

/// <summary>
/// Decodes rows of 1-bit pixels from TIFF compression 2 data. The data has the Modified Huffman run codes of ITU-T T.4,
/// but no EOL codes. Each row starts on a byte boundary of the compressed data. See TIFF 6.0 specification, section 10,
/// pages 43-44: https://www.itu.int/itudoc/itu-t/com16/tiff-fx/docs/tiff6.pdf
/// Decodes rows of 1-bit pixels from TIFF compression 2 data. The data has the Modified Huffman run codes of ITU-T T.4, but no EOL codes. Each row starts on a
/// byte boundary of the compressed data. See TIFF 6.0 specification, section 10, pages 43-44: https://www.itu.int/itudoc/itu-t/com16/tiff-fx/docs/tiff6.pdf
/// </summary>
/// <remarks>
/// <para>
/// A row bit is 1 for a black pixel of the code and 0 for a white pixel. The photometric interpretation of the format
/// gives the displayed colors. For example, TIFF reverses the meaning of white and black for BlackIsZero data. See
/// TIFF 6.0 specification, section 10, page 44: https://www.itu.int/itudoc/itu-t/com16/tiff-fx/docs/tiff6.pdf
/// A row bit is 1 for a black pixel of the code and 0 for a white pixel. The photometric interpretation of the format gives the displayed colors. For example,
/// TIFF reverses the meaning of white and black for BlackIsZero data. See TIFF 6.0 specification, section 10, page 44:
/// https://www.itu.int/itudoc/itu-t/com16/tiff-fx/docs/tiff6.pdf
/// </para>
/// <para>
/// The decoder does not throw for data that is not valid. It sets <see cref="IsDamaged"/>, so the caller can apply the
/// segment integrity mode of the decode.
/// In the Strict and IgnoreAncillary modes, the decoder throws for damaged data and for data that ends before a row. In the IgnoreImageData mode, the rows keep
/// their decoded pixels.
/// </para>
/// </remarks>
internal sealed class ModifiedHuffmanRowDecoder
{
/// <summary>
/// The message for damaged data.
/// </summary>
private const string DamagedMessage = "The CCITT Modified Huffman data is damaged or ends before the last row of the strip, tile or image.";

private CcittBitReader reader;

private readonly int width;

private readonly SegmentIntegrityHandling integrityHandling;

private bool isFirstRow = true;

/// <summary>
Expand All @@ -36,18 +43,14 @@ internal sealed class ModifiedHuffmanRowDecoder
/// <param name="bitOrder">The order of the code bits in each byte.</param>
/// <param name="byteCount">The number of bytes to read from the stream.</param>
/// <param name="width">The number of pixels in each row.</param>
public ModifiedHuffmanRowDecoder(BufferedReadStream stream, CcittBitOrder bitOrder, int byteCount, int width)
/// <param name="integrityHandling">The segment integrity mode of the decode. It selects what happens with damaged data.</param>
public ModifiedHuffmanRowDecoder(BufferedReadStream stream, CcittBitOrder bitOrder, int byteCount, int width, SegmentIntegrityHandling integrityHandling)
{
this.reader = new CcittBitReader(stream, bitOrder, byteCount);
this.width = width;
this.integrityHandling = integrityHandling;
}

/// <summary>
/// Gets a value indicating whether the data is damaged. Damaged data has a code that is not valid, a row with fewer
/// pixels than the width, or an end before a row.
/// </summary>
public bool IsDamaged { get; private set; }

/// <summary>
/// Decodes the next row. The first pixel goes to the most significant bit of the first byte. When the data ends
/// before the row, the row is not changed.
Expand All @@ -67,15 +70,15 @@ public void DecodeRow(Span<byte> row)
// decoder does. No run code starts with 8 zero bits, so this changes no valid data.
if (!this.reader.SkipEolCodes(out bool skippedRow))
{
this.IsDamaged = true;
this.integrityHandling.ThrowOrIgnoreImageDataError(DamagedMessage);
return;
}

// The row starts with bits that are no code. The reader skipped the data up to the next EOL code, so this row
// stays 0.
if (skippedRow)
{
this.IsDamaged = true;
this.integrityHandling.ThrowOrIgnoreImageDataError(DamagedMessage);
return;
}

Expand All @@ -92,7 +95,7 @@ public void DecodeRow(Span<byte> row)
this.reader.End();
}

this.IsDamaged = true;
this.integrityHandling.ThrowOrIgnoreImageDataError(DamagedMessage);
}
}
}
45 changes: 24 additions & 21 deletions src/ImageSharp/Compression/Ccitt/T4RowDecoder.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.

using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.IO;

namespace SixLabors.ImageSharp.Compression.Ccitt;
Expand All @@ -9,67 +10,69 @@ namespace SixLabors.ImageSharp.Compression.Ccitt;
/// Decodes rows of 1-bit pixels from data in the one-dimensional coding scheme of ITU-T T.4.
/// </summary>
/// <remarks>
/// An EOL code comes before the first row and after each row. Fill bits can come before each EOL code. Each row is a
/// sequence of white and black runs that alternate, and the first run is white. See ITU-T Recommendation T.4 (07/2003),
/// section 4.1, pages 3-4: https://www.itu.int/rec/T-REC-T.4
/// An EOL code comes before the first row and after each row. Fill bits can come before each EOL code. Each row is a sequence of white and black runs that
/// alternate, and the first run is white. See ITU-T Recommendation T.4 (07/2003), section 4.1, pages 3-4: https://www.itu.int/rec/T-REC-T.4
/// <para>
/// A row bit is 1 for a black pixel of the code and 0 for a white pixel. The photometric interpretation of the format
/// gives the displayed colors. For example, TIFF reverses the meaning of white and black for BlackIsZero data. See
/// TIFF 6.0 specification, section 10, page 44: https://www.itu.int/itudoc/itu-t/com16/tiff-fx/docs/tiff6.pdf
/// A row bit is 1 for a black pixel of the code and 0 for a white pixel. The photometric interpretation of the format gives the displayed colors. For example,
/// TIFF reverses the meaning of white and black for BlackIsZero data. See TIFF 6.0 specification, section 10, page 44:
/// https://www.itu.int/itudoc/itu-t/com16/tiff-fx/docs/tiff6.pdf
/// </para>
/// <para>
/// The decoder does not throw for data that is not valid. A code that is not valid ends the row. A run that is longer
/// than the row also ends the row. The decoder then continues after the next EOL code and sets
/// <see cref="IsDamaged"/>. Thus the caller can apply the segment integrity mode of the decode.
/// A code that is not valid ends the row. A run that is longer than the row also ends the row. The decoder then continues after the next EOL code. In the
/// Strict and IgnoreAncillary modes, the decoder throws for such damage and for data that ends before a row. In the IgnoreImageData mode, the rows keep their
/// decoded pixels.
/// </para>
/// </remarks>
internal sealed class T4RowDecoder
{
/// <summary>
/// The message for damaged data.
/// </summary>
private const string DamagedMessage = "The CCITT T.4 data is damaged or ends before the last row of the strip, tile or image.";

private CcittBitReader reader;

private readonly int width;

private readonly SegmentIntegrityHandling integrityHandling;

/// <summary>
/// Initializes a new instance of the <see cref="T4RowDecoder"/> class.
/// </summary>
/// <param name="stream">The compressed input stream.</param>
/// <param name="bitOrder">The order of the code bits in each byte.</param>
/// <param name="byteCount">The number of bytes to read from the stream.</param>
/// <param name="width">The number of pixels in each row.</param>
public T4RowDecoder(BufferedReadStream stream, CcittBitOrder bitOrder, int byteCount, int width)
/// <param name="integrityHandling">The segment integrity mode of the decode. It selects what happens with damaged data.</param>
public T4RowDecoder(BufferedReadStream stream, CcittBitOrder bitOrder, int byteCount, int width, SegmentIntegrityHandling integrityHandling)
{
this.reader = new CcittBitReader(stream, bitOrder, byteCount);
this.width = width;
this.integrityHandling = integrityHandling;
}

/// <summary>
/// Gets a value indicating whether the data is damaged. Damaged data has a code that is not valid, a row with fewer
/// pixels than the width, or an end before a row.
/// </summary>
public bool IsDamaged { get; private set; }

/// <summary>
/// Decodes the next row. The first pixel goes to the most significant bit of the first byte.
/// </summary>
/// <param name="row">The destination row. It holds at least (width + 7) / 8 bytes, and all of its bits are 0.</param>
/// <returns>
/// <see langword="true"/> if the data has codes for the row. <see langword="false"/> if the data ended before the
/// row. Then the row is not changed.
/// <see langword="true"/> if the data has codes for the row. <see langword="false"/> if the data ended before the row. The method then does not change the
/// row, and the caller stops.
/// </returns>
public bool DecodeRow(Span<byte> row)
{
// The EOL code before the row, and the fill bits before it, separate the row from the row above.
if (!this.reader.SkipEolCodes(out bool skippedRow))
{
this.IsDamaged = true;
this.integrityHandling.ThrowOrIgnoreImageDataError(DamagedMessage);
return false;
}

// The row starts with bits that are no code. The reader skipped the row data up to the next EOL code. Thus this
// row stays 0, and the next row decodes into its own place.
if (skippedRow)
{
this.IsDamaged = true;
this.integrityHandling.ThrowOrIgnoreImageDataError(DamagedMessage);
return true;
}

Expand All @@ -85,7 +88,7 @@ public bool DecodeRow(Span<byte> row)
this.reader.SkipToEol();
}

this.IsDamaged = true;
this.integrityHandling.ThrowOrIgnoreImageDataError(DamagedMessage);
}

return true;
Expand Down
Loading
Loading