Skip to content

Commit

Permalink
add workaround for WIC JPEG bug
Browse files Browse the repository at this point in the history
  • Loading branch information
saucecontrol committed Dec 4, 2024
1 parent 1a58f2b commit 971cec0
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/MagicScaler/Magic/InvertTransform.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Copyright © Clinton Ingram and Contributors
// SPDX-License-Identifier: MIT

using PhotoSauce.MagicScaler.Converters;

namespace PhotoSauce.MagicScaler.Transforms;

internal sealed class InvertTransform(PixelSource source) : ChainedPixelSource(source)
{
protected override unsafe void CopyPixelsInternal(in PixelArea prc, int cbStride, int cbBufferSize, byte* pbBuffer)
{
Profiler.PauseTiming();
PrevSource.CopyPixels(prc, cbStride, cbBufferSize, pbBuffer);
Profiler.ResumeTiming();

nint cb = prc.Width * PrevSource.Format.BytesPerPixel;
for (int y = 0; y < prc.Height; y++)
{
InvertConverter.InvertLine(pbBuffer, cb);
pbBuffer += cbStride;
}
}

public override string ToString() => nameof(InvertTransform);
}
21 changes: 21 additions & 0 deletions src/MagicScaler/Magic/MagicTransforms.cs
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,27 @@ public static void AddCropper(PipelineContext ctx)
return;
}

// Workaround for WIC JPEG decoder bug https://github.com/saucecontrol/wic-jpeg-bug
var src = ctx.Source;
if (src is WicFramePixelSource && src.Format == PixelFormat.Cmyk32 && src.Width != crop.Width)
{
using var buff = BufferPool.RentLocal<byte>(src.Width * src.Format.BytesPerPixel);
unsafe
{
fixed (byte* pBuff = buff)
{
src.CopyPixels(src.Area.Slice(crop.Y, 1), buff.Length, buff.Length, pBuff);
uint rpix = *((uint*)pBuff + crop.X);

src.CopyPixels(crop.Slice(0, 1), buff.Length, buff.Length, pBuff);
uint cpix = *(uint*)pBuff;

if (cpix == ~rpix)
ctx.Source = ctx.AddProfiler(new InvertTransform(src));
}
}
}

ctx.Source = ctx.AddProfiler(new CropTransform(ctx.Source, crop));
}

Expand Down

0 comments on commit 971cec0

Please sign in to comment.