#include "../../common/common.h"

#include "inspirecv/task/planning/pixel_program.h"

#include <algorithm>
#include <array>
#include <cstdint>
#include <cstring>
#include <vector>

namespace {

using inspirecv::SUCCESS;
using inspirecv::task::BGR;
using inspirecv::task::BGR555;
using inspirecv::task::BGR565;
using inspirecv::task::BGRA;
using inspirecv::task::BILINEAR;
using inspirecv::task::CLAMP_TO_EDGE;
using inspirecv::task::GRAY;
using inspirecv::task::HSV;
using inspirecv::task::HSV_FULL;
using inspirecv::task::NEAREST;
using inspirecv::task::RGB;
using inspirecv::task::RGBA;
using inspirecv::task::StreamFormat;
using inspirecv::task::TensorLayout;
using inspirecv::task::XYZ;
using inspirecv::task::YCrCb;
using inspirecv::task::YUV;
using inspirecv::task::YUV_I420;
using inspirecv::task::YUV_NV12;
using inspirecv::task::YUV_NV21;
using inspirecv::task::internal::CompilePixelProgram;
using inspirecv::task::internal::DestinationRow;
using inspirecv::task::internal::PixelProgram;
using inspirecv::task::internal::PixelProgramSpec;
using inspirecv::task::internal::RunPixelSpan;
using inspirecv::task::internal::RunSampleSpan;
using inspirecv::task::internal::SampleLine;
using inspirecv::task::internal::SourceRow;

struct ConversionBaseline {
    StreamFormat source;
    StreamFormat destination;
    int source_channels;
    int destination_channels;
    const char* name;
    uint64_t p0_hash;
};

// Generated by the frozen P0 implementation at commit 6de3530. Each digest
// covers 257 pixels at every source and destination byte offset from 0 to 15.
constexpr std::array<ConversionBaseline, 42> kConversionBaselines = {{
  {RGBA, RGBA, 4, 4, "RGBA_RGBA", UINT64_C(0x9a32c5b93d04b983)},
  {RGBA, BGRA, 4, 4, "RGBA_BGRA", UINT64_C(0xd4321f9a51e5d583)},
  {RGBA, BGR, 4, 3, "RGBA_BGR", UINT64_C(0x1b5e7da4708b6983)},
  {RGBA, RGB, 4, 3, "RGBA_RGB", UINT64_C(0xecf025b195c7a583)},
  {RGBA, GRAY, 4, 1, "RGBA_GRAY", UINT64_C(0x7395f62512f48383)},
  {BGRA, RGBA, 4, 4, "BGRA_RGBA", UINT64_C(0xd4321f9a51e5d583)},
  {BGRA, BGRA, 4, 4, "BGRA_BGRA", UINT64_C(0x9a32c5b93d04b983)},
  {BGRA, BGR, 4, 3, "BGRA_BGR", UINT64_C(0xecf025b195c7a583)},
  {BGRA, RGB, 4, 3, "BGRA_RGB", UINT64_C(0x1b5e7da4708b6983)},
  {BGRA, GRAY, 4, 1, "BGRA_GRAY", UINT64_C(0x2b060fe0d343e283)},
  {RGB, RGB, 3, 3, "RGB_RGB", UINT64_C(0x769520adf68ecf83)},
  {RGB, BGR, 3, 3, "RGB_BGR", UINT64_C(0x67cb7ba046980f83)},
  {RGB, GRAY, 3, 1, "RGB_GRAY", UINT64_C(0x4921e21f66c45083)},
  {RGB, RGBA, 3, 4, "RGB_RGBA", UINT64_C(0xa4774243e71a9583)},
  {RGB, YCrCb, 3, 3, "RGB_YCrCb", UINT64_C(0x02f8190e593feb83)},
  {RGB, YUV, 3, 3, "RGB_YUV", UINT64_C(0xfa2556cf276ecc83)},
  {RGB, XYZ, 3, 3, "RGB_XYZ", UINT64_C(0x087028d6756ab283)},
  {RGB, HSV, 3, 3, "RGB_HSV", UINT64_C(0xd8284e854795b383)},
  {RGB, BGR555, 3, 2, "RGB_BGR555", UINT64_C(0x49f76b785f77f383)},
  {RGB, BGR565, 3, 2, "RGB_BGR565", UINT64_C(0xab630e36f9e19583)},
  {RGB, HSV_FULL, 3, 3, "RGB_HSV_FULL", UINT64_C(0xd3a52836ccc5f383)},
  {BGR, BGR, 3, 3, "BGR_BGR", UINT64_C(0x769520adf68ecf83)},
  {BGR, RGB, 3, 3, "BGR_RGB", UINT64_C(0x67cb7ba046980f83)},
  {BGR, GRAY, 3, 1, "BGR_GRAY", UINT64_C(0xe67f670b3b825f83)},
  {BGR, BGRA, 3, 4, "BGR_BGRA", UINT64_C(0xa4774243e71a9583)},
  {BGR, YCrCb, 3, 3, "BGR_YCrCb", UINT64_C(0x52db1d15869f7783)},
  {BGR, YUV, 3, 3, "BGR_YUV", UINT64_C(0x8a356a78d79f6483)},
  {BGR, XYZ, 3, 3, "BGR_XYZ", UINT64_C(0xfb90de14b8ec3e83)},
  {BGR, HSV, 3, 3, "BGR_HSV", UINT64_C(0x3b356c1b9a7c8f83)},
  {BGR, BGR555, 3, 2, "BGR_BGR555", UINT64_C(0xef9aa10452304783)},
  {BGR, BGR565, 3, 2, "BGR_BGR565", UINT64_C(0xdcbe9fa352bddd83)},
  {BGR, HSV_FULL, 3, 3, "BGR_HSV_FULL", UINT64_C(0xca9408f8a7551783)},
  {GRAY, RGBA, 1, 4, "GRAY_RGBA", UINT64_C(0xe537a69ccf188383)},
  {GRAY, BGRA, 1, 4, "GRAY_BGRA", UINT64_C(0xe537a69ccf188383)},
  {GRAY, BGR, 1, 3, "GRAY_BGR", UINT64_C(0x75c5b569d7ff3083)},
  {GRAY, RGB, 1, 3, "GRAY_RGB", UINT64_C(0x75c5b569d7ff3083)},
  {GRAY, GRAY, 1, 1, "GRAY_GRAY", UINT64_C(0xbf3b9ecdb8aa1a83)},
  {YUV_NV21, GRAY, 0, 1, "NV21_GRAY", UINT64_C(0xbf3b9ecdb8aa1a83)},
  {YUV_NV21, RGB, 0, 3, "NV21_RGB", UINT64_C(0xdb933f2332aa5383)},
  {YUV_NV21, BGR, 0, 3, "NV21_BGR", UINT64_C(0x1e804df4fef32b83)},
  {YUV_NV21, RGBA, 0, 4, "NV21_RGBA", UINT64_C(0xce189c5553143583)},
  {YUV_NV21, BGRA, 0, 4, "NV21_BGRA", UINT64_C(0x5707e6a2cda44583)},
}};

struct YuvSampleBaseline {
    StreamFormat format;
    size_t width;
    size_t height;
    bool direct;
    uint64_t p0_hash;
};

// These digests freeze both the normalized NV21-style temporary layout and
// the compact odd-height chroma behavior of P0.
constexpr std::array<YuvSampleBaseline, 12> kYuvSampleBaselines = {{
  {YUV_NV21, 6, 4, true, UINT64_C(0xbf6ca434702eb383)},
  {YUV_NV21, 6, 4, false, UINT64_C(0xa81e8dd3db65d589)},
  {YUV_NV21, 5, 3, true, UINT64_C(0x28e8766d07e2da1c)},
  {YUV_NV21, 5, 3, false, UINT64_C(0xa6601932afeb1b46)},
  {YUV_NV12, 6, 4, true, UINT64_C(0xcca4628398591a05)},
  {YUV_NV12, 6, 4, false, UINT64_C(0x3386d66fd8c95d3f)},
  {YUV_NV12, 5, 3, true, UINT64_C(0x21d313130a8786fe)},
  {YUV_NV12, 5, 3, false, UINT64_C(0xd8c1632c4dba11de)},
  {YUV_I420, 6, 4, true, UINT64_C(0xaed781e66afa49d5)},
  {YUV_I420, 6, 4, false, UINT64_C(0x6e0bf9775d23007f)},
  {YUV_I420, 5, 3, true, UINT64_C(0xeee404a18079a5a4)},
  {YUV_I420, 5, 3, false, UINT64_C(0x79993367c93a5d03)},
}};

struct PackedSampleBaseline {
    StreamFormat format;
    size_t channels;
    inspirecv::task::Filter filter;
    uint64_t neon_hash;
    uint64_t sse_hash;
    uint64_t scalar_hash;
};

// P0 samplers intentionally have ISA-specific rounding in C1/C4. Keeping all
// three hashes makes those existing platform contracts explicit.
constexpr std::array<PackedSampleBaseline, 6> kPackedSampleBaselines = {{
  {GRAY, 1, NEAREST, UINT64_C(0x9e6942c5b52c1983),
   UINT64_C(0xdd5514039adb4b83), UINT64_C(0xdd5514039adb4b83)},
  {GRAY, 1, BILINEAR, UINT64_C(0xd04f8a0d05582383),
   UINT64_C(0x87fde017fca54683), UINT64_C(0x87fde017fca54683)},
  {BGR, 3, NEAREST, UINT64_C(0x1a20e2983a99a483),
   UINT64_C(0x1a20e2983a99a483), UINT64_C(0x1a20e2983a99a483)},
  {BGR, 3, BILINEAR, UINT64_C(0x667b8c97573bde83),
   UINT64_C(0x667b8c97573bde83), UINT64_C(0x667b8c97573bde83)},
  {RGBA, 4, NEAREST, UINT64_C(0x12bf63679a805b83),
   UINT64_C(0x12bf63679a805b83), UINT64_C(0xb3e5e585979c4783)},
  {RGBA, 4, BILINEAR, UINT64_C(0x44fd060310364383),
   UINT64_C(0x44fd060310364383), UINT64_C(0x8b4be7cb3cf5c783)},
}};

constexpr std::array<size_t, 13> kPixelCounts = {
  1, 2, 3, 4, 7, 8, 15, 16, 31, 32, 255, 256, 257};

PixelProgramSpec MakeSpec(StreamFormat source, StreamFormat destination,
                          int source_channels, int destination_channels,
                          halide_type_t type = halide_type_of<uint8_t>(),
                          TensorLayout layout = TensorLayout::NHWC) {
    PixelProgramSpec specification;
    specification.source_format = source;
    specification.destination_format = destination;
    specification.filter = NEAREST;
    specification.wrap = CLAMP_TO_EDGE;
    specification.destination_type = type;
    specification.destination_layout = layout;
    specification.source_channels = source_channels;
    specification.destination_channels = destination_channels;
    specification.direct_sampling = true;
    return specification;
}

uint64_t HashByte(uint64_t hash, uint8_t value) {
    return (hash ^ value) * UINT64_C(1099511628211);
}

uint32_t FloatBits(float value) {
    uint32_t bits;
    std::memcpy(&bits, &value, sizeof(bits));
    return bits;
}

uint8_t Pattern(size_t pixel, int channel) {
    return static_cast<uint8_t>((37 * pixel + 53 * static_cast<size_t>(channel) + 11) & 255);
}

}  // namespace

TEST_CASE("task_pixel_program_matches_every_p0_color_conversion",
          "[task][kernel-contract][p0-color]") {
    constexpr size_t count = 257;
    for (const ConversionBaseline& operation : kConversionBaselines) {
        CAPTURE(operation.name);
        PixelProgram program;
        REQUIRE(CompilePixelProgram(
                  MakeSpec(operation.source, operation.destination,
                           operation.source_channels, operation.destination_channels),
                  &program) == SUCCESS);
        uint64_t hash = UINT64_C(1469598103934665603);
        const size_t source_bytes = operation.source == YUV_NV21
                                      ? count + 2 * ((count + 1) / 2)
                                      : count * static_cast<size_t>(operation.source_channels);
        const size_t destination_bytes =
          count * static_cast<size_t>(operation.destination_channels);
        for (size_t source_offset = 0; source_offset < 16; ++source_offset) {
            for (size_t destination_offset = 0; destination_offset < 16;
                 ++destination_offset) {
                std::vector<uint8_t> source(source_offset + source_bytes + 16, 0xA7);
                std::vector<uint8_t> destination(destination_offset + destination_bytes + 16,
                                                 0xCD);
                for (size_t i = 0; i < source_bytes; ++i) {
                    source[source_offset + i] =
                      static_cast<uint8_t>((i * 37 + i / 3 * 19 + 11) & 255);
                }
                const SourceRow input = {
                  source.data() + source_offset, operation.source, count,
                  operation.source_channels, source_bytes};
                const DestinationRow output = {
                  destination.data() + destination_offset, TensorLayout::NHWC, count,
                  operation.destination_channels, 1, destination_bytes, 0};
                REQUIRE(RunPixelSpan(program, input, output, nullptr, nullptr,
                                     nullptr, 0) == SUCCESS);
                for (size_t i = 0; i < destination_bytes; ++i) {
                    hash = HashByte(hash, destination[destination_offset + i]);
                }
                REQUIRE(std::all_of(destination.begin(),
                                    destination.begin() + destination_offset,
                                    [](uint8_t value) { return value == 0xCD; }));
                REQUIRE(std::all_of(destination.begin() + destination_offset +
                                                        destination_bytes,
                                    destination.end(),
                                    [](uint8_t value) { return value == 0xCD; }));
            }
        }
        REQUIRE(hash == operation.p0_hash);
    }
}

TEST_CASE("task_pixel_program_matches_p0_yuv_plane_sampling",
          "[task][kernel-contract][p0-yuv]") {
    for (const YuvSampleBaseline& baseline : kYuvSampleBaselines) {
        CAPTURE(baseline.format, baseline.width, baseline.height, baseline.direct);
        PixelProgramSpec specification =
          MakeSpec(baseline.format, BGR, 0, 3);
        specification.direct_sampling = baseline.direct;
        PixelProgram program;
        REQUIRE(CompilePixelProgram(specification, &program) == SUCCESS);

        const size_t y_bytes = baseline.width * baseline.height;
        const size_t chroma_bytes =
          baseline.format == YUV_I420
            ? 2 * ((baseline.width + 1) / 2) * ((baseline.height + 1) / 2)
            : baseline.width * std::max<size_t>(1, baseline.height / 2);
        std::vector<uint8_t> source(y_bytes + chroma_bytes);
        for (size_t i = 0; i < source.size(); ++i) {
            source[i] = static_cast<uint8_t>((i * 41 + i / 2 * 17 + 23) & 255);
        }

        const size_t count = baseline.direct ? baseline.width : 9;
        const size_t result_bytes = count + 2 * ((count + 1) / 2);
        std::vector<uint8_t> destination(result_bytes + 16, 0xCD);
        const SampleLine line = {
          baseline.direct
            ? inspirecv::task::Point{0.0f, static_cast<float>(baseline.height - 1)}
            : inspirecv::task::Point{-0.25f,
                                      static_cast<float>(baseline.height) - 0.75f},
          baseline.direct ? inspirecv::task::Point{1.0f, 0.0f}
                          : inspirecv::task::Point{0.73f, -0.31f},
          0, count, count};
        REQUIRE(RunSampleSpan(program, source.data(), static_cast<int>(baseline.width),
                              static_cast<int>(baseline.height), 0,
                              line, destination.data()) == SUCCESS);
        uint64_t hash = UINT64_C(1469598103934665603);
        for (size_t i = 0; i < result_bytes; ++i) {
            hash = HashByte(hash, destination[i]);
        }
        REQUIRE(hash == baseline.p0_hash);
        REQUIRE(std::all_of(destination.begin() + result_bytes, destination.end(),
                            [](uint8_t value) { return value == 0xCD; }));
    }
}

TEST_CASE("task_pixel_program_matches_p0_packed_samplers",
          "[task][kernel-contract][p0-sampling]") {
    constexpr size_t width = 331;
    constexpr size_t height = 19;
    constexpr size_t count = 257;
    constexpr size_t first = 3;
    constexpr size_t capacity = first + count;
    for (const PackedSampleBaseline& baseline : kPackedSampleBaselines) {
        CAPTURE(baseline.format, baseline.filter);
        PixelProgramSpec specification =
          MakeSpec(baseline.format, baseline.format,
                   static_cast<int>(baseline.channels),
                   static_cast<int>(baseline.channels));
        specification.filter = baseline.filter;
        specification.direct_sampling = false;
        PixelProgram program;
        REQUIRE(CompilePixelProgram(specification, &program) == SUCCESS);

        const size_t stride = width * baseline.channels + 7;
        const size_t source_bytes = height * stride;
        uint64_t hash = UINT64_C(1469598103934665603);
        for (size_t source_offset = 0; source_offset < 16; ++source_offset) {
            for (size_t destination_offset = 0; destination_offset < 16;
                 ++destination_offset) {
                std::vector<uint8_t> source(source_offset + source_bytes + 16, 0xA7);
                std::vector<uint8_t> destination(
                  destination_offset + capacity * baseline.channels + 16, 0xCD);
                for (size_t i = 0; i < source_bytes; ++i) {
                    source[source_offset + i] =
                      static_cast<uint8_t>((i * 29 + i / 5 * 43 + 7) & 255);
                }
                const SampleLine line = {
                  {0.25f, 0.4f}, {1.17f, 0.03f}, first, count, capacity};
                REQUIRE(RunSampleSpan(program, source.data() + source_offset,
                                      width, height, static_cast<int>(stride), line,
                                      destination.data() + destination_offset) == SUCCESS);
                const size_t begin = destination_offset + first * baseline.channels;
                const size_t end = begin + count * baseline.channels;
                for (size_t i = begin; i < end; ++i) {
                    hash = HashByte(hash, destination[i]);
                }
                REQUIRE(std::all_of(destination.begin(), destination.begin() + begin,
                                    [](uint8_t value) { return value == 0xCD; }));
                REQUIRE(std::all_of(destination.begin() + end, destination.end(),
                                    [](uint8_t value) { return value == 0xCD; }));
            }
        }
#if defined(INSPIRECV_TASK_USE_NEON)
        const uint64_t expected = baseline.neon_hash;
#elif defined(INSPIRECV_TASK_USE_SSE)
        const uint64_t expected = baseline.sse_hash;
#else
        const uint64_t expected = baseline.scalar_hash;
#endif
        REQUIRE(hash == expected);
    }
}

TEST_CASE("task_pixel_program_draw_writers_fill_every_channel_width",
          "[task][kernel-contract][draw]") {
    for (const int channels : {1, 3, 4}) {
        PixelProgramSpec specification =
          MakeSpec(BGR, BGR, channels, channels);
        specification.drawing = true;
        PixelProgram program;
        REQUIRE(CompilePixelProgram(specification, &program) == SUCCESS);
        for (const size_t count : kPixelCounts) {
            for (size_t offset = 0; offset < 16; ++offset) {
                CAPTURE(channels, count, offset);
                std::vector<uint8_t> color(offset + count * channels + 16, 0xA7);
                std::vector<uint8_t> destination(offset + count * channels + 16, 0xCD);
                for (int channel = 0; channel < channels; ++channel) {
                    color[offset + channel] = Pattern(0, channel);
                }
                const SourceRow input = {color.data() + offset, BGR, count,
                                         channels, count * static_cast<size_t>(channels)};
                const DestinationRow output = {
                  destination.data() + offset, TensorLayout::NHWC, count,
                  channels, 1, count * static_cast<size_t>(channels), 0};
                REQUIRE(RunPixelSpan(program, input, output, nullptr, nullptr,
                                     nullptr, 0) == SUCCESS);
                for (size_t pixel = 0; pixel < count; ++pixel) {
                    for (int channel = 0; channel < channels; ++channel) {
                        REQUIRE(destination[offset + pixel * channels + channel] ==
                                color[offset + channel]);
                    }
                }
                REQUIRE(std::all_of(destination.begin(), destination.begin() + offset,
                                    [](uint8_t value) { return value == 0xCD; }));
                REQUIRE(std::all_of(destination.begin() + offset + count * channels,
                                    destination.end(),
                                    [](uint8_t value) { return value == 0xCD; }));
            }
        }
    }
}

TEST_CASE("task_pixel_program_float_c4_writers_preserve_blocked_layout",
          "[task][kernel-contract][float][nc4hw4]") {
    constexpr float mean[4] = {1.0f, 2.0f, 3.0f, 4.0f};
    constexpr float normal[4] = {0.5f, 0.25f, 2.0f, 0.125f};

    SECTION("one source channel occupies only lane zero") {
        PixelProgram program;
        REQUIRE(CompilePixelProgram(
                  MakeSpec(GRAY, GRAY, 1, 4, halide_type_of<float>(),
                           TensorLayout::NC4HW4),
                  &program) == SUCCESS);
        for (const size_t count : kPixelCounts) {
            std::vector<uint8_t> source(count);
            std::vector<float> destination(count * 4 + 4, -999.0f);
            for (size_t pixel = 0; pixel < count; ++pixel) {
                source[pixel] = Pattern(pixel, 0);
            }
            const SourceRow input = {source.data(), GRAY, count, 1, count};
            const DestinationRow output = {destination.data(), TensorLayout::NC4HW4,
                                           count, 4, 4,
                                           count * 4 * sizeof(float), 0};
            REQUIRE(RunPixelSpan(program, input, output, mean, normal,
                                 nullptr, 0) == SUCCESS);
            for (size_t pixel = 0; pixel < count; ++pixel) {
                CAPTURE(count, pixel);
                const float expected = normal[0] * (source[pixel] - mean[0]);
                REQUIRE(FloatBits(destination[4 * pixel]) == FloatBits(expected));
#if defined(INSPIRECV_TASK_USE_NEON)
                // P0 ARM64 writes zero into unused lanes of each eight-pixel
                // vector block, then applies the C1 mean/normal pair to zero
                // in its scalar tail. Preserve that bit-exact distinction.
                const float unused = pixel < (count / 8) * 8
                                       ? 0.0f
                                       : normal[0] * (0.0f - mean[0]);
#else
                const float unused = 0.0f;
#endif
                REQUIRE(FloatBits(destination[4 * pixel + 1]) == FloatBits(unused));
                REQUIRE(FloatBits(destination[4 * pixel + 2]) == FloatBits(unused));
                REQUIRE(FloatBits(destination[4 * pixel + 3]) == FloatBits(unused));
            }
            REQUIRE(std::all_of(destination.begin() + count * 4, destination.end(),
                                [](float value) { return value == -999.0f; }));
        }
    }

    SECTION("three source channels are converted then padded") {
        PixelProgram program;
        REQUIRE(CompilePixelProgram(
                  MakeSpec(BGR, RGB, 3, 4, halide_type_of<float>(),
                           TensorLayout::NC4HW4),
                  &program) == SUCCESS);
        for (const size_t count : kPixelCounts) {
            std::vector<uint8_t> source(count * 3);
            std::vector<uint8_t> temporary(count * 4, 0xEF);
            std::vector<float> destination(count * 4 + 4, -999.0f);
            for (size_t pixel = 0; pixel < count; ++pixel) {
                for (int channel = 0; channel < 3; ++channel) {
                    source[3 * pixel + channel] = Pattern(pixel, channel);
                }
            }
            const SourceRow input = {source.data(), BGR, count, 3, count * 3};
            const DestinationRow output = {destination.data(), TensorLayout::NC4HW4,
                                           count, 4, 4,
                                           count * 4 * sizeof(float), 0};
            REQUIRE(RunPixelSpan(program, input, output, mean, normal,
                                 temporary.data(), temporary.size()) == SUCCESS);
            for (size_t pixel = 0; pixel < count; ++pixel) {
                const uint8_t converted[3] = {
                  source[3 * pixel + 2], source[3 * pixel + 1],
                  source[3 * pixel + 0]};
                for (int channel = 0; channel < 3; ++channel) {
                    CAPTURE(count, pixel, channel);
                    const float expected =
                      normal[channel] * (converted[channel] - mean[channel]);
                    REQUIRE(FloatBits(destination[4 * pixel + channel]) ==
                            FloatBits(expected));
                }
#if defined(INSPIRECV_TASK_USE_NEON)
                // As in P0, only the ARM64 scalar tail normalizes the padded
                // fourth lane with mean[3]/normal[3]. Vector blocks store zero.
                const float unused = pixel < (count / 8) * 8
                                       ? 0.0f
                                       : normal[3] * (0.0f - mean[3]);
#else
                const float unused = 0.0f;
#endif
                REQUIRE(FloatBits(destination[4 * pixel + 3]) == FloatBits(unused));
            }
            REQUIRE(std::all_of(destination.begin() + count * 4, destination.end(),
                                [](float value) { return value == -999.0f; }));
        }
    }

    SECTION("four source channels retain all lanes") {
        PixelProgram program;
        REQUIRE(CompilePixelProgram(
                  MakeSpec(RGBA, RGBA, 4, 4, halide_type_of<float>(),
                           TensorLayout::NC4HW4),
                  &program) == SUCCESS);
        for (const size_t count : kPixelCounts) {
            std::vector<uint8_t> source(count * 4);
            std::vector<float> destination(count * 4 + 4, -999.0f);
            for (size_t pixel = 0; pixel < count; ++pixel) {
                for (int channel = 0; channel < 4; ++channel) {
                    source[4 * pixel + channel] = Pattern(pixel, channel);
                }
            }
            const SourceRow input = {source.data(), RGBA, count, 4, count * 4};
            const DestinationRow output = {destination.data(), TensorLayout::NC4HW4,
                                           count, 4, 4,
                                           count * 4 * sizeof(float), 0};
            REQUIRE(RunPixelSpan(program, input, output, mean, normal,
                                 nullptr, 0) == SUCCESS);
            for (size_t pixel = 0; pixel < count; ++pixel) {
                for (int channel = 0; channel < 4; ++channel) {
                    CAPTURE(count, pixel, channel);
                    const float expected = normal[channel] *
                                           (source[4 * pixel + channel] - mean[channel]);
                    REQUIRE(FloatBits(destination[4 * pixel + channel]) ==
                            FloatBits(expected));
                }
            }
            REQUIRE(std::all_of(destination.begin() + count * 4, destination.end(),
                                [](float value) { return value == -999.0f; }));
        }
    }
}

TEST_CASE("task_pixel_program_rejects_mismatched_rows_and_short_scratch",
          "[task][kernel-contract][validation]") {
    PixelProgram program;
    REQUIRE(CompilePixelProgram(
              MakeSpec(BGR, RGB, 3, 3, halide_type_of<float>()),
              &program) == SUCCESS);
    std::array<uint8_t, 9> source{};
    std::array<float, 9> destination{};
    std::array<uint8_t, 11> short_scratch{};
    constexpr float mean[4] = {};
    constexpr float normal[4] = {1.0f, 1.0f, 1.0f, 1.0f};
    const SourceRow input = {source.data(), BGR, 3, 3, 9};
    const DestinationRow output = {destination.data(), TensorLayout::NHWC,
                                   3, 3, 4, sizeof(destination), 0};

    REQUIRE(RunPixelSpan(program, input, output, mean, normal,
                         short_scratch.data(), short_scratch.size()) ==
            inspirecv::INPUT_DATA_ERROR);
    DestinationRow wrong_count = output;
    wrong_count.pixel_count = 2;
    REQUIRE(RunPixelSpan(program, input, wrong_count, mean, normal,
                         nullptr, 0) == inspirecv::INPUT_DATA_ERROR);
    REQUIRE(RunPixelSpan(program, input, output, nullptr, normal,
                         nullptr, 0) == inspirecv::INPUT_DATA_ERROR);
}
