Do N.148i V1 ao V2: a implementação

Do N.148i V1 ao V2: a implementação

Olá leitor, seja muito bem vindo de volta a mais uma etapa da nossa jornada aqui no Portal da Micilini! 😊

Este é o quadragésimo primeiro artigo da nossa série, e o décimo quinto e último da Fase 5.

Do artigo 27 ao artigo 40, nós estudamos cada ferramenta da V2 com exemplos pequenos e independentes, e no artigo passado vimos a V2 vencer o WebP M6 no julgamento.

Hoje é o dia de abrir o código de verdade: vamos passar por cada arquivo do projeto e ver como ele era na V1 e como ficou na V2. 🔓

A ideia deste artigo é ser direto, então eu não vou explicar de novo a lógica de cada função, porque isso já foi feito nos artigos anteriores, e cada arquivo vem com o link para o artigo que explica a ideia por trás dele.

E tem uma promessa: no fim deste artigo, você vai ter o código completo da V2, arquivo por arquivo e linha por linha, sem nenhum trecho cortado.

Pega o café, porque este é o artigo mais longo da série! ☕

Como este artigo está organizado?

Cada arquivo de código do projeto aparece numa de três situações, e cada uma tem o seu formato:

  • Alterado: primeiro vem o código completo da V1 e depois o código completo da V2.
  • Novo: o arquivo foi criado durante o processo da V2, sendo assim, ele só vem com código completo do mesmo.
  • Igual: o arquivo não mudou, mas aparece completo mesmo assim, para que a V2 fique inteira aqui dentro deste artigo.

Os arquivos estão agrupados por pasta, e dentro da pasta src os arquivos novos seguem a ordem dos artigos da Fase 5, do rANS até as reconstruções.

A versão da V1 é a do commit 86cd4fe, que fechou a biblioteca da V1, e a versão da V2 é a do commit 6193c19, que fechou a V2.

E você pode ficar tranquilo, pois eu (William) conferi cada arquivo deste artigo contra esses dois commits, byte por byte, e todos são idênticos ao que está no repositório. ✅

O mapa da mudança

Contando só o código e os arquivos de build, a V1 tinha 49 arquivos, já a V2... tem 93 arquivos, somando 33.157 linhas totais:

Situação             │ Arquivos │ Linhas na V2
─────────────────────┼──────────┼─────────────
Alterados            │ 27       │ 11.689
Novos                │ 53       │ 20.159
Iguais               │ 13       │ 1.309
─────────────────────┼──────────┼─────────────
Total da V2          │ 93       │ 33.157
Removidos da V1      │ 9        │ -

A pasta src é onde está o coração da mudança: a V1 tinha 24 arquivos ali, e agora a V2 tem 58.

Os 9 arquivos removidos são ferramentas antigas do benchmark da V1, em Python, que deram lugar às ferramentas do julgamento da V2.

Da V1 para a V2, o projeto saiu de 49 para 93 arquivos de código, e a pasta src saiu de 24 para 58 arquivos.

Os arquivos que não são código

Para que este artigo fique só com o código, quatro grupos de arquivos ficam apenas no repositório:

  • A documentação em Markdown: o README.md, o LIBRARY-NOTES.md, o BENCHMARK.md, o FORMAT.md, que é novo na V2 e descreve o formato byte a byte, além dos README das pastas tools e docs.
  • As imagens com o acervo de 130 imagens, a imagem de exemplo e os créditos de cada imagem, na pasta images, e as figuras do README, na pasta docs/assets/readme.
  • Os dados do benchmark, na pasta benchmarks, com as medições brutas, as análises e uma cópia do código da V1 usada na comparação.
  • A pasta output, que guarda só um arquivo .gitkeep com uma linha vazia, para a pasta existir no repositório, e é ali que o programa de linha de comando escreve os resultados.

Nenhum desses arquivos é necessário para compilar a biblioteca, e todo o resto do código fonte você vai encontrar aqui. 📦

Só tem um detalhe: a bateria de validação lê a imagem images/example.ppm e escreve um arquivo de teste na pasta output, logo, essas duas coisas precisam existir na hora de rodar os testes, como vamos ver na seção de compilação.

A raiz do projeto

Na raiz ficam os arquivos que configuram o Git, o build e a licença.

.gitattributes

O .gitattributes diz ao Git como tratar o final de linha de cada tipo de arquivo.

Na V2, ele passou a forçar o final de linha do Linux em todos os arquivos de texto, para que os hashes das fontes medidas sejam os mesmos no Linux, no Windows e no macOS.

Na V1, o arquivo tinha 8 linhas:

*.n148i binary
*.pgm binary
*.ppm binary
*.png binary
*.csv text eol=lf
*.json text eol=lf
*.md text eol=lf
*.svg text eol=lf

Na V2, ele ficou com 15 linhas:

# Keep measured source hashes stable on Linux, Windows and macOS checkouts.
* text=auto eol=lf
*.n148i binary
*.pgm binary
*.ppm binary
*.png binary
*.csv text eol=lf
*.json text eol=lf
*.md text eol=lf
*.svg text eol=lf

# Preserve published tool output and its checksums across checkouts.
benchmarks/release/*.csv -text
benchmarks/release/library-validation/validation.log -text whitespace=-blank-at-eof
benchmarks/release/rate-distortion.svg whitespace=-blank-at-eol

.gitignore

O .gitignore lista o que o Git deve ignorar, como executáveis, bibliotecas compiladas e arquivos gerados pelo codec. Na V2, ele ganhou as pastas de build e de instalação, os arquivos temporários e a regra que mantém a pasta output vazia no repositório.

Na V1, o arquivo tinha 32 linhas:

# Local compiler output
/n148i
/bench
/compare
/validate
/benchmark-final
/src/n148i
/src/n148i.exe
/gmon.out
__pycache__/
*.o
.benchmark-deps/
.venv/
/.build/
/cmake-build*/
/builds/
/libn148i.a
/libn148i.so*
/libn148i.dylib*
/n148i.dll
/n148i.lib

# Generated codec output. Benchmark inputs and datasets are intentionally
# versioned on chore/benchmark-v1 so the published measurements are auditable.
*.n148i
*.pgm
output/validation-*.ppm

# Editor and operating-system files
.DS_Store
Thumbs.db
*.swp

Na V2, ele ficou com 45 linhas:

# Local compiler output
/n148i
/bench
/compare
/validate
/benchmark-final
/src/n148i
/src/n148i.exe
/gmon.out
__pycache__/
*.o
*.tmp
*.log
!benchmarks/release/library-validation/validation.log
.benchmark-deps/
.venv/
/.build/
/cmake-build*/
/builds/
/build/
/install/
/consumer-build/
/benchmark-final-nojxl
/libn148i.a
/libn148i.so*
/libn148i.dylib*
/n148i.dll
/n148i.lib
/*.zip

# Generated codec output. Benchmark inputs and published datasets remain
# versioned so the measurements are auditable.
*.n148i
*.pgm
/output/*
!/output/.gitkeep

# Local visual comparison sites
/blind-test/
/blink-test/

# Editor and operating-system files
.DS_Store
Thumbs.db
*.swp

CMakeLists.txt

O CMakeLists.txt é o build portátil da biblioteca, que nasceu no artigo 26. Na V2, ele ganhou os quatorze arquivos .c novos, a versão 2.0.0 e os testes de ida e volta com a biblioteca compartilhada e com uma pilha pequena.

Na V1, o arquivo tinha 164 linhas:

# N.148i portable library build
# Copyright (c) 2026 Micilini Roll. Licensed under the MIT License.

cmake_minimum_required(VERSION 3.16)

project(n148i VERSION 1.0.0 LANGUAGES C)

include(CTest)
include(GNUInstallDirs)
include(CMakePackageConfigHelpers)

option(N148I_BUILD_CLI "Build the N.148i command-line program" ON)
option(N148I_BUILD_EXAMPLE "Build the memory API example" ON)
option(N148I_BUILD_VALIDATION "Build the codec validation suite" ON)

set(N148I_SOURCES
    src/n148i.c
    src/header.c
    src/ppm.c
    src/tables.c
    src/dct.c
    src/cpu.c
    src/parallel.c
    src/huffman.c
    src/encoder.c
    src/decoder.c)

if(APPLE AND NOT DEFINED CMAKE_OSX_DEPLOYMENT_TARGET)
    set(CMAKE_OSX_DEPLOYMENT_TARGET "10.15" CACHE STRING
        "Minimum supported macOS version")
endif()

if(NOT WIN32)
    find_package(Threads REQUIRED)
endif()

function(n148i_configure_library target)
    target_sources(${target} PRIVATE ${N148I_SOURCES})
    target_compile_features(${target} PUBLIC c_std_11)
    target_include_directories(${target}
        PUBLIC
            $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
            $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
        PRIVATE
            ${CMAKE_CURRENT_SOURCE_DIR}/src)
    set_target_properties(${target} PROPERTIES
        C_VISIBILITY_PRESET hidden
        POSITION_INDEPENDENT_CODE ON)

    if(MSVC)
        target_compile_options(${target} PRIVATE /W4)
        target_compile_definitions(${target} PRIVATE _CRT_SECURE_NO_WARNINGS)
    else()
        target_compile_options(${target} PRIVATE
            -Wall -Wextra -Wpedantic -Wno-unused-parameter)
    endif()

    if(WIN32)
        # v1 uses pthreads on POSIX. The Windows library keeps the same codec
        # behavior through the tested single-thread fallback.
        target_compile_definitions(${target} PRIVATE N148_NO_THREADS)
    else()
        target_link_libraries(${target} PRIVATE Threads::Threads m)
    endif()
endfunction()

add_library(n148i_static STATIC)
n148i_configure_library(n148i_static)
target_compile_definitions(n148i_static PUBLIC N148I_STATIC_DEFINE)
set_target_properties(n148i_static PROPERTIES
    OUTPUT_NAME n148i
    EXPORT_NAME n148i_static
    ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/static")

add_library(n148i_shared SHARED)
n148i_configure_library(n148i_shared)
target_compile_definitions(n148i_shared PRIVATE N148I_BUILDING_LIBRARY)
set_target_properties(n148i_shared PROPERTIES
    OUTPUT_NAME n148i
    EXPORT_NAME n148i
    VERSION ${PROJECT_VERSION}
    SOVERSION ${PROJECT_VERSION_MAJOR}
    ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/shared"
    LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/shared"
    RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/shared")

if(WIN32)
    set_target_properties(n148i_static PROPERTIES PREFIX "" SUFFIX ".lib")
    set_target_properties(n148i_shared PROPERTIES
        PREFIX ""
        IMPORT_PREFIX ""
        IMPORT_SUFFIX ".lib")
elseif(UNIX AND NOT APPLE)
    target_link_options(n148i_shared PRIVATE
        "LINKER:--version-script=${CMAKE_CURRENT_SOURCE_DIR}/cmake/n148i.map")
endif()

add_library(n148i::n148i ALIAS n148i_shared)
add_library(n148i::n148i_static ALIAS n148i_static)

if(N148I_BUILD_CLI)
    add_executable(n148i_cli src/main.c)
    target_include_directories(n148i_cli PRIVATE src)
    target_link_libraries(n148i_cli PRIVATE n148i_static)
    set_target_properties(n148i_cli PROPERTIES OUTPUT_NAME n148i)
endif()

if(N148I_BUILD_EXAMPLE)
    add_executable(n148i_memory_roundtrip examples/memory_roundtrip.c)
    target_link_libraries(n148i_memory_roundtrip PRIVATE n148i_static)
    if(BUILD_TESTING)
        add_test(NAME n148i.memory_roundtrip COMMAND n148i_memory_roundtrip)
    endif()
endif()

if(N148I_BUILD_VALIDATION)
    add_executable(n148i_validate src/validate_cli.c)
    target_include_directories(n148i_validate PRIVATE src)
    target_link_libraries(n148i_validate PRIVATE n148i_static)
    set_target_properties(n148i_validate PROPERTIES OUTPUT_NAME validate)
    if(BUILD_TESTING AND CMAKE_SYSTEM_NAME STREQUAL "Linux" AND
       CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|amd64|AMD64)$")
        add_test(NAME n148i.validation COMMAND n148i_validate)
        set_tests_properties(n148i.validation PROPERTIES
            WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")
    endif()
endif()

configure_file(cmake/n148i.pc.in n148i.pc @ONLY)
configure_package_config_file(
    cmake/n148iConfig.cmake.in
    "${CMAKE_CURRENT_BINARY_DIR}/n148iConfig.cmake"
    INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/n148i")
write_basic_package_version_file(
    "${CMAKE_CURRENT_BINARY_DIR}/n148iConfigVersion.cmake"
    VERSION ${PROJECT_VERSION}
    COMPATIBILITY SameMajorVersion)

install(TARGETS n148i_shared
    EXPORT n148iTargets
    RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
    LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
    ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR})
install(TARGETS n148i_static
    EXPORT n148iTargets
    ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}/static")
install(FILES include/n148i.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
install(FILES LICENSE DESTINATION .)
install(FILES "packaging/README-${CMAKE_SYSTEM_NAME}.txt"
    DESTINATION . RENAME README.txt)
install(FILES "${CMAKE_CURRENT_BINARY_DIR}/n148i.pc"
    DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig")
install(FILES
    "${CMAKE_CURRENT_BINARY_DIR}/n148iConfig.cmake"
    "${CMAKE_CURRENT_BINARY_DIR}/n148iConfigVersion.cmake"
    DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/n148i")
install(EXPORT n148iTargets
    FILE n148iTargets.cmake
    NAMESPACE n148i::
    DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/n148i")

if(N148I_BUILD_CLI)
    install(TARGETS n148i_cli RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
endif()

Na V2, ele ficou com 199 linhas:

# N.148i portable library build
# Copyright (c) 2026 Micilini Roll. Licensed under the MIT License.

cmake_minimum_required(VERSION 3.16)

# V2 is the product name; CMake requires a numeric package/ABI version.
project(n148i VERSION 2.0.0 LANGUAGES C)

include(CTest)
include(GNUInstallDirs)
include(CMakePackageConfigHelpers)

option(N148I_BUILD_CLI "Build the N.148i command-line program" ON)
option(N148I_BUILD_EXAMPLE "Build the memory API example" ON)
option(N148I_BUILD_VALIDATION "Build the codec validation suite" ON)

set(N148I_SOURCES
    src/n148i.c
    src/header.c
    src/ppm.c
    src/tables.c
    src/dct.c
    src/cpu.c
    src/parallel.c
    src/huffman.c
    src/rans.c
    src/intra.c
    src/perceptual.c
    src/adaptive_quant.c
    src/segmentation.c
    src/variable_transform.c
    src/rdo.c
    src/loop_filter.c
    src/directional_intra.c
    src/entropy_payload.c
    src/chroma_profile.c
    src/luma_profile.c
    src/fidelity_profile.c
    src/entropy_profile.c
    src/encoder.c
    src/decoder.c)

if(APPLE AND NOT DEFINED CMAKE_OSX_DEPLOYMENT_TARGET)
    set(CMAKE_OSX_DEPLOYMENT_TARGET "10.15" CACHE STRING
        "Minimum supported macOS version")
endif()

if(NOT WIN32)
    find_package(Threads REQUIRED)
endif()

function(n148i_configure_library target)
    target_sources(${target} PRIVATE ${N148I_SOURCES})
    target_compile_features(${target} PUBLIC c_std_11)
    target_include_directories(${target}
        PUBLIC
            $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
            $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
        PRIVATE
            ${CMAKE_CURRENT_SOURCE_DIR}/src)
    set_target_properties(${target} PROPERTIES
        C_VISIBILITY_PRESET hidden
        POSITION_INDEPENDENT_CODE ON)

    if(MSVC)
        target_compile_options(${target} PRIVATE /W4)
        target_compile_definitions(${target} PRIVATE _CRT_SECURE_NO_WARNINGS)
    else()
        target_compile_options(${target} PRIVATE
            -Wall -Wextra -Wpedantic -Wno-unused-parameter)
    endif()

    if(WIN32)
        # The codec uses pthreads on POSIX. The Windows library keeps the same
        # behavior through the tested single-thread fallback.
        target_compile_definitions(${target} PRIVATE N148_NO_THREADS)
    else()
        target_link_libraries(${target} PRIVATE Threads::Threads m)
    endif()
endfunction()

add_library(n148i_static STATIC)
n148i_configure_library(n148i_static)
target_compile_definitions(n148i_static PUBLIC N148I_STATIC_DEFINE)
set_target_properties(n148i_static PROPERTIES
    OUTPUT_NAME n148i
    EXPORT_NAME n148i_static
    ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/static")

add_library(n148i_shared SHARED)
n148i_configure_library(n148i_shared)
target_compile_definitions(n148i_shared PRIVATE N148I_BUILDING_LIBRARY)
set_target_properties(n148i_shared PROPERTIES
    OUTPUT_NAME n148i
    EXPORT_NAME n148i
    VERSION ${PROJECT_VERSION}
    SOVERSION ${PROJECT_VERSION_MAJOR}
    ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/shared"
    LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/shared"
    RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/shared")

if(WIN32)
    set_target_properties(n148i_static PROPERTIES PREFIX "" SUFFIX ".lib")
    set_target_properties(n148i_shared PROPERTIES
        PREFIX ""
        IMPORT_PREFIX ""
        IMPORT_SUFFIX ".lib")
elseif(UNIX AND NOT APPLE)
    target_link_options(n148i_shared PRIVATE
        "LINKER:--version-script=${CMAKE_CURRENT_SOURCE_DIR}/cmake/n148i.map")
endif()

add_library(n148i::n148i ALIAS n148i_shared)
add_library(n148i::n148i_static ALIAS n148i_static)

if(N148I_BUILD_CLI)
    add_executable(n148i_cli src/main.c)
    target_include_directories(n148i_cli PRIVATE src)
    target_link_libraries(n148i_cli PRIVATE n148i_static)
    set_target_properties(n148i_cli PROPERTIES OUTPUT_NAME n148i)
endif()

if(N148I_BUILD_EXAMPLE)
    add_executable(n148i_memory_roundtrip examples/memory_roundtrip.c)
    target_link_libraries(n148i_memory_roundtrip PRIVATE n148i_static)
    if(BUILD_TESTING)
        add_test(NAME n148i.memory_roundtrip COMMAND n148i_memory_roundtrip)
    endif()
    add_executable(n148i_shared_roundtrip examples/memory_roundtrip.c)
    target_link_libraries(n148i_shared_roundtrip PRIVATE n148i_shared)
    if(BUILD_TESTING)
        add_test(NAME n148i.shared_roundtrip COMMAND n148i_shared_roundtrip)
        if(WIN32)
            add_custom_command(TARGET n148i_shared_roundtrip POST_BUILD
                COMMAND ${CMAKE_COMMAND} -E copy_if_different
                    $<TARGET_FILE:n148i_shared>
                    $<TARGET_FILE_DIR:n148i_shared_roundtrip>)
        endif()
        if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
            # Exercise the default MSVC stack limit for both library variants.
            foreach(linkage IN ITEMS memory shared)
                add_test(NAME n148i.${linkage}_roundtrip_small_stack
                    COMMAND /bin/sh -c
                        "ulimit -c 0 && ulimit -s 1024 && exec \"$0\""
                        $<TARGET_FILE:n148i_${linkage}_roundtrip>)
            endforeach()
        endif()
    endif()
endif()

if(N148I_BUILD_VALIDATION)
    add_executable(n148i_validate src/validate_cli.c)
    target_include_directories(n148i_validate PRIVATE src)
    target_link_libraries(n148i_validate PRIVATE n148i_static)
    set_target_properties(n148i_validate PROPERTIES OUTPUT_NAME validate)
    if(BUILD_TESTING AND CMAKE_SYSTEM_NAME STREQUAL "Linux" AND
       CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|amd64|AMD64)$")
        add_test(NAME n148i.validation COMMAND n148i_validate)
        set_tests_properties(n148i.validation PROPERTIES
            WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")
    endif()
endif()

configure_file(cmake/n148i.pc.in n148i.pc @ONLY)
configure_package_config_file(
    cmake/n148iConfig.cmake.in
    "${CMAKE_CURRENT_BINARY_DIR}/n148iConfig.cmake"
    INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/n148i")
write_basic_package_version_file(
    "${CMAKE_CURRENT_BINARY_DIR}/n148iConfigVersion.cmake"
    VERSION ${PROJECT_VERSION}
    COMPATIBILITY SameMajorVersion)

install(TARGETS n148i_shared
    EXPORT n148iTargets
    RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
    LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
    ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR})
install(TARGETS n148i_static
    EXPORT n148iTargets
    ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}/static")
install(FILES include/n148i.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
install(FILES LICENSE DESTINATION .)
install(FILES "packaging/README-${CMAKE_SYSTEM_NAME}.txt"
    DESTINATION . RENAME README.txt)
install(FILES "${CMAKE_CURRENT_BINARY_DIR}/n148i.pc"
    DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig")
install(FILES
    "${CMAKE_CURRENT_BINARY_DIR}/n148iConfig.cmake"
    "${CMAKE_CURRENT_BINARY_DIR}/n148iConfigVersion.cmake"
    DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/n148i")
install(EXPORT n148iTargets
    FILE n148iTargets.cmake
    NAMESPACE n148i::
    DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/n148i")

if(N148I_BUILD_CLI)
    install(TARGETS n148i_cli RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
endif()

Makefile

O Makefile é o build de conveniência para Linux, que liga cada ferramenta à biblioteca estática, como vimos no artigo 26.

Atenção na hora de copiar: as linhas de comando dentro dele começam com um caractere de tabulação, e não com espaços, porque o make exige isso.

Na V1, o arquivo tinha 120 linhas:

# N.148i codec and library - Linux convenience build
#
# Copyright (c) 2026 Micilini Roll. Licensed under the MIT License.
#
# CMake is the portable distribution build. This Makefile preserves the
# original development targets and now links each executable against the
# static N.148i library instead of compiling the codec sources into every tool.

CC       ?= cc
AR       ?= ar
RANLIB   ?= ranlib
CPPFLAGS ?=
CFLAGS   ?= -O2 -Wall -Wextra -Wno-unused-parameter
LDFLAGS  ?=
LDLIBS   := -lm

CPPFLAGS += -Iinclude -Isrc

JXL_PREFIX ?=
ifeq ($(strip $(JXL_PREFIX)),)
JXL_CFLAGS ?= $(shell pkg-config --cflags libjxl libjxl_threads 2>/dev/null)
JXL_LIBS ?= $(shell pkg-config --libs libjxl libjxl_threads 2>/dev/null)
JXL_LINK_FLAGS ?=
JXL_CHECK = pkg-config --atleast-version=0.8 libjxl && \
            pkg-config --exists libjxl_threads
else
JXL_CFLAGS ?= -I$(JXL_PREFIX)/include
JXL_LIBS ?= -L$(JXL_PREFIX)/lib -ljxl -ljxl_threads
JXL_LINK_FLAGS ?= -Wl,--disable-new-dtags -Wl,-rpath,"$(JXL_PREFIX)/lib"
JXL_CHECK = test -f "$(JXL_PREFIX)/include/jxl/encode.h" -a \
                 -f "$(JXL_PREFIX)/lib/libjxl.so" -a \
                 -f "$(JXL_PREFIX)/lib/libjxl_threads.so"
endif

BUILD_KIND := release
ifdef DEBUG
CFLAGS := -O0 -g -Wall -Wextra -Wno-unused-parameter
BUILD_KIND := debug
endif

ifndef NOTHREADS
CFLAGS  += -pthread
LDFLAGS += -pthread
else
CFLAGS  += -DN148_NO_THREADS
BUILD_KIND := $(BUILD_KIND)-nothreads
endif

SRCDIR   := src
BUILDDIR := .build/make/$(BUILD_KIND)
CORE_SOURCES := $(SRCDIR)/n148i.c $(SRCDIR)/header.c $(SRCDIR)/ppm.c \
                $(SRCDIR)/tables.c $(SRCDIR)/dct.c $(SRCDIR)/cpu.c \
                $(SRCDIR)/parallel.c $(SRCDIR)/huffman.c \
                $(SRCDIR)/encoder.c $(SRCDIR)/decoder.c
CORE_OBJECTS := $(patsubst $(SRCDIR)/%.c,$(BUILDDIR)/%.o,$(CORE_SOURCES))
CORE_DEPS    := $(CORE_OBJECTS:.o=.d)

STATIC_LIBRARY := libn148i.a
SHARED_REAL    := libn148i.so.1.0.0
SHARED_SONAME  := libn148i.so.1
SHARED_LIBRARY := libn148i.so

all: n148i

libraries: $(STATIC_LIBRARY) $(SHARED_LIBRARY)

$(BUILDDIR)/%.o: $(SRCDIR)/%.c
	@mkdir -p $(dir $@)
	$(CC) $(CPPFLAGS) $(CFLAGS) -fPIC -fvisibility=hidden -MMD -MP -c $< -o $@

$(STATIC_LIBRARY): $(CORE_OBJECTS)
	$(AR) rcs $@ $^
	$(RANLIB) $@

$(SHARED_REAL): $(CORE_OBJECTS) cmake/n148i.map
	$(CC) -shared -Wl,-soname,$(SHARED_SONAME) \
		-Wl,--version-script=cmake/n148i.map $(CORE_OBJECTS) \
		-o $@ $(LDFLAGS) $(LDLIBS)

$(SHARED_SONAME): $(SHARED_REAL)
	ln -sf $(SHARED_REAL) $@

$(SHARED_LIBRARY): $(SHARED_SONAME)
	ln -sf $(SHARED_SONAME) $@

n148i: $(SRCDIR)/main.c $(STATIC_LIBRARY)
	$(CC) $(CPPFLAGS) $(CFLAGS) -DN148I_STATIC_DEFINE $< \
		$(STATIC_LIBRARY) -o $@ $(LDFLAGS) $(LDLIBS)

bench: $(SRCDIR)/bench_cli.c $(STATIC_LIBRARY)
	$(CC) $(CPPFLAGS) $(CFLAGS) -DN148I_STATIC_DEFINE $< \
		$(STATIC_LIBRARY) -o $@ $(LDFLAGS) $(LDLIBS)

compare: $(SRCDIR)/compare_cli.c $(STATIC_LIBRARY)
	$(CC) $(CPPFLAGS) $(CFLAGS) -DN148I_STATIC_DEFINE $< \
		$(STATIC_LIBRARY) -o $@ $(LDFLAGS) $(LDLIBS) -ljpeg

benchmark-final: $(SRCDIR)/benchmark_final_cli.c $(STATIC_LIBRARY)
	@$(JXL_CHECK) || \
	  (echo "libjxl >= 0.8 development files not found via pkg-config or JXL_PREFIX=$(JXL_PREFIX)" >&2; exit 1)
	$(CC) $(CPPFLAGS) $(CFLAGS) $(JXL_CFLAGS) -DN148I_STATIC_DEFINE $< \
		$(STATIC_LIBRARY) -o $@ $(LDFLAGS) $(LDLIBS) \
		-ljpeg $(JXL_LIBS) $(JXL_LINK_FLAGS)

validate: $(SRCDIR)/validate_cli.c $(STATIC_LIBRARY)
	$(CC) $(CPPFLAGS) $(CFLAGS) -DN148I_STATIC_DEFINE $< \
		$(STATIC_LIBRARY) -o $@ $(LDFLAGS) $(LDLIBS)

run: n148i
	./n148i

clean:
	rm -rf .build/make
	rm -f n148i bench compare validate benchmark-final \
		$(STATIC_LIBRARY) $(SHARED_LIBRARY) $(SHARED_SONAME) $(SHARED_REAL) \
		$(SRCDIR)/n148i $(SRCDIR)/n148i.exe $(SRCDIR)/bench

-include $(CORE_DEPS)

.PHONY: all libraries run clean bench compare benchmark-final validate

Na V2, ele ficou com 142 linhas:

# N.148i codec and library - Linux convenience build
#
# Copyright (c) 2026 Micilini Roll. Licensed under the MIT License.
#
# CMake is the portable distribution build. This Makefile preserves the
# command-line and benchmark targets and links each executable against the
# static N.148i library instead of compiling the codec sources into every tool.

CC       ?= cc
AR       ?= ar
RANLIB   ?= ranlib
CPPFLAGS ?=
CFLAGS   ?= -O3 -Wall -Wextra -Wno-unused-parameter
LDFLAGS  ?=
LDLIBS   := -lm

CPPFLAGS += -Iinclude -Isrc

JXL_PREFIX ?=
ifeq ($(strip $(JXL_PREFIX)),)
JXL_CFLAGS ?= $(shell pkg-config --cflags libjxl libjxl_threads 2>/dev/null)
JXL_LIBS ?= $(shell pkg-config --libs libjxl libjxl_threads 2>/dev/null)
JXL_LINK_FLAGS ?=
JXL_CHECK = pkg-config --atleast-version=0.8 libjxl && \
            pkg-config --exists libjxl_threads
else
JXL_CFLAGS ?= -I$(JXL_PREFIX)/include
JXL_LIBS ?= -L$(JXL_PREFIX)/lib -ljxl -ljxl_threads
JXL_LINK_FLAGS ?= -Wl,--disable-new-dtags -Wl,-rpath,"$(JXL_PREFIX)/lib"
JXL_CHECK = test -f "$(JXL_PREFIX)/include/jxl/encode.h" -a \
                 -f "$(JXL_PREFIX)/lib/libjxl.so" -a \
                 -f "$(JXL_PREFIX)/lib/libjxl_threads.so"
endif

WEBP_CFLAGS ?= $(shell pkg-config --cflags libwebp 2>/dev/null)
WEBP_LIBS ?= $(shell pkg-config --libs libwebp 2>/dev/null)
WEBP_CHECK = pkg-config --exists libwebp

BUILD_KIND := release
ifdef DEBUG
CFLAGS := -O0 -g -Wall -Wextra -Wno-unused-parameter
BUILD_KIND := debug
endif

ifndef NOTHREADS
CFLAGS  += -pthread
LDFLAGS += -pthread
else
CFLAGS  += -DN148_NO_THREADS
BUILD_KIND := $(BUILD_KIND)-nothreads
endif

SRCDIR   := src
BUILDDIR := .build/make/$(BUILD_KIND)
CORE_SOURCES := $(SRCDIR)/n148i.c $(SRCDIR)/header.c $(SRCDIR)/ppm.c \
                $(SRCDIR)/tables.c $(SRCDIR)/dct.c $(SRCDIR)/cpu.c \
                $(SRCDIR)/parallel.c $(SRCDIR)/huffman.c \
                $(SRCDIR)/rans.c $(SRCDIR)/intra.c $(SRCDIR)/perceptual.c \
                $(SRCDIR)/adaptive_quant.c $(SRCDIR)/segmentation.c \
                $(SRCDIR)/variable_transform.c $(SRCDIR)/rdo.c \
                $(SRCDIR)/loop_filter.c \
                $(SRCDIR)/entropy_payload.c $(SRCDIR)/directional_intra.c \
                $(SRCDIR)/chroma_profile.c $(SRCDIR)/luma_profile.c \
                $(SRCDIR)/fidelity_profile.c $(SRCDIR)/entropy_profile.c \
                $(SRCDIR)/encoder.c $(SRCDIR)/decoder.c
CORE_OBJECTS := $(patsubst $(SRCDIR)/%.c,$(BUILDDIR)/%.o,$(CORE_SOURCES))
CORE_DEPS    := $(CORE_OBJECTS:.o=.d)

STATIC_LIBRARY := libn148i.a
SHARED_REAL    := libn148i.so.2.0.0
SHARED_SONAME  := libn148i.so.2
SHARED_LIBRARY := libn148i.so

all: n148i

libraries: $(STATIC_LIBRARY) $(SHARED_LIBRARY)

$(BUILDDIR)/%.o: $(SRCDIR)/%.c
	@mkdir -p $(dir $@)
	$(CC) $(CPPFLAGS) $(CFLAGS) -fPIC -fvisibility=hidden -MMD -MP -c $< -o $@

$(STATIC_LIBRARY): $(CORE_OBJECTS)
	$(AR) rcs $@ $^
	$(RANLIB) $@

$(SHARED_REAL): $(CORE_OBJECTS) cmake/n148i.map
	$(CC) -shared -Wl,-soname,$(SHARED_SONAME) \
		-Wl,--version-script=cmake/n148i.map $(CORE_OBJECTS) \
		-o $@ $(LDFLAGS) $(LDLIBS)

$(SHARED_SONAME): $(SHARED_REAL)
	ln -sf $(SHARED_REAL) $@

$(SHARED_LIBRARY): $(SHARED_SONAME)
	ln -sf $(SHARED_SONAME) $@

n148i: $(SRCDIR)/main.c $(STATIC_LIBRARY)
	$(CC) $(CPPFLAGS) $(CFLAGS) -DN148I_STATIC_DEFINE $< \
		$(STATIC_LIBRARY) -o $@ $(LDFLAGS) $(LDLIBS)

bench: $(SRCDIR)/bench_cli.c $(STATIC_LIBRARY)
	$(CC) $(CPPFLAGS) $(CFLAGS) -DN148I_STATIC_DEFINE $< \
		$(STATIC_LIBRARY) -o $@ $(LDFLAGS) $(LDLIBS)

compare: $(SRCDIR)/compare_cli.c $(STATIC_LIBRARY)
	$(CC) $(CPPFLAGS) $(CFLAGS) -DN148I_STATIC_DEFINE $< \
		$(STATIC_LIBRARY) -o $@ $(LDFLAGS) $(LDLIBS) -ljpeg

benchmark-final: $(SRCDIR)/benchmark_final_cli.c $(STATIC_LIBRARY)
	@$(JXL_CHECK) || \
	  (echo "libjxl >= 0.8 development files not found via pkg-config or JXL_PREFIX=$(JXL_PREFIX)" >&2; exit 1)
	@$(WEBP_CHECK) || \
	  (echo "libwebp development files not found via pkg-config" >&2; exit 1)
	$(CC) $(CPPFLAGS) $(CFLAGS) $(JXL_CFLAGS) $(WEBP_CFLAGS) \
		-DN148I_STATIC_DEFINE $< \
		$(STATIC_LIBRARY) -o $@ $(LDFLAGS) $(LDLIBS) \
		-ljpeg $(JXL_LIBS) $(WEBP_LIBS) $(JXL_LINK_FLAGS)

benchmark-final-nojxl: $(SRCDIR)/benchmark_final_cli.c $(STATIC_LIBRARY)
	@$(WEBP_CHECK) || \
	  (echo "libwebp development files not found via pkg-config" >&2; exit 1)
	$(CC) $(CPPFLAGS) $(CFLAGS) $(WEBP_CFLAGS) \
		-DN148I_STATIC_DEFINE -DN148_BENCH_NO_JXL $< \
		$(STATIC_LIBRARY) -o $@ $(LDFLAGS) $(LDLIBS) \
		-ljpeg $(WEBP_LIBS)

validate: $(SRCDIR)/validate_cli.c $(STATIC_LIBRARY)
	$(CC) $(CPPFLAGS) $(CFLAGS) -DN148I_STATIC_DEFINE $< \
		$(STATIC_LIBRARY) -o $@ $(LDFLAGS) $(LDLIBS)

run: n148i
	./n148i

clean:
	rm -rf .build/make
	rm -f n148i bench compare validate benchmark-final benchmark-final-nojxl \
		$(STATIC_LIBRARY) $(SHARED_LIBRARY) $(SHARED_SONAME) $(SHARED_REAL) \
		$(SRCDIR)/n148i $(SRCDIR)/n148i.exe $(SRCDIR)/bench

-include $(CORE_DEPS)

.PHONY: all libraries run clean bench compare benchmark-final benchmark-final-nojxl validate

LICENSE

O LICENSE é a licença MIT do projeto, e a instalação feita pelo CMake copia esse arquivo junto com a biblioteca.

Ele não mudou da V1 para a V2, e o arquivo completo tem 46 linhas:

MIT License

Copyright (c) 2026 Micilini Roll

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Benchmark corpus and documentation assets
-----------------------------------------

The MIT License above applies to the N.148/N.148i source code, benchmark
programs, generated measurements and plots, and original project
documentation authored by Micilini Roll.

It does not relicense third-party photographs or artworks distributed in
`images/corpus-*.ppm`. Each corpus image remains under the public-domain,
CC0, or CC BY license recorded for that individual work in
`images/CREDITS.txt` and `benchmarks/v1/corpus-manifest.json`. The source author,
source page, license, and license URL in those files are part of the required
attribution and must be retained when redistributing the corpus. The committed
PPMs are normalized adaptations: they were resized, converted to sRGB, stripped
of metadata, and flattened where an alpha channel was present. Exact conversion
arguments are recorded per image in the manifest.

`docs/assets/readme/corpus-grid.png` is a montage derived from eight corpus
images and remains subject to their respective source licenses and
attributions, listed in `docs/assets/readme/README.md`.

`images/example.ppm` and the README comparison images derived from it are
project fixtures by Micilini Roll and are distributed under the MIT License
above.

A pasta .github

Aqui fica a integração contínua, que compila a biblioteca nos três sistemas.

.github/workflows/build-libraries.yml

O build-libraries.yml é o roteiro que compila e testa a biblioteca no Linux, no Windows e no macOS a cada envio ao repositório, como vimos no artigo 26. Na V2, ele passou a gerar o macOS universal em máquinas Intel e Apple Silicon e a testar programas que usam a biblioteca já instalada.

Na V1, o arquivo tinha 61 linhas:

# N.148i release library builds
# Copyright (c) 2026 Micilini Roll. Licensed under the MIT License.

name: Build libraries

on:
  workflow_dispatch:
  pull_request:
  push:
    tags:
      - "v*"

permissions:
  contents: read

jobs:
  build:
    name: ${{ matrix.artifact }}
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-latest
            artifact: linux-x86_64
            cmake_args: ""
          - os: windows-latest
            artifact: windows-x86_64
            cmake_args: ""
          - os: macos-latest
            artifact: macos-universal
            cmake_args: "-DCMAKE_OSX_ARCHITECTURES=x86_64;arm64"

    steps:
      - uses: actions/checkout@v4

      - name: Configure
        shell: bash
        env:
          N148I_CMAKE_ARGS: ${{ matrix.cmake_args }}
        run: >-
          cmake -S . -B cmake-build
          -DCMAKE_BUILD_TYPE=Release
          -DCMAKE_INSTALL_PREFIX="$GITHUB_WORKSPACE/builds/${{ matrix.artifact }}"
          ${N148I_CMAKE_ARGS}

      - name: Build
        run: cmake --build cmake-build --config Release --parallel

      - name: Test public API
        run: ctest --test-dir cmake-build -C Release --output-on-failure

      - name: Install
        run: cmake --install cmake-build --config Release

      - name: Upload package
        uses: actions/upload-artifact@v4
        with:
          name: n148i-${{ matrix.artifact }}
          path: builds/${{ matrix.artifact }}
          if-no-files-found: error

Na V2, ele ficou com 85 linhas:

# N.148i release library builds
# Copyright (c) 2026 Micilini Roll. Licensed under the MIT License.

name: V2 libraries

on:
  workflow_dispatch:
  pull_request:
  push:
    branches:
      - "**"
    tags:
      - "v*"

permissions:
  contents: read

jobs:
  build:
    name: ${{ matrix.artifact }}
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-24.04
            artifact: linux-x86_64
            cmake_args: ""
          - os: windows-2022
            artifact: windows-x86_64
            cmake_args: "-A x64"
          - os: macos-15
            artifact: macos-universal-arm64-test
            cmake_args: "-DCMAKE_OSX_ARCHITECTURES=x86_64;arm64"
          - os: macos-15-intel
            artifact: macos-universal-intel-test
            cmake_args: "-DCMAKE_OSX_ARCHITECTURES=x86_64;arm64"

    steps:
      - uses: actions/checkout@v4

      - name: Configure
        shell: bash
        env:
          N148I_CMAKE_ARGS: ${{ matrix.cmake_args }}
        run: >-
          cmake -S . -B cmake-build
          -DCMAKE_BUILD_TYPE=Release
          -DCMAKE_INSTALL_PREFIX="$GITHUB_WORKSPACE/builds/${{ matrix.artifact }}"
          ${N148I_CMAKE_ARGS}

      - name: Build
        run: cmake --build cmake-build --config Release --parallel

      - name: Test public API
        run: ctest --test-dir cmake-build -C Release --output-on-failure

      - name: Install
        run: cmake --install cmake-build --config Release

      - name: Configure installed library consumers
        shell: bash
        env:
          N148I_CMAKE_ARGS: ${{ matrix.cmake_args }}
        run: >-
          cmake -S examples -B consumer-build
          -DCMAKE_BUILD_TYPE=Release
          -DCMAKE_PREFIX_PATH="$GITHUB_WORKSPACE/builds/${{ matrix.artifact }}"
          ${N148I_CMAKE_ARGS}

      - name: Build installed library consumers
        run: cmake --build consumer-build --config Release --parallel

      - name: Test installed shared and static libraries
        shell: bash
        run: |
          export PATH="$GITHUB_WORKSPACE/builds/${{ matrix.artifact }}/bin:$PATH"
          ctest --test-dir consumer-build -C Release --output-on-failure

      - name: Upload package
        uses: actions/upload-artifact@v4
        with:
          name: n148i-V2-${{ matrix.artifact }}
          path: builds/${{ matrix.artifact }}
          if-no-files-found: error

A pasta cmake

Estes arquivos ajudam o CMake a exportar e a empacotar a biblioteca.

cmake/n148i.map

O n148i.map define quais funções a biblioteca compartilhada exporta no Linux. A única mudança foi a versão da ABI, de N148I_1.0 para N148I_2.0.

Na V1, o arquivo tinha 7 linhas:

/* N.148i exported ABI, Copyright (c) 2026 Micilini Roll, MIT License. */
N148I_1.0 {
    global:
        n148i_*;
    local:
        *;
};

Na V2, ele ficou com 7 linhas:

/* N.148i exported ABI, Copyright (c) 2026 Micilini Roll, MIT License. */
N148I_2.0 {
    global:
        n148i_*;
    local:
        *;
};

cmake/n148i.pc.in

O n148i.pc.in é o modelo do arquivo usado pelo pkg-config. Na V2, só a descrição mudou, para dizer que a biblioteca decodifica os formatos de 1 a 7.

Na V1, o arquivo tinha 13 linhas:

# N.148i pkg-config metadata
# Copyright (c) 2026 Micilini Roll. Licensed under the MIT License.

prefix=${pcfiledir}/../..
exec_prefix=${prefix}
libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@
includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@

Name: n148i
Description: N.148i v1 experimental lossy image codec
Version: @PROJECT_VERSION@
Libs: -L${libdir} -ln148i
Cflags: -I${includedir}

Na V2, ele ficou com 13 linhas:

# N.148i pkg-config metadata
# Copyright (c) 2026 Micilini Roll. Licensed under the MIT License.

prefix=${pcfiledir}/../..
exec_prefix=${prefix}
libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@
includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@

Name: n148i
Description: N.148i experimental lossy image codec with format 1-7 decoding
Version: @PROJECT_VERSION@
Libs: -L${libdir} -ln148i
Cflags: -I${includedir}

cmake/n148iConfig.cmake.in

O n148iConfig.cmake.in é o modelo que permite usar find_package(n148i) em outros projetos CMake.

Ele não mudou da V1 para a V2, e o arquivo completo tem 12 linhas:

# N.148i CMake package configuration
# Copyright (c) 2026 Micilini Roll. Licensed under the MIT License.

@PACKAGE_INIT@

include(CMakeFindDependencyMacro)
if(NOT WIN32)
    find_dependency(Threads)
endif()

include("${CMAKE_CURRENT_LIST_DIR}/n148iTargets.cmake")
check_required_components(n148i)

cmake/toolchains/mingw-w64-x86_64.cmake

O mingw-w64-x86_64.cmake ensina o CMake a gerar a biblioteca e os executáveis do Windows a partir do Linux, usando o MinGW.

Ele não mudou da V1 para a V2, e o arquivo completo tem 14 linhas:

# N.148i MinGW-w64 cross-compilation toolchain
# Copyright (c) 2026 Micilini Roll. Licensed under the MIT License.

set(CMAKE_SYSTEM_NAME Windows)
set(CMAKE_SYSTEM_PROCESSOR x86_64)

set(CMAKE_C_COMPILER x86_64-w64-mingw32-gcc)
set(CMAKE_RC_COMPILER x86_64-w64-mingw32-windres)

set(CMAKE_FIND_ROOT_PATH /usr/x86_64-w64-mingw32)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)

A pasta include

A pasta include tem um arquivo só, e ele é a porta de entrada de quem usa a biblioteca.

include/n148i.h

O n148i.h é o único cabeçalho público da biblioteca, criado no artigo 26. Na V2, ele ganhou o nome V2, as constantes dos formatos de 1 a 7, os bits de recurso e as máscaras dos perfis que vimos no artigo 38.

Na V1, o arquivo tinha 154 linhas:

/*
 * N.148i public library API
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#ifndef N148I_H
#define N148I_H

#include <stddef.h>
#include <stdint.h>

#define N148I_VERSION_MAJOR 1
#define N148I_VERSION_MINOR 0
#define N148I_VERSION_PATCH 0
#define N148I_VERSION_STRING "1.0.0"

/* The file format has its own version and can evolve independently. */
#define N148I_FORMAT_VERSION 1
#define N148I_MAX_THREADS 32

#if defined(N148I_STATIC_DEFINE)
#define N148I_API
#elif defined(_WIN32) || defined(__CYGWIN__)
#if defined(N148I_BUILDING_LIBRARY)
#define N148I_API __declspec(dllexport)
#else
#define N148I_API __declspec(dllimport)
#endif
#elif defined(__GNUC__) || defined(__clang__)
#define N148I_API __attribute__((visibility("default")))
#else
#define N148I_API
#endif

#ifdef __cplusplus
extern "C" {
#endif

typedef enum n148i_result {
    N148I_OK = 0,
    N148I_ERROR_INVALID_ARGUMENT = 1,
    N148I_ERROR_OUT_OF_MEMORY = 2,
    N148I_ERROR_INVALID_FORMAT = 3,
    N148I_ERROR_UNSUPPORTED_VERSION = 4,
    N148I_ERROR_TRUNCATED_DATA = 5,
    N148I_ERROR_CORRUPT_DATA = 6,
    N148I_ERROR_SIZE_OVERFLOW = 7,
    N148I_ERROR_ENCODE_FAILED = 8,
    N148I_ERROR_DECODE_FAILED = 9,
    N148I_ERROR_UNSUPPORTED_SIMD = 10
} n148i_result_t;

typedef enum n148i_chroma {
    N148I_CHROMA_444 = 0,
    N148I_CHROMA_422 = 1,
    N148I_CHROMA_420 = 2
} n148i_chroma_t;

typedef enum n148i_simd_level {
    N148I_SIMD_AUTO = -1,
    N148I_SIMD_SCALAR = 0,
    N148I_SIMD_SSE2 = 1,
    N148I_SIMD_AVX2 = 2,
    N148I_SIMD_AVX2_FMA = 3
} n148i_simd_level_t;

/* Interleaved 8-bit RGB pixels. A zero stride means width * 3 bytes. */
typedef struct n148i_image {
    uint8_t *pixels;
    uint32_t width;
    uint32_t height;
    size_t stride;
} n148i_image_t;

/*
 * Initialize this structure with n148i_encode_options_init(). The struct_size
 * member lets future library versions append fields without breaking callers.
 */
typedef struct n148i_encode_options {
    size_t struct_size;
    int quality;
    n148i_chroma_t chroma;
    int optimize_huffman;
    int thread_count;
} n148i_encode_options_t;

typedef struct n148i_image_info {
    uint32_t width;
    uint32_t height;
    uint32_t payload_size;
    size_t encoded_header_size;
    uint8_t format_version;
    uint8_t quality;
    n148i_chroma_t chroma;
    int optimized_huffman;
} n148i_image_info_t;

/*
 * Thread safety in v1:
 * - version/error queries, header parsing, and deallocation may run together;
 * - encode and decode calls require external serialization because the codec
 *   shares dispatch, thread configuration, histogram scratch, and a pool;
 * - configure SIMD and nonzero thread_count values before codec work starts.
 * Returned buffers are independently owned after an operation completes.
 */

/* Fill options with the v1 defaults: quality 50, 4:2:0, optimized Huffman. */
N148I_API void n148i_encode_options_init(n148i_encode_options_t *options);

/*
 * Encode an RGB image into a newly allocated N.148i buffer. Pass NULL options
 * to use the defaults. Release the returned buffer with n148i_free_buffer().
 */
N148I_API n148i_result_t n148i_encode_memory(
    const n148i_image_t *image,
    const n148i_encode_options_t *options,
    uint8_t **encoded,
    size_t *encoded_size);

/*
 * Decode a complete N.148i buffer into newly allocated, tightly packed RGB
 * pixels. Release the returned image with n148i_free_image().
 */
N148I_API n148i_result_t n148i_decode_memory(
    const uint8_t *encoded,
    size_t encoded_size,
    n148i_image_t *image);

/* Parse and validate the container header without decoding the pixels. */
N148I_API n148i_result_t n148i_read_header(
    const uint8_t *encoded,
    size_t encoded_size,
    n148i_image_info_t *info);

/* Memory returned by this library must be released by this library. */
N148I_API void n148i_free_buffer(void *buffer);
N148I_API void n148i_free_image(n148i_image_t *image);

N148I_API const char *n148i_result_string(n148i_result_t result);
N148I_API const char *n148i_library_version(void);
N148I_API uint32_t n148i_format_version(void);

/* Query or override runtime SIMD dispatch. Configure it before worker calls. */
N148I_API n148i_simd_level_t n148i_simd_level(void);
N148I_API const char *n148i_simd_name(n148i_simd_level_t level);
N148I_API n148i_result_t n148i_simd_force(n148i_simd_level_t level);

#ifdef __cplusplus
}
#endif

#endif

Na V2, ele ficou com 304 linhas:

/*
 * N.148i public library API
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#ifndef N148I_H
#define N148I_H

#include <stddef.h>
#include <stdint.h>

#define N148I_VERSION_MAJOR 2
#define N148I_VERSION_MINOR 0
#define N148I_VERSION_PATCH 0
#define N148I_VERSION_STRING "V2"

/* The file format has its own version and can evolve independently. */
#define N148I_FORMAT_VERSION_1 1
#define N148I_FORMAT_VERSION_2 2
#define N148I_FORMAT_VERSION_3 3
#define N148I_FORMAT_VERSION_4 4
#define N148I_FORMAT_VERSION_5 5
#define N148I_FORMAT_VERSION_6 6
#define N148I_FORMAT_VERSION_7 7
#define N148I_FORMAT_VERSION N148I_FORMAT_VERSION_7
#define N148I_MAX_THREADS 32

#if defined(N148I_STATIC_DEFINE)
#define N148I_API
#elif defined(_WIN32) || defined(__CYGWIN__)
#if defined(N148I_BUILDING_LIBRARY)
#define N148I_API __declspec(dllexport)
#else
#define N148I_API __declspec(dllimport)
#endif
#elif defined(__GNUC__) || defined(__clang__)
#define N148I_API __attribute__((visibility("default")))
#else
#define N148I_API
#endif

#ifdef __cplusplus
extern "C" {
#endif

typedef enum n148i_result {
    N148I_OK = 0,
    N148I_ERROR_INVALID_ARGUMENT = 1,
    N148I_ERROR_OUT_OF_MEMORY = 2,
    N148I_ERROR_INVALID_FORMAT = 3,
    N148I_ERROR_UNSUPPORTED_VERSION = 4,
    N148I_ERROR_TRUNCATED_DATA = 5,
    N148I_ERROR_CORRUPT_DATA = 6,
    N148I_ERROR_SIZE_OVERFLOW = 7,
    N148I_ERROR_ENCODE_FAILED = 8,
    N148I_ERROR_DECODE_FAILED = 9,
    N148I_ERROR_UNSUPPORTED_SIMD = 10,
    N148I_ERROR_UNSUPPORTED_FEATURE = 11
} n148i_result_t;

typedef enum n148i_chroma {
    N148I_CHROMA_444 = 0,
    N148I_CHROMA_422 = 1,
    N148I_CHROMA_420 = 2,
    /* Encoder-only automatic-chroma request. Streams always store one of the three
       concrete layouts above. Effort 0 resolves AUTO directly to 4:2:0. */
    N148I_CHROMA_AUTO = 3
} n148i_chroma_t;

typedef enum n148i_simd_level {
    N148I_SIMD_AUTO = -1,
    N148I_SIMD_SCALAR = 0,
    N148I_SIMD_SSE2 = 1,
    N148I_SIMD_AVX2 = 2,
    N148I_SIMD_AVX2_FMA = 3
} n148i_simd_level_t;

typedef enum n148i_feature {
    N148I_FEATURE_RANS = 1u << 0,
    N148I_FEATURE_CONTEXT = 1u << 1,
    N148I_FEATURE_INTRA = 1u << 2,
    N148I_FEATURE_PERCEPTUAL_COLOR = 1u << 3, /* format 2 only */
    N148I_FEATURE_ADAPTIVE_QUANT = 1u << 4,
    N148I_FEATURE_VARIABLE_TRANSFORM = 1u << 5,
    N148I_FEATURE_RDO = 1u << 6,
    N148I_FEATURE_LOOP_FILTER = 1u << 7,
    N148I_FEATURE_DIRECTIONAL_INTRA = 1u << 8,
    N148I_FEATURE_INTRA_4X4 = 1u << 9,
    N148I_FEATURE_CONTEXTUAL_RDO = 1u << 10,
    N148I_FEATURE_PERCEPTUAL_TRELLIS = 1u << 11,
    N148I_FEATURE_RECONSTRUCTION_AWARE_CHROMA = 1u << 12,
    N148I_FEATURE_JOINT_CHROMA_INTRA = 1u << 13,
    N148I_FEATURE_CALIBRATED_CHROMA_QUANT = 1u << 14,
    N148I_FEATURE_SEGMENTATION = 1u << 15,
    N148I_FEATURE_ADAPTIVE_LOOP_FILTER = 1u << 16,
    N148I_FEATURE_CALIBRATED_LUMA_QUANT = 1u << 17,
    N148I_FEATURE_LUMA_TRANSFORM_16X16 = 1u << 18,
    N148I_FEATURE_QUANT_ADAPTIVE_LUMA_FILTER = 1u << 19,
    N148I_FEATURE_FILTERED_INTRA_REFERENCES = 1u << 20,
    N148I_FEATURE_PLANAR_INTRA_PREDICTION = 1u << 21,
    N148I_FEATURE_STRUCTURAL_RDO = 1u << 22,
    N148I_FEATURE_QUALITY_LAMBDA = 1u << 23,
    N148I_FEATURE_LUMA_TRANSFORM_32X32 = 1u << 24,
    N148I_FEATURE_SECOND_ORDER_DC = 1u << 25,
    N148I_FEATURE_FINE_INTRA_DIRECTIONS = 1u << 26,
    N148I_FEATURE_ADAPTIVE_ENTROPY = 1u << 27,
    N148I_FEATURE_RICH_COEFFICIENT_CONTEXTS = 1u << 28,
    N148I_FEATURE_MULTIPLE_INTRA_REFERENCES = 1u << 29,
    N148I_FEATURE_DIRECTIONAL_SCAN = 1u << 30
} n148i_feature_t;

/* Kept as a macro because ISO C requires enum values to fit in signed int. */
#define N148I_FEATURE_DIRECTIONAL_TRANSFORM ((uint32_t) 1u << 31)

/* N148I_FEATURE_ALL retains the base-feature mask for source compatibility.
   Later formats use their own masks because rejected experiments remain opt-in. */
#define N148I_FEATURE_ALL ((uint32_t) 0xffu)
#define N148I_FORMAT_2_DEFAULT_FEATURES ((uint32_t) 0xc7u)
#define N148I_FORMAT_2_FEATURE_MASK N148I_FEATURE_ALL
#define N148I_PROFILE_DIRECTIONAL_INTRA ((uint32_t) 0x3c7u)
#define N148I_PROFILE_CONTEXTUAL_RDO ((uint32_t) 0x7c7u)
#define N148I_PROFILE_PERCEPTUAL_TRELLIS ((uint32_t) 0xfc7u)
#define N148I_FORMAT_3_DEFAULT_FEATURES N148I_PROFILE_CONTEXTUAL_RDO
#define N148I_FORMAT_3_FEATURE_MASK N148I_PROFILE_PERCEPTUAL_TRELLIS
#define N148I_PROFILE_RECONSTRUCTION_AWARE_CHROMA ((uint32_t) 0x17c7u)
#define N148I_PROFILE_JOINT_CHROMA_INTRA ((uint32_t) 0x37c7u)
#define N148I_PROFILE_CALIBRATED_CHROMA_QUANT ((uint32_t) 0x57c7u)
#define N148I_PROFILE_CHROMA_SEGMENTATION ((uint32_t) 0xd7c7u)
#define N148I_PROFILE_ADAPTIVE_CHROMA_FILTER ((uint32_t) 0x1d7c7u)
#define N148I_FORMAT_4_DEFAULT_FEATURES N148I_PROFILE_CALIBRATED_CHROMA_QUANT
#define N148I_FORMAT_4_FEATURE_MASK ((uint32_t) 0x1f7c7u)
#define N148I_PROFILE_CALIBRATED_LUMA_QUANT ((uint32_t) 0x257c7u)
#define N148I_PROFILE_VARIABLE_LUMA_TRANSFORM ((uint32_t) 0x657c7u)
#define N148I_PROFILE_PERCEPTUAL_LUMA_TRELLIS ((uint32_t) 0x65fc7u)
#define N148I_PROFILE_QUANT_ADAPTIVE_LUMA_FILTER ((uint32_t) 0xe57c7u)
#define N148I_FORMAT_5_DEFAULT_FEATURES N148I_PROFILE_VARIABLE_LUMA_TRANSFORM
#define N148I_FORMAT_5_FEATURE_MASK ((uint32_t) 0xff7c7u)
#define N148I_PROFILE_LUMA_TRANSFORM_32X32 ((uint32_t) 0x10657c7u)
#define N148I_PROFILE_FILTERED_INTRA_REFERENCES ((uint32_t) 0x1657c7u)
#define N148I_PROFILE_PLANAR_INTRA_PREDICTION ((uint32_t) 0x2657c7u)
#define N148I_PROFILE_COMBINED_INTRA_PREDICTION ((uint32_t) 0x3657c7u)
#define N148I_PROFILE_STRUCTURAL_RDO ((uint32_t) 0x6657c7u)
#define N148I_PROFILE_QUALITY_LAMBDA ((uint32_t) 0xa657c7u)
#define N148I_FORMAT_6_DEFAULT_FEATURES N148I_PROFILE_PLANAR_INTRA_PREDICTION
#define N148I_FORMAT_6_FEATURE_MASK ((uint32_t) 0x7fff7c7u)
#define N148I_PROFILE_ADAPTIVE_ENTROPY ((uint32_t) 0x82657c7u)
#define N148I_PROFILE_RICH_COEFFICIENT_CONTEXTS ((uint32_t) 0x182657c7u)
#define N148I_PROFILE_MULTIPLE_INTRA_REFERENCES ((uint32_t) 0x382657c7u)
#define N148I_PROFILE_DIRECTIONAL_SCAN ((uint32_t) 0x782657c7u)
#define N148I_PROFILE_DIRECTIONAL_TRANSFORM ((uint32_t) 0xf82657c7u)
#define N148I_PROFILE_RATE_CALIBRATED_SEARCH \
    (N148I_PROFILE_RICH_COEFFICIENT_CONTEXTS | N148I_FEATURE_QUALITY_LAMBDA)
#define N148I_FORMAT_7_DEFAULT_FEATURES N148I_PROFILE_RATE_CALIBRATED_SEARCH
/* Format 7 alone uses bit 3 for the spectral luma table. In format 2 the
   same bit retains its historical perceptual-colour meaning. The file-format
   version disambiguates them; existing format 7 readers reject this bit. */
#define N148I_FORMAT_7_SPECTRAL_LUMA_QUANT ((uint32_t) 1u << 3)
#define N148I_PROFILE_SPECTRAL_LUMA_QUANT \
    (N148I_PROFILE_RATE_CALIBRATED_SEARCH | \
     N148I_FORMAT_7_SPECTRAL_LUMA_QUANT)
/* Format 7 alone uses bit 4 to select the refined spectral table, together
   with bit 3. In format 2, bit 4 retains its adaptive-quantization meaning. */
#define N148I_FORMAT_7_REFINED_SPECTRAL_LUMA_QUANT ((uint32_t) 1u << 4)
#define N148I_PROFILE_REFINED_SPECTRAL_LUMA_QUANT \
    (N148I_PROFILE_SPECTRAL_LUMA_QUANT | \
     N148I_FORMAT_7_REFINED_SPECTRAL_LUMA_QUANT)
#define N148I_FORMAT_7_FULL_TRELLIS_FEATURES \
    (N148I_FORMAT_7_DEFAULT_FEATURES | N148I_FEATURE_PERCEPTUAL_TRELLIS)
/* Format 7 alone uses bit 5 for the structural luma table. Format 2 keeps
   its original variable-transform meaning. This profile adds segmentation
   and encoder preparation of luma from reconstructed chroma. */
#define N148I_FORMAT_7_STRUCTURAL_LUMA_QUANT ((uint32_t) 1u << 5)
#define N148I_PROFILE_STRUCTURAL_LUMA_QUANT \
    (N148I_PROFILE_REFINED_SPECTRAL_LUMA_QUANT | \
     N148I_FEATURE_SEGMENTATION | N148I_FORMAT_7_STRUCTURAL_LUMA_QUANT)
/* Format 7 bit 31 identifies the balanced table and output chroma
   reconstruction. The former planned directional profiles were never
   supported and lack the required structural reconstruction features. */
#define N148I_FORMAT_7_BALANCED_RECONSTRUCTION ((uint32_t) 1u << 31)
#define N148I_PROFILE_BALANCED_RECONSTRUCTION \
    (N148I_PROFILE_STRUCTURAL_LUMA_QUANT | \
     N148I_FORMAT_7_BALANCED_RECONSTRUCTION)
/* Format 7 bit 30 identifies the detail reconstruction profile. It keeps
   balanced chroma reconstruction and uses a 100% DCT16 quantizer scale; older
   profiles retain their 115% scale. Readers without this profile reject bit 30. */
#define N148I_FORMAT_7_DETAIL_RECONSTRUCTION ((uint32_t) 1u << 30)
#define N148I_PROFILE_DETAIL_RECONSTRUCTION \
    (N148I_PROFILE_BALANCED_RECONSTRUCTION | \
     N148I_FORMAT_7_DETAIL_RECONSTRUCTION)
#define N148I_FORMAT_7_FEATURE_MASK ((uint32_t) 0xffffffffu)

/* V2's public default. Numbered format presets above retain their original
   feature masks for applications that explicitly select a legacy profile. */
#define N148I_DEFAULT_FEATURES N148I_PROFILE_DETAIL_RECONSTRUCTION

/* Interleaved 8-bit RGB pixels. A zero stride means width * 3 bytes. */
typedef struct n148i_image {
    uint8_t *pixels;
    uint32_t width;
    uint32_t height;
    size_t stride;
} n148i_image_t;

/*
 * Initialize this structure with n148i_encode_options_init(). The struct_size
 * member lets future library versions append fields without breaking callers.
 */
typedef struct n148i_encode_options {
    size_t struct_size;
    int quality;
    n148i_chroma_t chroma;
    int optimize_huffman;
    int thread_count;
    uint32_t format_version;
    uint32_t feature_flags;
    /* Default 3. The structural profile uses six quantized luma candidates
       and contextual coefficient refinement at effort 3. The refined
       spectral profile selectively tests a second luma mode; effort 4
       enables broader selective search on format-7 profiles with rich
       contexts and quality-lambda search. */
    int effort;
    /* Zero selects quality for the structural profile, or the calibrated
       default (quality + 5, clamped to 100) for older profiles.
       A separate 1..100 value requires the calibrated-chroma-quantization
       feature and is stored in the stream. Older formats require zero. */
    int chroma_quality;
} n148i_encode_options_t;

typedef struct n148i_image_info {
    uint32_t width;
    uint32_t height;
    uint32_t payload_size;
    size_t encoded_header_size;
    uint8_t format_version;
    uint8_t quality;
    n148i_chroma_t chroma;
    int optimized_huffman;
    uint32_t feature_flags;
    uint8_t effort;
    uint32_t metadata_size;
    uint8_t chroma_quality;
} n148i_image_info_t;

/*
 * Thread safety:
 * - version/error queries, header parsing, and deallocation may run together;
 * - encode and decode calls require external serialization because the codec
 *   shares dispatch, thread configuration, histogram scratch, and a pool;
 * - configure SIMD and nonzero thread_count values before codec work starts.
 * Returned buffers are independently owned after an operation completes.
 */

/* Fill options with V2 defaults: quality 50, 4:2:0, detail reconstruction,
   chroma quality equal to luma, adaptive contextual rANS, intra prediction,
   variable transforms and effort 3. When forcing an older format, also
   select that format's default feature mask and leave chroma_quality at
   zero. */
N148I_API void n148i_encode_options_init(n148i_encode_options_t *options);

/*
 * Encode an RGB image into a newly allocated N.148i buffer. Pass NULL options
 * to use the defaults. Release the returned buffer with n148i_free_buffer().
 */
N148I_API n148i_result_t n148i_encode_memory(
    const n148i_image_t *image,
    const n148i_encode_options_t *options,
    uint8_t **encoded,
    size_t *encoded_size);

/*
 * Decode a complete N.148i buffer into newly allocated, tightly packed RGB
 * pixels. Release the returned image with n148i_free_image().
 */
N148I_API n148i_result_t n148i_decode_memory(
    const uint8_t *encoded,
    size_t encoded_size,
    n148i_image_t *image);

/* Parse and validate the container header without decoding the pixels. */
N148I_API n148i_result_t n148i_read_header(
    const uint8_t *encoded,
    size_t encoded_size,
    n148i_image_info_t *info);

/* Memory returned by this library must be released by this library. */
N148I_API void n148i_free_buffer(void *buffer);
N148I_API void n148i_free_image(n148i_image_t *image);

N148I_API const char *n148i_result_string(n148i_result_t result);
N148I_API const char *n148i_library_version(void);
N148I_API uint32_t n148i_format_version(void);

/* Query or override runtime SIMD dispatch. Configure it before worker calls. */
N148I_API n148i_simd_level_t n148i_simd_level(void);
N148I_API const char *n148i_simd_name(n148i_simd_level_t level);
N148I_API n148i_result_t n148i_simd_force(n148i_simd_level_t level);

#ifdef __cplusplus
}
#endif

#endif

A pasta src: os arquivos da V1 que mudaram

Agora entramos no coração do codec, e começamos pelos 15 arquivos da V1 que foram alterados.

Repare que a maioria deles mudou pouco, porque a V2 preservou o caminho da V1 inteiro para continuar lendo e escrevendo o formato 1.

src/header.h

O header.h guarda as constantes do cabeçalho do formato 1, que nasceu no artigo 14. Na V2, só os nomes mudaram, para deixar claro que esses valores pertencem ao formato 1.

Na V1, o arquivo tinha 36 linhas:

#ifndef HEADER_H
#define HEADER_H

#include <stdint.h>
#include <stdio.h>

#define N148I_MAGIC "N148I"
#define N148I_MAGIC_LEN 5
#define N148I_VERSION 1
#define N148I_HEADER_SIZE 21

// Chroma subsampling modes.
#define CHROMA_444 0
#define CHROMA_422 1
#define CHROMA_420 2

typedef struct {
    uint8_t version;
    uint32_t width;
    uint32_t height;
    uint8_t quality;
    uint8_t chroma;
    uint8_t optimized; // Non-zero when custom Huffman tables follow.
    uint32_t data_size; // Number of compressed bytes after the header.
} N148iHeader;

void write_u8(FILE *file, uint8_t value);
void write_u32(FILE *file, uint32_t value);
uint8_t read_u8(FILE *file);
uint32_t read_u32(FILE *file);

int write_header(FILE *file, N148iHeader *header);
int read_header(FILE *file, N148iHeader *header);
const char *chroma_name(uint8_t chroma);

#endif

Na V2, ele ficou com 36 linhas:

#ifndef HEADER_H
#define HEADER_H

#include <stdint.h>
#include <stdio.h>

#define N148I_MAGIC "N148I"
#define N148I_MAGIC_LEN 5
#define N148_FORMAT_VERSION_1 1
#define N148_FORMAT_1_HEADER_SIZE 21

// Chroma subsampling modes.
#define CHROMA_444 0
#define CHROMA_422 1
#define CHROMA_420 2

typedef struct {
    uint8_t version;
    uint32_t width;
    uint32_t height;
    uint8_t quality;
    uint8_t chroma;
    uint8_t optimized; // Non-zero when custom Huffman tables follow.
    uint32_t data_size; // Number of compressed bytes after the header.
} N148iHeader;

void write_u8(FILE *file, uint8_t value);
void write_u32(FILE *file, uint32_t value);
uint8_t read_u8(FILE *file);
uint32_t read_u32(FILE *file);

int write_header(FILE *file, N148iHeader *header);
int read_header(FILE *file, N148iHeader *header);
const char *chroma_name(uint8_t chroma);

#endif

src/tables.h

O tables.h declara as tabelas de quantização, que estudamos no artigo 10. Na V2, ele ganhou as declarações das tabelas novas da cor e do brilho, dos artigos 35 e 37.

Na V1, o arquivo tinha 20 linhas:

#ifndef TABLES_H
#define TABLES_H

extern const int Q_LUMA_BASE[8][8];
extern const int Q_CHROMA_BASE[8][8];

extern const int ZIGZAG[64];

extern const int BITS_DC_LUMA[17];
extern const unsigned char VAL_DC_LUMA[12];
extern const int BITS_DC_CHROMA[17];
extern const unsigned char VAL_DC_CHROMA[12];
extern const int BITS_AC_LUMA[17];
extern const unsigned char VAL_AC_LUMA[162];
extern const int BITS_AC_CHROMA[17];
extern const unsigned char VAL_AC_CHROMA[162];

void scale_table(const int base[8][8], int quality, int output[8][8]);

#endif

Na V2, ele ficou com 28 linhas:

#ifndef TABLES_H
#define TABLES_H

extern const int Q_LUMA_BASE[8][8];
extern const int FORMAT_5_LUMA_QUANT_BASE[8][8];
extern const int N148_SPECTRAL_LUMA_QUANT_BASE[8][8];
extern const int N148_REFINED_SPECTRAL_LUMA_QUANT_BASE[8][8];
extern const int N148_STRUCTURAL_LUMA_QUANT_BASE[8][8];
extern const int N148_BALANCED_LUMA_QUANT_BASE[8][8];
extern const int Q_CHROMA_BASE[8][8];
extern const int FORMAT_4_CHROMA_QUANT_BASE[8][8];
extern const int Q_PERCEPTUAL_INTENSITY_BASE[8][8];
extern const int Q_PERCEPTUAL_OPPONENT_BASE[8][8];

extern const int ZIGZAG[64];

extern const int BITS_DC_LUMA[17];
extern const unsigned char VAL_DC_LUMA[12];
extern const int BITS_DC_CHROMA[17];
extern const unsigned char VAL_DC_CHROMA[12];
extern const int BITS_AC_LUMA[17];
extern const unsigned char VAL_AC_LUMA[162];
extern const int BITS_AC_CHROMA[17];
extern const unsigned char VAL_AC_CHROMA[162];

void scale_table(const int base[8][8], int quality, int output[8][8]);

#endif

src/tables.c

O tables.c guarda os números dessas tabelas. A V1 tinha só as tabelas do JPEG, e a V2 acrescentou a tabela calibrada da cor, as tabelas calibrada, espectral, espectral refinada, estrutural e balanceada do brilho e as duas tabelas do espaço de cor oponente que ficou no cemitério de ideias.

Na V1, o arquivo tinha 103 linhas:

#include "tables.h"

const int Q_LUMA_BASE[8][8] = {
    {16, 11, 10, 16, 24, 40, 51, 61},
    {12, 12, 14, 19, 26, 58, 60, 55},
    {14, 13, 16, 24, 40, 57, 69, 56},
    {14, 17, 22, 29, 51, 87, 80, 62},
    {18, 22, 37, 56, 68, 109, 103, 77},
    {24, 35, 55, 64, 81, 104, 113, 92},
    {49, 64, 78, 87, 103, 121, 120, 101},
    {72, 92, 95, 98, 112, 100, 103, 99}
};

const int Q_CHROMA_BASE[8][8] = {
    {17, 18, 24, 47, 99, 99, 99, 99},
    {18, 21, 26, 66, 99, 99, 99, 99},
    {24, 26, 56, 99, 99, 99, 99, 99},
    {47, 66, 99, 99, 99, 99, 99, 99},
    {99, 99, 99, 99, 99, 99, 99, 99},
    {99, 99, 99, 99, 99, 99, 99, 99},
    {99, 99, 99, 99, 99, 99, 99, 99},
    {99, 99, 99, 99, 99, 99, 99, 99}
};

const int ZIGZAG[64] = {
     0,  1,  8, 16,  9,  2,  3, 10, 17, 24, 32, 25, 18, 11,  4,  5,
    12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13,  6,  7, 14, 21, 28,
    35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51,
    58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63
};

const int BITS_DC_LUMA[17] = {
    0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0
};
const unsigned char VAL_DC_LUMA[12] = {
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
};

const int BITS_DC_CHROMA[17] = {
    0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0
};
const unsigned char VAL_DC_CHROMA[12] = {
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
};

const int BITS_AC_LUMA[17] = {
    0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 125
};
const unsigned char VAL_AC_LUMA[162] = {
    0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,
    0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,
    0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,
    0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,
    0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,
    0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
    0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,
    0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,
    0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,
    0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
    0xf9,0xfa
};

const int BITS_AC_CHROMA[17] = {
    0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 119
};
const unsigned char VAL_AC_CHROMA[162] = {
    0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,
    0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,
    0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,
    0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,
    0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,
    0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,
    0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,
    0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,
    0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,
    0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
    0xf9,0xfa
};

void scale_table(const int base[8][8], int quality, int output[8][8]) {
    if (quality <= 0) {
        quality = 1;
    }
    if (quality > 100) {
        quality = 100;
    }

    int factor =
        (quality < 50) ? (5000 / quality) : (200 - quality * 2);

    for (int row = 0; row < 8; row++) {
        for (int column = 0; column < 8; column++) {
            int value = (base[row][column] * factor + 50) / 100;
            if (value < 1) {
                value = 1;
            }
            if (value > 255) {
                value = 255;
            }
            output[row][column] = value;
        }
    }
}

Na V2, ele ficou com 209 linhas:

#include "tables.h"

const int Q_LUMA_BASE[8][8] = {
    {16, 11, 10, 16, 24, 40, 51, 61},
    {12, 12, 14, 19, 26, 58, 60, 55},
    {14, 13, 16, 24, 40, 57, 69, 56},
    {14, 17, 22, 29, 51, 87, 80, 62},
    {18, 22, 37, 56, 68, 109, 103, 77},
    {24, 35, 55, 64, 81, 104, 113, 92},
    {49, 64, 78, 87, 103, 121, 120, 101},
    {72, 92, 95, 98, 112, 100, 103, 99}
};

/* Format 5's accepted table is a 12.5% geometric blend toward the measured
   residual-standard-deviation shape, scaled by 1.4 to preserve the
   luma/chroma rate balance. Keeping it format-local protects format 1-4 streams. */
const int FORMAT_5_LUMA_QUANT_BASE[8][8] = {
    {22, 15, 14, 20, 28, 44, 53, 60},
    {16, 16, 18, 23, 29, 58, 58, 53},
    {18, 16, 19, 27, 42, 56, 65, 53},
    {18, 20, 25, 32, 51, 80, 73, 57},
    {21, 25, 39, 55, 65, 96, 90, 67},
    {27, 36, 54, 61, 74, 91, 95, 77},
    {49, 60, 71, 77, 89, 101, 97, 81},
    {67, 80, 82, 83, 92, 82, 82, 77}
};

/* Format 7's optional spectral profile redistributes bits from the first
   spatial frequencies to fine luma detail. The shape was guided by a
   matched-rate reconstruction diagnosis; the old table stays intact for
   every pre-existing stream. */
const int N148_SPECTRAL_LUMA_QUANT_BASE[8][8] = {
    {26, 17, 16, 20, 28, 44, 53, 48},
    {19, 19, 18, 23, 29, 58, 46, 42},
    {21, 16, 19, 27, 42, 45, 52, 42},
    {18, 20, 25, 32, 41, 64, 58, 46},
    {21, 25, 39, 44, 52, 77, 72, 46},
    {27, 36, 43, 49, 59, 73, 65, 52},
    {49, 48, 57, 62, 71, 69, 66, 55},
    {54, 64, 66, 66, 63, 56, 56, 52},
};

/* Format 7's refined spectral profile moves a small bit budget from the low
   band to fine luma detail: low-band steps rise by about 8%, middle-band
   steps stay fixed, and high-band steps fall by about 4%. The extra format-7
   feature bit keeps previously encoded spectral streams on their table. */
const int N148_REFINED_SPECTRAL_LUMA_QUANT_BASE[8][8] = {
    {28, 18, 17, 20, 28, 44, 53, 46},
    {21, 21, 18, 23, 29, 58, 44, 40},
    {23, 16, 19, 27, 42, 43, 50, 40},
    {18, 20, 25, 32, 39, 61, 56, 44},
    {21, 25, 39, 42, 50, 74, 69, 44},
    {27, 36, 41, 47, 57, 70, 62, 50},
    {49, 46, 55, 60, 68, 66, 63, 53},
    {52, 61, 63, 63, 60, 54, 54, 50},
};

const int Q_CHROMA_BASE[8][8] = {
    {17, 18, 24, 47, 99, 99, 99, 99},
    {18, 21, 26, 66, 99, 99, 99, 99},
    {24, 26, 56, 99, 99, 99, 99, 99},
    {47, 66, 99, 99, 99, 99, 99, 99},
    {99, 99, 99, 99, 99, 99, 99, 99},
    {99, 99, 99, 99, 99, 99, 99, 99},
    {99, 99, 99, 99, 99, 99, 99, 99},
    {99, 99, 99, 99, 99, 99, 99, 99}
};

/* Format 4 keeps its chroma-residual table separate so calibration cannot change
   any format 1, 2, or 3 stream. These accepted weights retain more medium/high
   frequency chroma detail than the heavily saturated historical table. */
const int FORMAT_4_CHROMA_QUANT_BASE[8][8] = {
    {17, 18, 24, 40, 70, 80, 90, 99},
    {18, 21, 26, 48, 70, 85, 95, 99},
    {24, 26, 40, 60, 80, 90, 99, 99},
    {40, 48, 60, 75, 90, 99, 99, 99},
    {70, 70, 80, 90, 99, 99, 99, 99},
    {80, 85, 90, 99, 99, 99, 99, 99},
    {90, 95, 99, 99, 99, 99, 99, 99},
    {99, 99, 99, 99, 99, 99, 99, 99}
};

/* Segmentation starts from the mature JPEG frequency weighting, then calibrates
   the plane scales in its own colour space. Keeping dedicated tables makes
   that calibration normative without changing any earlier stream. */
const int Q_PERCEPTUAL_INTENSITY_BASE[8][8] = {
    {16, 11, 10, 16, 24, 40, 51, 61},
    {12, 12, 14, 19, 26, 58, 60, 55},
    {14, 13, 16, 24, 40, 57, 69, 56},
    {14, 17, 22, 29, 51, 87, 80, 62},
    {18, 22, 37, 56, 68,109,103, 77},
    {24, 35, 55, 64, 81,104,113, 92},
    {49, 64, 78, 87,103,121,120,101},
    {72, 92, 95, 98,112,100,103, 99}
};

const int Q_PERCEPTUAL_OPPONENT_BASE[8][8] = {
    {17, 18, 24, 47, 99, 99, 99, 99},
    {18, 21, 26, 66, 99, 99, 99, 99},
    {24, 26, 56, 99, 99, 99, 99, 99},
    {47, 66, 99, 99, 99, 99, 99, 99},
    {99, 99, 99, 99, 99, 99, 99, 99},
    {99, 99, 99, 99, 99, 99, 99, 99},
    {99, 99, 99, 99, 99, 99, 99, 99},
    {99, 99, 99, 99, 99, 99, 99, 99}
};

const int ZIGZAG[64] = {
     0,  1,  8, 16,  9,  2,  3, 10, 17, 24, 32, 25, 18, 11,  4,  5,
    12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13,  6,  7, 14, 21, 28,
    35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51,
    58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63
};

const int BITS_DC_LUMA[17] = {
    0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0
};
const unsigned char VAL_DC_LUMA[12] = {
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
};

const int BITS_DC_CHROMA[17] = {
    0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0
};
const unsigned char VAL_DC_CHROMA[12] = {
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
};

const int BITS_AC_LUMA[17] = {
    0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 125
};
const unsigned char VAL_AC_LUMA[162] = {
    0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,
    0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,
    0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,
    0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,
    0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,
    0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
    0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,
    0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,
    0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,
    0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
    0xf9,0xfa
};

const int BITS_AC_CHROMA[17] = {
    0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 119
};
const unsigned char VAL_AC_CHROMA[162] = {
    0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,
    0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,
    0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,
    0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,
    0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,
    0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,
    0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,
    0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,
    0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,
    0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
    0xf9,0xfa
};

void scale_table(const int base[8][8], int quality, int output[8][8]) {
    if (quality <= 0) {
        quality = 1;
    }
    if (quality > 100) {
        quality = 100;
    }

    int factor =
        (quality < 50) ? (5000 / quality) : (200 - quality * 2);

    for (int row = 0; row < 8; row++) {
        for (int column = 0; column < 8; column++) {
            int value = (base[row][column] * factor + 50) / 100;
            if (value < 1) {
                value = 1;
            }
            if (value > 255) {
                value = 255;
            }
            output[row][column] = value;
        }
    }
}

/* Derived from N.148 spatial-basis error energy, with six protected low frequencies. */
const int N148_BALANCED_LUMA_QUANT_BASE[8][8] = {
    {28, 25, 25, 28, 29, 31, 32, 31},
    {26, 26, 28, 28, 29, 32, 31, 30},
    {27, 27, 28, 29, 31, 31, 31, 30},
    {28, 28, 29, 30, 30, 32, 32, 31},
    {28, 29, 30, 31, 31, 33, 33, 31},
    {29, 30, 31, 31, 32, 33, 32, 31},
    {31, 31, 32, 32, 33, 33, 32, 32},
    {32, 32, 32, 32, 32, 32, 32, 31},
};

const int N148_STRUCTURAL_LUMA_QUANT_BASE[8][8] = {
    {28, 18, 17, 28, 33, 41, 45, 42},
    {21, 21, 27, 30, 34, 47, 41, 39},
    {23, 26, 27, 32, 40, 41, 44, 39},
    {27, 28, 31, 35, 39, 49, 47, 41},
    {29, 31, 39, 40, 44, 54, 52, 41},
    {32, 37, 40, 43, 47, 52, 49, 44},
    {44, 42, 46, 48, 51, 51, 49, 45},
    {45, 49, 49, 49, 48, 46, 46, 44}
};

src/dct.h

O dct.h é a interface da DCT, que vimos nos artigos 9, 19 e 22. Na V2, ele ganhou uma IDCT escalar pública e duas versões em AVX2 que já somam a predição na volta, usadas pela predição intra do artigo 30.

Na V1, o arquivo tinha 51 linhas:

/*
 * N.148 codec - forward and inverse DCT.
 *
 * Three implementations live behind this interface:
 *
 *   1. The separable reference transform (slow, exact, easy to read).
 *   2. A scalar AAN fast transform.
 *   3. An AVX2 AAN transform that handles all eight columns at once.
 *
 * The fast paths produce coefficients multiplied by a per-position
 * constant. That constant is folded into the quantization tables, so
 * nothing has to undo it at run time.
 */
#ifndef DCT_H
#define DCT_H

// Builds the cosine tables. Safe to call more than once.
void init_dct_tables(void);

// ---- Reference transform (article 9) ----
void dct_block(double block[8][8], double coef[8][8]);
void idct_block(double coef[8][8], double block[8][8]);

// ---- Fast transform, scaled output ----
// Input and output are 64 floats in row-major order.
void dct_block_fast(const float block[64], float coef[64]);
void idct_block_fast(const float coef[64], float block[64]);

// Direct entry points for callers that already performed CPU dispatch.
#if defined(__x86_64__) || defined(__i386__)
void dct_block_avx2(const float block[64], float coef[64]);
void idct_block_avx2(const float coef[64], float block[64]);
void idct_block_store_avx2(const float coef[64], unsigned char *dst,
                           int stride);
void idct_block_store_single_avx2(float dc, float ac, int index,
                                  unsigned char *dst, int stride);
void idct_block_store_two_avx2(float dc,
                               float first_ac, int first_index,
                               float second_ac, int second_index,
                               unsigned char *dst, int stride);
void idct_block_store_three_avx2(float dc,
                                 float first_ac, int first_index,
                                 float second_ac, int second_index,
                                 float third_ac, int third_index,
                                 unsigned char *dst, int stride);
#endif

// The constant the fast transform leaves on coefficient (u,v).
double aan_scale_factor(int u, int v);

#endif

Na V2, ele ficou com 62 linhas:

/*
 * N.148 codec - forward and inverse DCT.
 *
 * Three implementations live behind this interface:
 *
 *   1. The separable reference transform (slow, exact, easy to read).
 *   2. A scalar AAN fast transform.
 *   3. An AVX2 AAN transform that handles all eight columns at once.
 *
 * The fast paths produce coefficients multiplied by a per-position
 * constant. That constant is folded into the quantization tables, so
 * nothing has to undo it at run time.
 */
#ifndef DCT_H
#define DCT_H

// Builds the cosine tables. Safe to call more than once.
void init_dct_tables(void);

// ---- Reference transform (article 9) ----
void dct_block(double block[8][8], double coef[8][8]);
void idct_block(double coef[8][8], double block[8][8]);

// ---- Fast transform, scaled output ----
// Input and output are 64 floats in row-major order.
void dct_block_fast(const float block[64], float coef[64]);
void idct_block_fast(const float coef[64], float block[64]);

/* Intra prediction feeds reconstructed pixels into later blocks. Keep this
   scalar entry point for CPUs without AVX2 and for parity checks against the
   vector reconstruction path. */
void n148_idct_block_scalar(const float coef[64], float block[64]);

// Direct entry points for callers that already performed CPU dispatch.
#if defined(__x86_64__) || defined(__i386__)
void dct_block_avx2(const float block[64], float coef[64]);
void idct_block_avx2(const float coef[64], float block[64]);
void idct_block_store_avx2(const float coef[64], unsigned char *dst,
                           int stride);
void idct_block_add_prediction_avx2(const float coef[64],
                                     const unsigned char prediction[64],
                                     unsigned char *dst, int stride);
void idct_block_add_prediction_dc_avx2(float dc,
                                        const unsigned char prediction[64],
                                        unsigned char *dst, int stride);
void idct_block_store_single_avx2(float dc, float ac, int index,
                                  unsigned char *dst, int stride);
void idct_block_store_two_avx2(float dc,
                               float first_ac, int first_index,
                               float second_ac, int second_index,
                               unsigned char *dst, int stride);
void idct_block_store_three_avx2(float dc,
                                 float first_ac, int first_index,
                                 float second_ac, int second_index,
                                 float third_ac, int third_index,
                                 unsigned char *dst, int stride);
#endif

// The constant the fast transform leaves on coefficient (u,v).
double aan_scale_factor(int u, int v);

#endif

src/dct.c

O dct.c implementa essas transformadas. Na V2, a IDCT escalar, que antes era interna, virou a função pública n148_idct_block_scalar, e as duas versões em AVX2 com a predição foram acrescentadas, sem mexer nas transformadas que já existiam.

Na V1, o arquivo tinha 458 linhas:

#include <math.h>
#include <string.h>
#include "dct.h"
#include "cpu.h"

#define BLOCK_SIZE 8
#define PI 3.14159265358979323846

// ============================================================
// REFERENCE TRANSFORM (article 9)
// ============================================================

static double cos_table[BLOCK_SIZE][BLOCK_SIZE];
static double alpha[BLOCK_SIZE];
static int    tables_ready = 0;
#if defined(__x86_64__) || defined(__i386__)
static float sparse_inverse_basis[8][8];
static void init_sparse_inverse_basis(void);
#endif

void init_dct_tables(void) {
    if (tables_ready) return;
    for (int f = 0; f < BLOCK_SIZE; f++) {
        alpha[f] = (f == 0) ? (1.0 / sqrt(2.0)) : 1.0;
        for (int p = 0; p < BLOCK_SIZE; p++)
            cos_table[f][p] = cos((2.0 * p + 1.0) * f * PI / (2.0 * BLOCK_SIZE));
    }
#if defined(__x86_64__) || defined(__i386__)
    init_sparse_inverse_basis();
#endif
    tables_ready = 1;
}

static void dct_1d(double in[BLOCK_SIZE], double out[BLOCK_SIZE]) {
    for (int f = 0; f < BLOCK_SIZE; f++) {
        double s = 0.0;
        for (int p = 0; p < BLOCK_SIZE; p++) s += in[p] * cos_table[f][p];
        out[f] = 0.5 * alpha[f] * s;
    }
}

static void idct_1d(double in[BLOCK_SIZE], double out[BLOCK_SIZE]) {
    for (int p = 0; p < BLOCK_SIZE; p++) {
        double s = 0.0;
        for (int f = 0; f < BLOCK_SIZE; f++) s += alpha[f] * in[f] * cos_table[f][p];
        out[p] = 0.5 * s;
    }
}

void dct_block(double block[8][8], double coef[8][8]) {
    double temp[8][8];
    for (int r = 0; r < 8; r++) {
        double a[8], b[8];
        for (int c = 0; c < 8; c++) a[c] = block[r][c] - 128.0;
        dct_1d(a, b);
        for (int c = 0; c < 8; c++) temp[r][c] = b[c];
    }
    for (int c = 0; c < 8; c++) {
        double a[8], b[8];
        for (int r = 0; r < 8; r++) a[r] = temp[r][c];
        dct_1d(a, b);
        for (int r = 0; r < 8; r++) coef[r][c] = b[r];
    }
}

void idct_block(double coef[8][8], double block[8][8]) {
    double temp[8][8];
    for (int c = 0; c < 8; c++) {
        double a[8], b[8];
        for (int r = 0; r < 8; r++) a[r] = coef[r][c];
        idct_1d(a, b);
        for (int r = 0; r < 8; r++) temp[r][c] = b[r];
    }
    for (int r = 0; r < 8; r++) {
        double a[8], b[8];
        for (int c = 0; c < 8; c++) a[c] = temp[r][c];
        idct_1d(a, b);
        for (int c = 0; c < 8; c++) block[r][c] = b[c] + 128.0;
    }
}

// The scale the AAN transform leaves behind on each coefficient.
static const double AAN_SCALE[8] = {
    1.0, 1.387039845, 1.306562965, 1.175875602,
    1.0, 0.785694958, 0.541196100, 0.275899379
};

double aan_scale_factor(int u, int v) {
    return AAN_SCALE[u] * AAN_SCALE[v] * 8.0;
}

// ============================================================
// SCALAR AAN — 5 multiplications per 1-D pass instead of 64
// ============================================================

static void fdct_pass(float *p, int stride) {
    float t0,t1,t2,t3,t4,t5,t6,t7,t10,t11,t12,t13,z1,z2,z3,z4,z5,z11,z13;

    t0 = p[0*stride] + p[7*stride];  t7 = p[0*stride] - p[7*stride];
    t1 = p[1*stride] + p[6*stride];  t6 = p[1*stride] - p[6*stride];
    t2 = p[2*stride] + p[5*stride];  t5 = p[2*stride] - p[5*stride];
    t3 = p[3*stride] + p[4*stride];  t4 = p[3*stride] - p[4*stride];

    t10 = t0 + t3;  t13 = t0 - t3;
    t11 = t1 + t2;  t12 = t1 - t2;

    p[0*stride] = t10 + t11;
    p[4*stride] = t10 - t11;

    z1 = (t12 + t13) * 0.707106781f;
    p[2*stride] = t13 + z1;
    p[6*stride] = t13 - z1;

    t10 = t4 + t5;
    t11 = t5 + t6;
    t12 = t6 + t7;

    z5 = (t10 - t12) * 0.382683433f;
    z2 = 0.541196100f * t10 + z5;
    z4 = 1.306562965f * t12 + z5;
    z3 = t11 * 0.707106781f;

    z11 = t7 + z3;
    z13 = t7 - z3;

    p[5*stride] = z13 + z2;
    p[3*stride] = z13 - z2;
    p[1*stride] = z11 + z4;
    p[7*stride] = z11 - z4;
}

static void idct_pass(float *p, int stride) {
    float t0,t1,t2,t3,t4,t5,t6,t7,t10,t11,t12,t13,z5,z10,z11,z12,z13;

    t0 = p[0*stride];  t1 = p[2*stride];
    t2 = p[4*stride];  t3 = p[6*stride];

    t10 = t0 + t2;
    t11 = t0 - t2;
    t13 = t1 + t3;
    t12 = (t1 - t3) * 1.414213562f - t13;

    t0 = t10 + t13;  t3 = t10 - t13;
    t1 = t11 + t12;  t2 = t11 - t12;

    t4 = p[1*stride];  t5 = p[3*stride];
    t6 = p[5*stride];  t7 = p[7*stride];

    z13 = t6 + t5;  z10 = t6 - t5;
    z11 = t4 + t7;  z12 = t4 - t7;

    t7  = z11 + z13;
    t11 = (z11 - z13) * 1.414213562f;

    z5  = (z10 + z12) * 1.847759065f;
    t10 = z5 - z12 * 1.082392200f;
    t12 = z5 - z10 * 2.613125930f;

    t6 = t12 - t7;
    t5 = t11 - t6;
    t4 = t10 - t5;

    p[0*stride] = t0 + t7;   p[7*stride] = t0 - t7;
    p[1*stride] = t1 + t6;   p[6*stride] = t1 - t6;
    p[2*stride] = t2 + t5;   p[5*stride] = t2 - t5;
    p[3*stride] = t3 + t4;   p[4*stride] = t3 - t4;
}

static void dct_scalar(const float block[64], float coef[64]) {
    float t[64];
    for (int i = 0; i < 64; i++) t[i] = block[i] - 128.0f;
    /* Match the AVX2 path's pass order.  The two separable orders are
       mathematically equivalent, but changing their order changes the last
       few float bits and can cross a quantization boundary at high quality. */
    for (int c = 0; c < 8; c++) fdct_pass(&t[c],   8);
    for (int r = 0; r < 8; r++) fdct_pass(&t[r*8], 1);
    memcpy(coef, t, sizeof(t));
}

static void idct_scalar(const float coef[64], float block[64]) {
    float t[64];
    memcpy(t, coef, sizeof(t));
    for (int c = 0; c < 8; c++) idct_pass(&t[c],   8);
    for (int r = 0; r < 8; r++) idct_pass(&t[r*8], 1);
    for (int i = 0; i < 64; i++) block[i] = t[i] + 128.0f;
}

// ============================================================
// AVX2 AAN — all eight columns travel through the butterfly
// together, one per vector lane.
// ============================================================

#if defined(__x86_64__) || defined(__i386__)
#include <immintrin.h>

#define TRANSPOSE8(r0,r1,r2,r3,r4,r5,r6,r7) do {                        \
    __m256 a0,a1,a2,a3,a4,a5,a6,a7,b0,b1,b2,b3,b4,b5,b6,b7;             \
    a0=_mm256_unpacklo_ps(r0,r1); a1=_mm256_unpackhi_ps(r0,r1);         \
    a2=_mm256_unpacklo_ps(r2,r3); a3=_mm256_unpackhi_ps(r2,r3);         \
    a4=_mm256_unpacklo_ps(r4,r5); a5=_mm256_unpackhi_ps(r4,r5);         \
    a6=_mm256_unpacklo_ps(r6,r7); a7=_mm256_unpackhi_ps(r6,r7);         \
    b0=_mm256_shuffle_ps(a0,a2,0x44); b1=_mm256_shuffle_ps(a0,a2,0xEE); \
    b2=_mm256_shuffle_ps(a1,a3,0x44); b3=_mm256_shuffle_ps(a1,a3,0xEE); \
    b4=_mm256_shuffle_ps(a4,a6,0x44); b5=_mm256_shuffle_ps(a4,a6,0xEE); \
    b6=_mm256_shuffle_ps(a5,a7,0x44); b7=_mm256_shuffle_ps(a5,a7,0xEE); \
    r0=_mm256_permute2f128_ps(b0,b4,0x20); r1=_mm256_permute2f128_ps(b1,b5,0x20); \
    r2=_mm256_permute2f128_ps(b2,b6,0x20); r3=_mm256_permute2f128_ps(b3,b7,0x20); \
    r4=_mm256_permute2f128_ps(b0,b4,0x31); r5=_mm256_permute2f128_ps(b1,b5,0x31); \
    r6=_mm256_permute2f128_ps(b2,b6,0x31); r7=_mm256_permute2f128_ps(b3,b7,0x31); \
} while (0)

#define AAN_FWD(r0,r1,r2,r3,r4,r5,r6,r7) do {                           \
    __m256 t0,t1,t2,t3,t4,t5,t6,t7,t10,t11,t12,t13,z1,z2,z3,z4,z5,z11,z13; \
    t0=_mm256_add_ps(r0,r7); t7=_mm256_sub_ps(r0,r7);                   \
    t1=_mm256_add_ps(r1,r6); t6=_mm256_sub_ps(r1,r6);                   \
    t2=_mm256_add_ps(r2,r5); t5=_mm256_sub_ps(r2,r5);                   \
    t3=_mm256_add_ps(r3,r4); t4=_mm256_sub_ps(r3,r4);                   \
    t10=_mm256_add_ps(t0,t3); t13=_mm256_sub_ps(t0,t3);                 \
    t11=_mm256_add_ps(t1,t2); t12=_mm256_sub_ps(t1,t2);                 \
    r0=_mm256_add_ps(t10,t11); r4=_mm256_sub_ps(t10,t11);               \
    z1=_mm256_mul_ps(_mm256_add_ps(t12,t13),_mm256_set1_ps(0.707106781f)); \
    r2=_mm256_add_ps(t13,z1); r6=_mm256_sub_ps(t13,z1);                 \
    t10=_mm256_add_ps(t4,t5); t11=_mm256_add_ps(t5,t6); t12=_mm256_add_ps(t6,t7); \
    z5=_mm256_mul_ps(_mm256_sub_ps(t10,t12),_mm256_set1_ps(0.382683433f)); \
    z2=_mm256_add_ps(_mm256_mul_ps(t10,_mm256_set1_ps(0.541196100f)),z5); \
    z4=_mm256_add_ps(_mm256_mul_ps(t12,_mm256_set1_ps(1.306562965f)),z5); \
    z3=_mm256_mul_ps(t11,_mm256_set1_ps(0.707106781f));                 \
    z11=_mm256_add_ps(t7,z3); z13=_mm256_sub_ps(t7,z3);                 \
    r5=_mm256_add_ps(z13,z2); r3=_mm256_sub_ps(z13,z2);                 \
    r1=_mm256_add_ps(z11,z4); r7=_mm256_sub_ps(z11,z4);                 \
} while (0)

#define AAN_INV(r0,r1,r2,r3,r4,r5,r6,r7) do {                           \
    __m256 t0,t1,t2,t3,t4,t5,t6,t7,t10,t11,t12,t13,z5,z10,z11,z12,z13;  \
    t0=r0; t1=r2; t2=r4; t3=r6;                                         \
    t10=_mm256_add_ps(t0,t2); t11=_mm256_sub_ps(t0,t2);                 \
    t13=_mm256_add_ps(t1,t3);                                           \
    t12=_mm256_sub_ps(_mm256_mul_ps(_mm256_sub_ps(t1,t3),_mm256_set1_ps(1.414213562f)),t13); \
    t0=_mm256_add_ps(t10,t13); t3=_mm256_sub_ps(t10,t13);               \
    t1=_mm256_add_ps(t11,t12); t2=_mm256_sub_ps(t11,t12);               \
    t4=r1; t5=r3; t6=r5; t7=r7;                                         \
    z13=_mm256_add_ps(t6,t5); z10=_mm256_sub_ps(t6,t5);                 \
    z11=_mm256_add_ps(t4,t7); z12=_mm256_sub_ps(t4,t7);                 \
    t7=_mm256_add_ps(z11,z13);                                          \
    t11=_mm256_mul_ps(_mm256_sub_ps(z11,z13),_mm256_set1_ps(1.414213562f)); \
    z5=_mm256_mul_ps(_mm256_add_ps(z10,z12),_mm256_set1_ps(1.847759065f)); \
    t10=_mm256_sub_ps(z5,_mm256_mul_ps(z12,_mm256_set1_ps(1.082392200f))); \
    t12=_mm256_sub_ps(z5,_mm256_mul_ps(z10,_mm256_set1_ps(2.613125930f))); \
    t6=_mm256_sub_ps(t12,t7); t5=_mm256_sub_ps(t11,t6); t4=_mm256_sub_ps(t10,t5); \
    r0=_mm256_add_ps(t0,t7); r7=_mm256_sub_ps(t0,t7);                   \
    r1=_mm256_add_ps(t1,t6); r6=_mm256_sub_ps(t1,t6);                   \
    r2=_mm256_add_ps(t2,t5); r5=_mm256_sub_ps(t2,t5);                   \
    r3=_mm256_add_ps(t3,t4); r4=_mm256_sub_ps(t3,t4);                   \
} while (0)

__attribute__((target("avx2")))
void dct_block_avx2(const float block[64], float coef[64]) {
    __m256 r0=_mm256_loadu_ps(block+0),  r1=_mm256_loadu_ps(block+8);
    __m256 r2=_mm256_loadu_ps(block+16), r3=_mm256_loadu_ps(block+24);
    __m256 r4=_mm256_loadu_ps(block+32), r5=_mm256_loadu_ps(block+40);
    __m256 r6=_mm256_loadu_ps(block+48), r7=_mm256_loadu_ps(block+56);

    const __m256 shift = _mm256_set1_ps(128.0f);
    r0=_mm256_sub_ps(r0,shift); r1=_mm256_sub_ps(r1,shift);
    r2=_mm256_sub_ps(r2,shift); r3=_mm256_sub_ps(r3,shift);
    r4=_mm256_sub_ps(r4,shift); r5=_mm256_sub_ps(r5,shift);
    r6=_mm256_sub_ps(r6,shift); r7=_mm256_sub_ps(r7,shift);

    AAN_FWD(r0,r1,r2,r3,r4,r5,r6,r7);
    TRANSPOSE8(r0,r1,r2,r3,r4,r5,r6,r7);
    AAN_FWD(r0,r1,r2,r3,r4,r5,r6,r7);
    TRANSPOSE8(r0,r1,r2,r3,r4,r5,r6,r7);

    _mm256_storeu_ps(coef+0,r0);  _mm256_storeu_ps(coef+8,r1);
    _mm256_storeu_ps(coef+16,r2); _mm256_storeu_ps(coef+24,r3);
    _mm256_storeu_ps(coef+32,r4); _mm256_storeu_ps(coef+40,r5);
    _mm256_storeu_ps(coef+48,r6); _mm256_storeu_ps(coef+56,r7);
}

__attribute__((target("avx2"), always_inline))
static inline void idct_vectors_avx2(const float coef[64],
                                     __m256 *out0, __m256 *out1,
                                     __m256 *out2, __m256 *out3,
                                     __m256 *out4, __m256 *out5,
                                     __m256 *out6, __m256 *out7) {
    __m256 r0=_mm256_loadu_ps(coef+0),  r1=_mm256_loadu_ps(coef+8);
    __m256 r2=_mm256_loadu_ps(coef+16), r3=_mm256_loadu_ps(coef+24);
    __m256 r4=_mm256_loadu_ps(coef+32), r5=_mm256_loadu_ps(coef+40);
    __m256 r6=_mm256_loadu_ps(coef+48), r7=_mm256_loadu_ps(coef+56);

    AAN_INV(r0,r1,r2,r3,r4,r5,r6,r7);
    TRANSPOSE8(r0,r1,r2,r3,r4,r5,r6,r7);
    AAN_INV(r0,r1,r2,r3,r4,r5,r6,r7);
    TRANSPOSE8(r0,r1,r2,r3,r4,r5,r6,r7);

    *out0=r0; *out1=r1; *out2=r2; *out3=r3;
    *out4=r4; *out5=r5; *out6=r6; *out7=r7;
}

__attribute__((target("avx2")))
void idct_block_avx2(const float coef[64], float block[64]) {
    __m256 r0,r1,r2,r3,r4,r5,r6,r7;
    idct_vectors_avx2(coef, &r0, &r1, &r2, &r3,
                      &r4, &r5, &r6, &r7);

    const __m256 shift = _mm256_set1_ps(128.0f);
    _mm256_storeu_ps(block+0, _mm256_add_ps(r0,shift));
    _mm256_storeu_ps(block+8, _mm256_add_ps(r1,shift));
    _mm256_storeu_ps(block+16,_mm256_add_ps(r2,shift));
    _mm256_storeu_ps(block+24,_mm256_add_ps(r3,shift));
    _mm256_storeu_ps(block+32,_mm256_add_ps(r4,shift));
    _mm256_storeu_ps(block+40,_mm256_add_ps(r5,shift));
    _mm256_storeu_ps(block+48,_mm256_add_ps(r6,shift));
    _mm256_storeu_ps(block+56,_mm256_add_ps(r7,shift));
}

__attribute__((target("avx2"), always_inline))
static inline void store_idct_row_avx2(__m256 value, unsigned char *dst,
                                        __m256 shift, __m256 round) {
    value = _mm256_add_ps(value, shift);
    value = _mm256_add_ps(value, round);
    __m256i i32 = _mm256_cvttps_epi32(value);
    __m128i i16 = _mm_packs_epi32(_mm256_castsi256_si128(i32),
                                  _mm256_extracti128_si256(i32, 1));
    _mm_storel_epi64((__m128i *)dst, _mm_packus_epi16(i16, i16));
}

__attribute__((target("avx2")))
void idct_block_store_avx2(const float coef[64], unsigned char *dst,
                           int stride) {
    __m256 r0,r1,r2,r3,r4,r5,r6,r7;
    idct_vectors_avx2(coef, &r0, &r1, &r2, &r3,
                      &r4, &r5, &r6, &r7);

    const __m256 shift = _mm256_set1_ps(128.0f);
    const __m256 round = _mm256_set1_ps(0.5f);
    store_idct_row_avx2(r0, dst + (long)stride * 0, shift, round);
    store_idct_row_avx2(r1, dst + (long)stride * 1, shift, round);
    store_idct_row_avx2(r2, dst + (long)stride * 2, shift, round);
    store_idct_row_avx2(r3, dst + (long)stride * 3, shift, round);
    store_idct_row_avx2(r4, dst + (long)stride * 4, shift, round);
    store_idct_row_avx2(r5, dst + (long)stride * 5, shift, round);
    store_idct_row_avx2(r6, dst + (long)stride * 6, shift, round);
    store_idct_row_avx2(r7, dst + (long)stride * 7, shift, round);
}

/* A separable inverse transform reconstructs a sparse block as the DC level
   plus one outer product per AC coefficient.  These are the exact one-pass
   AAN responses used by the full transform, kept as eight tiny basis rows. */
static void init_sparse_inverse_basis(void) {
    for (int frequency = 0; frequency < 8; frequency++) {
        float values[8] = {0};
        values[frequency] = 1.0f;
        idct_pass(values, 1);
        memcpy(sparse_inverse_basis[frequency], values, sizeof(values));
    }
}

__attribute__((target("avx2")))
void idct_block_store_single_avx2(float dc, float ac, int index,
                                  unsigned char *dst, int stride) {
    int vertical_frequency = index >> 3;
    int horizontal_frequency = index & 7;
    __m256 horizontal =
        _mm256_loadu_ps(sparse_inverse_basis[horizontal_frequency]);
    const __m256 dc_vector = _mm256_set1_ps(dc);
    const __m256 shift = _mm256_set1_ps(128.0f);
    const __m256 round = _mm256_set1_ps(0.5f);
    for (int row = 0; row < 8; row++) {
        float vertical = ac * sparse_inverse_basis[vertical_frequency][row];
        __m256 value = _mm256_add_ps(
            dc_vector, _mm256_mul_ps(_mm256_set1_ps(vertical), horizontal));
        store_idct_row_avx2(value, dst + (long)stride * row, shift, round);
    }
}

__attribute__((target("avx2")))
void idct_block_store_two_avx2(float dc,
                               float first_ac, int first_index,
                               float second_ac, int second_index,
                               unsigned char *dst, int stride) {
    int first_vertical = first_index >> 3;
    int second_vertical = second_index >> 3;
    __m256 first_horizontal =
        _mm256_loadu_ps(sparse_inverse_basis[first_index & 7]);
    __m256 second_horizontal =
        _mm256_loadu_ps(sparse_inverse_basis[second_index & 7]);
    const __m256 dc_vector = _mm256_set1_ps(dc);
    const __m256 shift = _mm256_set1_ps(128.0f);
    const __m256 round = _mm256_set1_ps(0.5f);
    for (int row = 0; row < 8; row++) {
        float first = first_ac * sparse_inverse_basis[first_vertical][row];
        float second = second_ac * sparse_inverse_basis[second_vertical][row];
        __m256 value = _mm256_add_ps(
            dc_vector, _mm256_mul_ps(_mm256_set1_ps(first), first_horizontal));
        value = _mm256_add_ps(
            value, _mm256_mul_ps(_mm256_set1_ps(second), second_horizontal));
        store_idct_row_avx2(value, dst + (long)stride * row, shift, round);
    }
}

__attribute__((target("avx2")))
void idct_block_store_three_avx2(float dc,
                                 float first_ac, int first_index,
                                 float second_ac, int second_index,
                                 float third_ac, int third_index,
                                 unsigned char *dst, int stride) {
    int first_vertical = first_index >> 3;
    int second_vertical = second_index >> 3;
    int third_vertical = third_index >> 3;
    __m256 first_horizontal =
        _mm256_loadu_ps(sparse_inverse_basis[first_index & 7]);
    __m256 second_horizontal =
        _mm256_loadu_ps(sparse_inverse_basis[second_index & 7]);
    __m256 third_horizontal =
        _mm256_loadu_ps(sparse_inverse_basis[third_index & 7]);
    const __m256 dc_vector = _mm256_set1_ps(dc);
    const __m256 shift = _mm256_set1_ps(128.0f);
    const __m256 round = _mm256_set1_ps(0.5f);
    for (int row = 0; row < 8; row++) {
        float first = first_ac * sparse_inverse_basis[first_vertical][row];
        float second = second_ac * sparse_inverse_basis[second_vertical][row];
        float third = third_ac * sparse_inverse_basis[third_vertical][row];
        __m256 value = _mm256_add_ps(
            dc_vector, _mm256_mul_ps(_mm256_set1_ps(first), first_horizontal));
        value = _mm256_add_ps(
            value, _mm256_mul_ps(_mm256_set1_ps(second), second_horizontal));
        value = _mm256_add_ps(
            value, _mm256_mul_ps(_mm256_set1_ps(third), third_horizontal));
        store_idct_row_avx2(value, dst + (long)stride * row, shift, round);
    }
}

#endif

// ============================================================
// DISPATCH
// ============================================================

void dct_block_fast(const float block[64], float coef[64]) {
#if defined(__x86_64__) || defined(__i386__)
    if (n148_cpu_level() >= N148_CPU_AVX2) {
        dct_block_avx2(block, coef);
        return;
    }
#endif
    dct_scalar(block, coef);
}

void idct_block_fast(const float coef[64], float block[64]) {
#if defined(__x86_64__) || defined(__i386__)
    if (n148_cpu_level() >= N148_CPU_AVX2) {
        idct_block_avx2(coef, block);
        return;
    }
#endif
    idct_scalar(coef, block);
}

Na V2, ele ficou com 504 linhas:

#include <math.h>
#include <string.h>
#include "dct.h"
#include "cpu.h"

#define BLOCK_SIZE 8
#define PI 3.14159265358979323846

// ============================================================
// REFERENCE TRANSFORM (article 9)
// ============================================================

static double cos_table[BLOCK_SIZE][BLOCK_SIZE];
static double alpha[BLOCK_SIZE];
static int    tables_ready = 0;
#if defined(__x86_64__) || defined(__i386__)
static float sparse_inverse_basis[8][8];
static void init_sparse_inverse_basis(void);
#endif

void init_dct_tables(void) {
    if (tables_ready) return;
    for (int f = 0; f < BLOCK_SIZE; f++) {
        alpha[f] = (f == 0) ? (1.0 / sqrt(2.0)) : 1.0;
        for (int p = 0; p < BLOCK_SIZE; p++)
            cos_table[f][p] = cos((2.0 * p + 1.0) * f * PI / (2.0 * BLOCK_SIZE));
    }
#if defined(__x86_64__) || defined(__i386__)
    init_sparse_inverse_basis();
#endif
    tables_ready = 1;
}

static void dct_1d(double in[BLOCK_SIZE], double out[BLOCK_SIZE]) {
    for (int f = 0; f < BLOCK_SIZE; f++) {
        double s = 0.0;
        for (int p = 0; p < BLOCK_SIZE; p++) s += in[p] * cos_table[f][p];
        out[f] = 0.5 * alpha[f] * s;
    }
}

static void idct_1d(double in[BLOCK_SIZE], double out[BLOCK_SIZE]) {
    for (int p = 0; p < BLOCK_SIZE; p++) {
        double s = 0.0;
        for (int f = 0; f < BLOCK_SIZE; f++) s += alpha[f] * in[f] * cos_table[f][p];
        out[p] = 0.5 * s;
    }
}

void dct_block(double block[8][8], double coef[8][8]) {
    double temp[8][8];
    for (int r = 0; r < 8; r++) {
        double a[8], b[8];
        for (int c = 0; c < 8; c++) a[c] = block[r][c] - 128.0;
        dct_1d(a, b);
        for (int c = 0; c < 8; c++) temp[r][c] = b[c];
    }
    for (int c = 0; c < 8; c++) {
        double a[8], b[8];
        for (int r = 0; r < 8; r++) a[r] = temp[r][c];
        dct_1d(a, b);
        for (int r = 0; r < 8; r++) coef[r][c] = b[r];
    }
}

void idct_block(double coef[8][8], double block[8][8]) {
    double temp[8][8];
    for (int c = 0; c < 8; c++) {
        double a[8], b[8];
        for (int r = 0; r < 8; r++) a[r] = coef[r][c];
        idct_1d(a, b);
        for (int r = 0; r < 8; r++) temp[r][c] = b[r];
    }
    for (int r = 0; r < 8; r++) {
        double a[8], b[8];
        for (int c = 0; c < 8; c++) a[c] = temp[r][c];
        idct_1d(a, b);
        for (int c = 0; c < 8; c++) block[r][c] = b[c] + 128.0;
    }
}

// The scale the AAN transform leaves behind on each coefficient.
static const double AAN_SCALE[8] = {
    1.0, 1.387039845, 1.306562965, 1.175875602,
    1.0, 0.785694958, 0.541196100, 0.275899379
};

double aan_scale_factor(int u, int v) {
    return AAN_SCALE[u] * AAN_SCALE[v] * 8.0;
}

// ============================================================
// SCALAR AAN — 5 multiplications per 1-D pass instead of 64
// ============================================================

static void fdct_pass(float *p, int stride) {
    float t0,t1,t2,t3,t4,t5,t6,t7,t10,t11,t12,t13,z1,z2,z3,z4,z5,z11,z13;

    t0 = p[0*stride] + p[7*stride];  t7 = p[0*stride] - p[7*stride];
    t1 = p[1*stride] + p[6*stride];  t6 = p[1*stride] - p[6*stride];
    t2 = p[2*stride] + p[5*stride];  t5 = p[2*stride] - p[5*stride];
    t3 = p[3*stride] + p[4*stride];  t4 = p[3*stride] - p[4*stride];

    t10 = t0 + t3;  t13 = t0 - t3;
    t11 = t1 + t2;  t12 = t1 - t2;

    p[0*stride] = t10 + t11;
    p[4*stride] = t10 - t11;

    z1 = (t12 + t13) * 0.707106781f;
    p[2*stride] = t13 + z1;
    p[6*stride] = t13 - z1;

    t10 = t4 + t5;
    t11 = t5 + t6;
    t12 = t6 + t7;

    z5 = (t10 - t12) * 0.382683433f;
    z2 = 0.541196100f * t10 + z5;
    z4 = 1.306562965f * t12 + z5;
    z3 = t11 * 0.707106781f;

    z11 = t7 + z3;
    z13 = t7 - z3;

    p[5*stride] = z13 + z2;
    p[3*stride] = z13 - z2;
    p[1*stride] = z11 + z4;
    p[7*stride] = z11 - z4;
}

static void idct_pass(float *p, int stride) {
    float t0,t1,t2,t3,t4,t5,t6,t7,t10,t11,t12,t13,z5,z10,z11,z12,z13;

    t0 = p[0*stride];  t1 = p[2*stride];
    t2 = p[4*stride];  t3 = p[6*stride];

    t10 = t0 + t2;
    t11 = t0 - t2;
    t13 = t1 + t3;
    t12 = (t1 - t3) * 1.414213562f - t13;

    t0 = t10 + t13;  t3 = t10 - t13;
    t1 = t11 + t12;  t2 = t11 - t12;

    t4 = p[1*stride];  t5 = p[3*stride];
    t6 = p[5*stride];  t7 = p[7*stride];

    z13 = t6 + t5;  z10 = t6 - t5;
    z11 = t4 + t7;  z12 = t4 - t7;

    t7  = z11 + z13;
    t11 = (z11 - z13) * 1.414213562f;

    z5  = (z10 + z12) * 1.847759065f;
    t10 = z5 - z12 * 1.082392200f;
    t12 = z5 - z10 * 2.613125930f;

    t6 = t12 - t7;
    t5 = t11 - t6;
    t4 = t10 - t5;

    p[0*stride] = t0 + t7;   p[7*stride] = t0 - t7;
    p[1*stride] = t1 + t6;   p[6*stride] = t1 - t6;
    p[2*stride] = t2 + t5;   p[5*stride] = t2 - t5;
    p[3*stride] = t3 + t4;   p[4*stride] = t3 - t4;
}

static void dct_scalar(const float block[64], float coef[64]) {
    float t[64];
    for (int i = 0; i < 64; i++) t[i] = block[i] - 128.0f;
    /* Match the AVX2 path's pass order.  The two separable orders are
       mathematically equivalent, but changing their order changes the last
       few float bits and can cross a quantization boundary at high quality. */
    for (int c = 0; c < 8; c++) fdct_pass(&t[c],   8);
    for (int r = 0; r < 8; r++) fdct_pass(&t[r*8], 1);
    memcpy(coef, t, sizeof(t));
}

void n148_idct_block_scalar(const float coef[64], float block[64]) {
    float t[64];
    memcpy(t, coef, sizeof(t));
    for (int c = 0; c < 8; c++) idct_pass(&t[c],   8);
    for (int r = 0; r < 8; r++) idct_pass(&t[r*8], 1);
    for (int i = 0; i < 64; i++) block[i] = t[i] + 128.0f;
}

// ============================================================
// AVX2 AAN — all eight columns travel through the butterfly
// together, one per vector lane.
// ============================================================

#if defined(__x86_64__) || defined(__i386__)
#include <immintrin.h>

#define TRANSPOSE8(r0,r1,r2,r3,r4,r5,r6,r7) do {                        \
    __m256 a0,a1,a2,a3,a4,a5,a6,a7,b0,b1,b2,b3,b4,b5,b6,b7;             \
    a0=_mm256_unpacklo_ps(r0,r1); a1=_mm256_unpackhi_ps(r0,r1);         \
    a2=_mm256_unpacklo_ps(r2,r3); a3=_mm256_unpackhi_ps(r2,r3);         \
    a4=_mm256_unpacklo_ps(r4,r5); a5=_mm256_unpackhi_ps(r4,r5);         \
    a6=_mm256_unpacklo_ps(r6,r7); a7=_mm256_unpackhi_ps(r6,r7);         \
    b0=_mm256_shuffle_ps(a0,a2,0x44); b1=_mm256_shuffle_ps(a0,a2,0xEE); \
    b2=_mm256_shuffle_ps(a1,a3,0x44); b3=_mm256_shuffle_ps(a1,a3,0xEE); \
    b4=_mm256_shuffle_ps(a4,a6,0x44); b5=_mm256_shuffle_ps(a4,a6,0xEE); \
    b6=_mm256_shuffle_ps(a5,a7,0x44); b7=_mm256_shuffle_ps(a5,a7,0xEE); \
    r0=_mm256_permute2f128_ps(b0,b4,0x20); r1=_mm256_permute2f128_ps(b1,b5,0x20); \
    r2=_mm256_permute2f128_ps(b2,b6,0x20); r3=_mm256_permute2f128_ps(b3,b7,0x20); \
    r4=_mm256_permute2f128_ps(b0,b4,0x31); r5=_mm256_permute2f128_ps(b1,b5,0x31); \
    r6=_mm256_permute2f128_ps(b2,b6,0x31); r7=_mm256_permute2f128_ps(b3,b7,0x31); \
} while (0)

#define AAN_FWD(r0,r1,r2,r3,r4,r5,r6,r7) do {                           \
    __m256 t0,t1,t2,t3,t4,t5,t6,t7,t10,t11,t12,t13,z1,z2,z3,z4,z5,z11,z13; \
    t0=_mm256_add_ps(r0,r7); t7=_mm256_sub_ps(r0,r7);                   \
    t1=_mm256_add_ps(r1,r6); t6=_mm256_sub_ps(r1,r6);                   \
    t2=_mm256_add_ps(r2,r5); t5=_mm256_sub_ps(r2,r5);                   \
    t3=_mm256_add_ps(r3,r4); t4=_mm256_sub_ps(r3,r4);                   \
    t10=_mm256_add_ps(t0,t3); t13=_mm256_sub_ps(t0,t3);                 \
    t11=_mm256_add_ps(t1,t2); t12=_mm256_sub_ps(t1,t2);                 \
    r0=_mm256_add_ps(t10,t11); r4=_mm256_sub_ps(t10,t11);               \
    z1=_mm256_mul_ps(_mm256_add_ps(t12,t13),_mm256_set1_ps(0.707106781f)); \
    r2=_mm256_add_ps(t13,z1); r6=_mm256_sub_ps(t13,z1);                 \
    t10=_mm256_add_ps(t4,t5); t11=_mm256_add_ps(t5,t6); t12=_mm256_add_ps(t6,t7); \
    z5=_mm256_mul_ps(_mm256_sub_ps(t10,t12),_mm256_set1_ps(0.382683433f)); \
    z2=_mm256_add_ps(_mm256_mul_ps(t10,_mm256_set1_ps(0.541196100f)),z5); \
    z4=_mm256_add_ps(_mm256_mul_ps(t12,_mm256_set1_ps(1.306562965f)),z5); \
    z3=_mm256_mul_ps(t11,_mm256_set1_ps(0.707106781f));                 \
    z11=_mm256_add_ps(t7,z3); z13=_mm256_sub_ps(t7,z3);                 \
    r5=_mm256_add_ps(z13,z2); r3=_mm256_sub_ps(z13,z2);                 \
    r1=_mm256_add_ps(z11,z4); r7=_mm256_sub_ps(z11,z4);                 \
} while (0)

#define AAN_INV(r0,r1,r2,r3,r4,r5,r6,r7) do {                           \
    __m256 t0,t1,t2,t3,t4,t5,t6,t7,t10,t11,t12,t13,z5,z10,z11,z12,z13;  \
    t0=r0; t1=r2; t2=r4; t3=r6;                                         \
    t10=_mm256_add_ps(t0,t2); t11=_mm256_sub_ps(t0,t2);                 \
    t13=_mm256_add_ps(t1,t3);                                           \
    t12=_mm256_sub_ps(_mm256_mul_ps(_mm256_sub_ps(t1,t3),_mm256_set1_ps(1.414213562f)),t13); \
    t0=_mm256_add_ps(t10,t13); t3=_mm256_sub_ps(t10,t13);               \
    t1=_mm256_add_ps(t11,t12); t2=_mm256_sub_ps(t11,t12);               \
    t4=r1; t5=r3; t6=r5; t7=r7;                                         \
    z13=_mm256_add_ps(t6,t5); z10=_mm256_sub_ps(t6,t5);                 \
    z11=_mm256_add_ps(t4,t7); z12=_mm256_sub_ps(t4,t7);                 \
    t7=_mm256_add_ps(z11,z13);                                          \
    t11=_mm256_mul_ps(_mm256_sub_ps(z11,z13),_mm256_set1_ps(1.414213562f)); \
    z5=_mm256_mul_ps(_mm256_add_ps(z10,z12),_mm256_set1_ps(1.847759065f)); \
    t10=_mm256_sub_ps(z5,_mm256_mul_ps(z12,_mm256_set1_ps(1.082392200f))); \
    t12=_mm256_sub_ps(z5,_mm256_mul_ps(z10,_mm256_set1_ps(2.613125930f))); \
    t6=_mm256_sub_ps(t12,t7); t5=_mm256_sub_ps(t11,t6); t4=_mm256_sub_ps(t10,t5); \
    r0=_mm256_add_ps(t0,t7); r7=_mm256_sub_ps(t0,t7);                   \
    r1=_mm256_add_ps(t1,t6); r6=_mm256_sub_ps(t1,t6);                   \
    r2=_mm256_add_ps(t2,t5); r5=_mm256_sub_ps(t2,t5);                   \
    r3=_mm256_add_ps(t3,t4); r4=_mm256_sub_ps(t3,t4);                   \
} while (0)

__attribute__((target("avx2")))
void dct_block_avx2(const float block[64], float coef[64]) {
    __m256 r0=_mm256_loadu_ps(block+0),  r1=_mm256_loadu_ps(block+8);
    __m256 r2=_mm256_loadu_ps(block+16), r3=_mm256_loadu_ps(block+24);
    __m256 r4=_mm256_loadu_ps(block+32), r5=_mm256_loadu_ps(block+40);
    __m256 r6=_mm256_loadu_ps(block+48), r7=_mm256_loadu_ps(block+56);

    const __m256 shift = _mm256_set1_ps(128.0f);
    r0=_mm256_sub_ps(r0,shift); r1=_mm256_sub_ps(r1,shift);
    r2=_mm256_sub_ps(r2,shift); r3=_mm256_sub_ps(r3,shift);
    r4=_mm256_sub_ps(r4,shift); r5=_mm256_sub_ps(r5,shift);
    r6=_mm256_sub_ps(r6,shift); r7=_mm256_sub_ps(r7,shift);

    AAN_FWD(r0,r1,r2,r3,r4,r5,r6,r7);
    TRANSPOSE8(r0,r1,r2,r3,r4,r5,r6,r7);
    AAN_FWD(r0,r1,r2,r3,r4,r5,r6,r7);
    TRANSPOSE8(r0,r1,r2,r3,r4,r5,r6,r7);

    _mm256_storeu_ps(coef+0,r0);  _mm256_storeu_ps(coef+8,r1);
    _mm256_storeu_ps(coef+16,r2); _mm256_storeu_ps(coef+24,r3);
    _mm256_storeu_ps(coef+32,r4); _mm256_storeu_ps(coef+40,r5);
    _mm256_storeu_ps(coef+48,r6); _mm256_storeu_ps(coef+56,r7);
}

__attribute__((target("avx2"), always_inline))
static inline void idct_vectors_avx2(const float coef[64],
                                     __m256 *out0, __m256 *out1,
                                     __m256 *out2, __m256 *out3,
                                     __m256 *out4, __m256 *out5,
                                     __m256 *out6, __m256 *out7) {
    __m256 r0=_mm256_loadu_ps(coef+0),  r1=_mm256_loadu_ps(coef+8);
    __m256 r2=_mm256_loadu_ps(coef+16), r3=_mm256_loadu_ps(coef+24);
    __m256 r4=_mm256_loadu_ps(coef+32), r5=_mm256_loadu_ps(coef+40);
    __m256 r6=_mm256_loadu_ps(coef+48), r7=_mm256_loadu_ps(coef+56);

    AAN_INV(r0,r1,r2,r3,r4,r5,r6,r7);
    TRANSPOSE8(r0,r1,r2,r3,r4,r5,r6,r7);
    AAN_INV(r0,r1,r2,r3,r4,r5,r6,r7);
    TRANSPOSE8(r0,r1,r2,r3,r4,r5,r6,r7);

    *out0=r0; *out1=r1; *out2=r2; *out3=r3;
    *out4=r4; *out5=r5; *out6=r6; *out7=r7;
}

__attribute__((target("avx2")))
void idct_block_avx2(const float coef[64], float block[64]) {
    __m256 r0,r1,r2,r3,r4,r5,r6,r7;
    idct_vectors_avx2(coef, &r0, &r1, &r2, &r3,
                      &r4, &r5, &r6, &r7);

    const __m256 shift = _mm256_set1_ps(128.0f);
    _mm256_storeu_ps(block+0, _mm256_add_ps(r0,shift));
    _mm256_storeu_ps(block+8, _mm256_add_ps(r1,shift));
    _mm256_storeu_ps(block+16,_mm256_add_ps(r2,shift));
    _mm256_storeu_ps(block+24,_mm256_add_ps(r3,shift));
    _mm256_storeu_ps(block+32,_mm256_add_ps(r4,shift));
    _mm256_storeu_ps(block+40,_mm256_add_ps(r5,shift));
    _mm256_storeu_ps(block+48,_mm256_add_ps(r6,shift));
    _mm256_storeu_ps(block+56,_mm256_add_ps(r7,shift));
}

__attribute__((target("avx2"), always_inline))
static inline void store_idct_row_avx2(__m256 value, unsigned char *dst,
                                        __m256 shift, __m256 round) {
    value = _mm256_add_ps(value, shift);
    value = _mm256_add_ps(value, round);
    __m256i i32 = _mm256_cvttps_epi32(value);
    __m128i i16 = _mm_packs_epi32(_mm256_castsi256_si128(i32),
                                  _mm256_extracti128_si256(i32, 1));
    _mm_storel_epi64((__m128i *)dst, _mm_packus_epi16(i16, i16));
}

__attribute__((target("avx2")))
void idct_block_store_avx2(const float coef[64], unsigned char *dst,
                           int stride) {
    __m256 r0,r1,r2,r3,r4,r5,r6,r7;
    idct_vectors_avx2(coef, &r0, &r1, &r2, &r3,
                      &r4, &r5, &r6, &r7);

    const __m256 shift = _mm256_set1_ps(128.0f);
    const __m256 round = _mm256_set1_ps(0.5f);
    store_idct_row_avx2(r0, dst + (long)stride * 0, shift, round);
    store_idct_row_avx2(r1, dst + (long)stride * 1, shift, round);
    store_idct_row_avx2(r2, dst + (long)stride * 2, shift, round);
    store_idct_row_avx2(r3, dst + (long)stride * 3, shift, round);
    store_idct_row_avx2(r4, dst + (long)stride * 4, shift, round);
    store_idct_row_avx2(r5, dst + (long)stride * 5, shift, round);
    store_idct_row_avx2(r6, dst + (long)stride * 6, shift, round);
    store_idct_row_avx2(r7, dst + (long)stride * 7, shift, round);
}

__attribute__((target("avx2"), always_inline))
static inline void store_predicted_idct_row_avx2(
    __m256 residual, const unsigned char *prediction, unsigned char *dst) {
    __m128i bytes = _mm_loadl_epi64((const __m128i *) prediction);
    __m256 predictor = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(bytes));
    const __m256 shift = _mm256_set1_ps(128.0f);
    const __m256 zero = _mm256_setzero_ps();
    const __m256 maximum = _mm256_set1_ps(255.0f);
    const __m256 half = _mm256_set1_ps(0.5f);
    __m256 value = _mm256_add_ps(predictor,
                                  _mm256_add_ps(residual, shift));
    value = _mm256_sub_ps(value, shift);
    value = _mm256_min_ps(_mm256_max_ps(value, zero), maximum);
    __m256i rounded = _mm256_cvttps_epi32(_mm256_add_ps(value, half));
    __m128i words = _mm_packs_epi32(_mm256_castsi256_si128(rounded),
                                    _mm256_extracti128_si256(rounded, 1));
    _mm_storel_epi64((__m128i *) dst, _mm_packus_epi16(words, words));
}

__attribute__((target("avx2")))
void idct_block_add_prediction_dc_avx2(float dc,
                                        const unsigned char prediction[64],
                                        unsigned char *dst, int stride) {
    const __m256 level = _mm256_set1_ps(dc);
    for (int row = 0; row < 8; row++)
        store_predicted_idct_row_avx2(
            level, prediction + row * 8, dst + (long)stride * row);
}

__attribute__((target("avx2")))
void idct_block_add_prediction_avx2(const float coef[64],
                                     const unsigned char prediction[64],
                                     unsigned char *dst, int stride) {
    __m256 r0,r1,r2,r3,r4,r5,r6,r7;
    idct_vectors_avx2(coef, &r0, &r1, &r2, &r3,
                      &r4, &r5, &r6, &r7);
    store_predicted_idct_row_avx2(r0, prediction + 0, dst + (long)stride * 0);
    store_predicted_idct_row_avx2(r1, prediction + 8, dst + (long)stride * 1);
    store_predicted_idct_row_avx2(r2, prediction + 16, dst + (long)stride * 2);
    store_predicted_idct_row_avx2(r3, prediction + 24, dst + (long)stride * 3);
    store_predicted_idct_row_avx2(r4, prediction + 32, dst + (long)stride * 4);
    store_predicted_idct_row_avx2(r5, prediction + 40, dst + (long)stride * 5);
    store_predicted_idct_row_avx2(r6, prediction + 48, dst + (long)stride * 6);
    store_predicted_idct_row_avx2(r7, prediction + 56, dst + (long)stride * 7);
}

/* A separable inverse transform reconstructs a sparse block as the DC level
   plus one outer product per AC coefficient.  These are the exact one-pass
   AAN responses used by the full transform, kept as eight tiny basis rows. */
static void init_sparse_inverse_basis(void) {
    for (int frequency = 0; frequency < 8; frequency++) {
        float values[8] = {0};
        values[frequency] = 1.0f;
        idct_pass(values, 1);
        memcpy(sparse_inverse_basis[frequency], values, sizeof(values));
    }
}

__attribute__((target("avx2")))
void idct_block_store_single_avx2(float dc, float ac, int index,
                                  unsigned char *dst, int stride) {
    int vertical_frequency = index >> 3;
    int horizontal_frequency = index & 7;
    __m256 horizontal =
        _mm256_loadu_ps(sparse_inverse_basis[horizontal_frequency]);
    const __m256 dc_vector = _mm256_set1_ps(dc);
    const __m256 shift = _mm256_set1_ps(128.0f);
    const __m256 round = _mm256_set1_ps(0.5f);
    for (int row = 0; row < 8; row++) {
        float vertical = ac * sparse_inverse_basis[vertical_frequency][row];
        __m256 value = _mm256_add_ps(
            dc_vector, _mm256_mul_ps(_mm256_set1_ps(vertical), horizontal));
        store_idct_row_avx2(value, dst + (long)stride * row, shift, round);
    }
}

__attribute__((target("avx2")))
void idct_block_store_two_avx2(float dc,
                               float first_ac, int first_index,
                               float second_ac, int second_index,
                               unsigned char *dst, int stride) {
    int first_vertical = first_index >> 3;
    int second_vertical = second_index >> 3;
    __m256 first_horizontal =
        _mm256_loadu_ps(sparse_inverse_basis[first_index & 7]);
    __m256 second_horizontal =
        _mm256_loadu_ps(sparse_inverse_basis[second_index & 7]);
    const __m256 dc_vector = _mm256_set1_ps(dc);
    const __m256 shift = _mm256_set1_ps(128.0f);
    const __m256 round = _mm256_set1_ps(0.5f);
    for (int row = 0; row < 8; row++) {
        float first = first_ac * sparse_inverse_basis[first_vertical][row];
        float second = second_ac * sparse_inverse_basis[second_vertical][row];
        __m256 value = _mm256_add_ps(
            dc_vector, _mm256_mul_ps(_mm256_set1_ps(first), first_horizontal));
        value = _mm256_add_ps(
            value, _mm256_mul_ps(_mm256_set1_ps(second), second_horizontal));
        store_idct_row_avx2(value, dst + (long)stride * row, shift, round);
    }
}

__attribute__((target("avx2")))
void idct_block_store_three_avx2(float dc,
                                 float first_ac, int first_index,
                                 float second_ac, int second_index,
                                 float third_ac, int third_index,
                                 unsigned char *dst, int stride) {
    int first_vertical = first_index >> 3;
    int second_vertical = second_index >> 3;
    int third_vertical = third_index >> 3;
    __m256 first_horizontal =
        _mm256_loadu_ps(sparse_inverse_basis[first_index & 7]);
    __m256 second_horizontal =
        _mm256_loadu_ps(sparse_inverse_basis[second_index & 7]);
    __m256 third_horizontal =
        _mm256_loadu_ps(sparse_inverse_basis[third_index & 7]);
    const __m256 dc_vector = _mm256_set1_ps(dc);
    const __m256 shift = _mm256_set1_ps(128.0f);
    const __m256 round = _mm256_set1_ps(0.5f);
    for (int row = 0; row < 8; row++) {
        float first = first_ac * sparse_inverse_basis[first_vertical][row];
        float second = second_ac * sparse_inverse_basis[second_vertical][row];
        float third = third_ac * sparse_inverse_basis[third_vertical][row];
        __m256 value = _mm256_add_ps(
            dc_vector, _mm256_mul_ps(_mm256_set1_ps(first), first_horizontal));
        value = _mm256_add_ps(
            value, _mm256_mul_ps(_mm256_set1_ps(second), second_horizontal));
        value = _mm256_add_ps(
            value, _mm256_mul_ps(_mm256_set1_ps(third), third_horizontal));
        store_idct_row_avx2(value, dst + (long)stride * row, shift, round);
    }
}

#endif

// ============================================================
// DISPATCH
// ============================================================

void dct_block_fast(const float block[64], float coef[64]) {
#if defined(__x86_64__) || defined(__i386__)
    if (n148_cpu_level() >= N148_CPU_AVX2) {
        dct_block_avx2(block, coef);
        return;
    }
#endif
    dct_scalar(block, coef);
}

void idct_block_fast(const float coef[64], float block[64]) {
#if defined(__x86_64__) || defined(__i386__)
    if (n148_cpu_level() >= N148_CPU_AVX2) {
        idct_block_avx2(coef, block);
        return;
    }
#endif
    n148_idct_block_scalar(coef, block);
}

src/ppm.h

O ppm.h cuida da leitura do PPM e da conversão entre RGB e YCbCr, dos artigos 15 e 2. Na V2, ele ganhou a redução da cor que leva em conta a reconstrução, do artigo 35, e a projeção do brilho a partir da cor, do artigo 38.

Na V1, o arquivo tinha 39 linhas:

#ifndef PPM_H
#define PPM_H

// An RGB image loaded from a PPM file.
typedef struct {
    int width;
    int height;
    unsigned char *pixels; // RGB interleaved: R,G,B,R,G,B...
} Image;

// A single 8-bit channel (Y, Cb, or Cr). Chroma planes can be
// smaller than the image when subsampling is enabled.
typedef struct {
    int width;
    int height;
    unsigned char *data;
} Plane;

int load_ppm(const char *path, Image *image);
int save_ppm(const char *path, Image *image);
void free_image(Image *image);

Plane create_plane(int width, int height);
void free_plane(Plane *plane);

// Reads a pixel while clamping coordinates to the plane edges.
// This provides padding for partial 8x8 blocks.
int plane_sample(Plane *plane, int x, int y);

// Calculates the stored chroma-plane size for a subsampling mode.
void chroma_dimensions(int mode, int width, int height, int *cw, int *ch);

// Splits an RGB image into Y, Cb, and Cr planes.
int split_channels(Image *image, Plane *y, Plane *cb, Plane *cr,
                   int chroma_mode);

int save_pgm(const char *path, Plane *plane);

#endif

Na V2, ele ficou com 64 linhas:

#ifndef PPM_H
#define PPM_H

#include <stddef.h>

// An RGB image loaded from a PPM file.
typedef struct {
    int width;
    int height;
    unsigned char *pixels; // RGB interleaved: R,G,B,R,G,B...
} Image;

// A single 8-bit channel (Y, Cb, or Cr). Chroma planes can be
// smaller than the image when subsampling is enabled.
typedef struct {
    int width;
    int height;
    unsigned char *data;
} Plane;

int load_ppm(const char *path, Image *image);
int save_ppm(const char *path, Image *image);
void free_image(Image *image);

Plane create_plane(int width, int height);
void free_plane(Plane *plane);

// Reads a pixel while clamping coordinates to the plane edges.
// This provides padding for partial 8x8 blocks.
int plane_sample(Plane *plane, int x, int y);

// Calculates the stored chroma-plane size for a subsampling mode.
void chroma_dimensions(int mode, int width, int height, int *cw, int *ch);

// Splits an RGB image into Y, Cb, and Cr planes.
int split_channels(Image *image, Plane *y, Plane *cb, Plane *cr,
                   int chroma_mode);

/* Select the deterministic perceptual colour transform while
   retaining the same three-plane and chroma-subsampling layout. */
int n148_split_channels_ex(Image *image, Plane *first, Plane *second,
                           Plane *third, int chroma_mode,
                           int perceptual_color);

/* Encoder-side reconstruction-aware 4:2:2/4:2:0 colour preparation.
   minimizes error after the decoder's normative 3:1 interpolation on each
   reduced axis; 4:4:4 falls back to the ordinary full-resolution path. */
int n148_split_channels_reconstruction_aware(Image *image, Plane *y, Plane *cb, Plane *cr,
                           int chroma_mode, int reconstruction_aware);

/* Non-owning reference valid for one complete encoder invocation. */
typedef struct {
    const unsigned char *pixels;
    size_t stride;
    int width, height;
} N148RgbSource;

/* Encoder-only luma preparation from retained quantized/filtered chroma. */
int n148_project_luma_from_chroma(const N148RgbSource *reference,
    const Plane *source, const Plane *cb, const Plane *cr, Plane *corrected);

int save_pgm(const char *path, Plane *plane);

#endif

src/ppm.c

O ppm.c implementa tudo isso, e na V2 ele mais que dobrou de tamanho, com a conversão de cor em AVX2, a redução da cor consciente da reconstrução e a projeção do brilho.

Na V1, o arquivo tinha 560 linhas:

#include <stdio.h>
#include <stdlib.h>

#include "header.h"
#include <string.h>
#include "ppm.h"
#include "cpu.h"
#include "parallel.h"

// PPM header parsing helpers carried forward from article 15.
static void skip_whitespace_and_comments(FILE *file) {
    int character;

    for (;;) {
        character = fgetc(file);
        if (character == '#') {
            while (character != '\n' && character != EOF) {
                character = fgetc(file);
            }
        } else if (character == ' ' || character == '\t' ||
                   character == '\n' || character == '\r') {
            continue;
        } else {
            ungetc(character, file);
            return;
        }
    }
}

static int read_number(FILE *file) {
    skip_whitespace_and_comments(file);

    int value = 0;
    int character;
    int digits = 0;

    while ((character = fgetc(file)) != EOF &&
           character >= '0' && character <= '9') {
        value = value * 10 + (character - '0');
        digits++;
    }

    return digits ? value : -1;
}

int load_ppm(const char *path, Image *image) {
    FILE *file = fopen(path, "rb");
    if (!file) {
        printf("Could not open '%s'. Is the file in the images/ folder?\n", path);
        return 0;
    }

    char magic[3] = {0};
    if (fread(magic, 1, 2, file) != 2) {
        fclose(file);
        return 0;
    }
    if (magic[0] != 'P' || magic[1] != '6') {
        printf("Not a binary PPM (P6). Found '%s'.\n", magic);
        fclose(file);
        return 0;
    }

    int width = read_number(file);
    int height = read_number(file);
    int maxval = read_number(file);

    if (width <= 0 || height <= 0 || maxval != 255) {
        printf("Unsupported PPM header.\n");
        fclose(file);
        return 0;
    }

    long byte_count = (long)width * height * 3;
    unsigned char *pixels = (unsigned char *)malloc((size_t)byte_count);
    if (!pixels) {
        fclose(file);
        return 0;
    }

    if (fread(pixels, 1, (size_t)byte_count, file) != (size_t)byte_count) {
        printf("Pixel data ended too early.\n");
        free(pixels);
        fclose(file);
        return 0;
    }

    fclose(file);
    image->width = width;
    image->height = height;
    image->pixels = pixels;
    return 1;
}

int save_ppm(const char *path, Image *image) {
    FILE *file = fopen(path, "wb");
    if (!file) {
        return 0;
    }

    long byte_count = (long)image->width * image->height * 3;
    int header_ok =
        fprintf(file, "P6\n%d %d\n255\n", image->width, image->height) > 0;
    int pixels_ok =
        fwrite(image->pixels, 1, (size_t)byte_count, file) ==
        (size_t)byte_count;
    int close_ok = fclose(file) == 0;
    return header_ok && pixels_ok && close_ok;
}

void free_image(Image *image) {
    free(image->pixels);
    image->pixels = NULL;
}

Plane create_plane(int width, int height) {
    Plane plane;
    plane.width = width;
    plane.height = height;
    plane.data = (unsigned char *)malloc((size_t)((long)width * height));
    return plane;
}

void free_plane(Plane *plane) {
    free(plane->data);
    plane->data = NULL;
}

// Clamping the coordinates is the padding for partial blocks.
int plane_sample(Plane *plane, int x, int y) {
    if (x < 0) {
        x = 0;
    }
    if (y < 0) {
        y = 0;
    }
    if (x >= plane->width) {
        x = plane->width - 1;
    }
    if (y >= plane->height) {
        y = plane->height - 1;
    }

    return plane->data[(long)y * plane->width + x];
}

void chroma_dimensions(int mode, int width, int height, int *cw, int *ch) {
    switch (mode) {
        case CHROMA_422:
            *cw = (width + 1) / 2;
            *ch = height;
            break;
        case CHROMA_420:
            *cw = (width + 1) / 2;
            *ch = (height + 1) / 2;
            break;
        default:
            *cw = width;
            *ch = height;
            break;
    }
}

// Average all full-resolution samples represented by one stored chroma
// sample. Clamping duplicates the final row or column for odd dimensions.
static void downsample_plane(unsigned char *full, int width, int height,
                             Plane *output, int step_x, int step_y) {
    // The 2x2 case is by far the most common, so it gets a tight loop
    // with no per-sample bounds checks in the interior.
    if (step_x == 2 && step_y == 2 && (width & 1) == 0 && (height & 1) == 0) {
        for (int y = 0; y < output->height; y++) {
            const unsigned char *r0 = full + (long)(y*2)     * width;
            const unsigned char *r1 = full + (long)(y*2 + 1) * width;
            unsigned char *dst = output->data + (long) y * output->width;
            for (int x = 0; x < output->width; x++) {
                int sx = x * 2;
                dst[x] = (unsigned char)((r0[sx] + r0[sx+1] + r1[sx] + r1[sx+1] + 2) >> 2);
            }
        }
        return;
    }
    if (step_x == 1 && step_y == 1) {
        for (int y = 0; y < output->height; y++)
            memcpy(output->data + (long) y * output->width,
                   full + (long) y * width, output->width);
        return;
    }

    for (int y = 0; y < output->height; y++) {
        for (int x = 0; x < output->width; x++) {
            int sum = 0;
            int count = 0;

            for (int dy = 0; dy < step_y; dy++) {
                for (int dx = 0; dx < step_x; dx++) {
                    int source_x = x * step_x + dx;
                    int source_y = y * step_y + dy;
                    if (source_x >= width) {
                        source_x = width - 1;
                    }
                    if (source_y >= height) {
                        source_y = height - 1;
                    }
                    sum += full[(long)source_y * width + source_x];
                    count++;
                }
            }

            output->data[(long)y * output->width + x] =
                (unsigned char)((sum + count / 2) / count);
        }
    }
}

// ============================================================
// RGB -> YCbCr
// ============================================================
//
// The scalar version below is the readable reference. The vector
// version does the same arithmetic on eight pixels at a time, using
// fixed point integers: the coefficients are pre-multiplied by 2^16
// so the whole conversion stays in integer registers, which keeps
// every lane busy and avoids float conversions per pixel.

#define YCC_FIX_BITS 16
#define YCC_FIX(x)   ((int)((x) * (1 << YCC_FIX_BITS) + 0.5))
#define YCC_HALF     (1 << (YCC_FIX_BITS - 1))
#define YCC_OFFSET   ((128 << YCC_FIX_BITS) + YCC_HALF)

static const int YCC_YR =  YCC_FIX(0.299000);
static const int YCC_YG =  YCC_FIX(0.587000);
static const int YCC_YB =  YCC_FIX(0.114000);
static const int YCC_CBR = -YCC_FIX(0.168736);
static const int YCC_CBG = -YCC_FIX(0.331264);
static const int YCC_CBB =  YCC_FIX(0.500000);
static const int YCC_CRR =  YCC_FIX(0.500000);
static const int YCC_CRG = -YCC_FIX(0.418688);
static const int YCC_CRB = -YCC_FIX(0.081312);

static void rgb_to_ycbcr_scalar(const unsigned char *rgb, long count,
                                unsigned char *y, unsigned char *cb,
                                unsigned char *cr) {
    for (long i = 0; i < count; i++) {
        int red   = rgb[i*3 + 0];
        int green = rgb[i*3 + 1];
        int blue  = rgb[i*3 + 2];

        int luma = (YCC_YR * red + YCC_YG * green + YCC_YB * blue + YCC_HALF)
                   >> YCC_FIX_BITS;
        int blue_diff = (YCC_CBR * red + YCC_CBG * green + YCC_CBB * blue
                         + YCC_OFFSET) >> YCC_FIX_BITS;
        int red_diff  = (YCC_CRR * red + YCC_CRG * green + YCC_CRB * blue
                         + YCC_OFFSET) >> YCC_FIX_BITS;

        y[i]  = (unsigned char)(luma      < 0 ? 0 : luma      > 255 ? 255 : luma);
        cb[i] = (unsigned char)(blue_diff < 0 ? 0 : blue_diff > 255 ? 255 : blue_diff);
        cr[i] = (unsigned char)(red_diff  < 0 ? 0 : red_diff  > 255 ? 255 : red_diff);
    }
}

#if defined(__x86_64__) || defined(__i386__)
#include <immintrin.h>

__attribute__((target("avx2")))
static void rgb_to_ycbcr_avx2(const unsigned char *rgb, long count,
                              unsigned char *y, unsigned char *cb,
                              unsigned char *cr) {
    // Pixels arrive interleaved as R G B R G B ... A byte shuffle
    // pulls the three channels apart without touching memory: each
    // 128 bit lane holds four pixels, so one 256 bit register covers
    // eight pixels per iteration.
    const __m256i shuffle_r = _mm256_setr_epi8(
        0,-1,-1,-1, 3,-1,-1,-1, 6,-1,-1,-1, 9,-1,-1,-1,
        0,-1,-1,-1, 3,-1,-1,-1, 6,-1,-1,-1, 9,-1,-1,-1);
    const __m256i shuffle_g = _mm256_setr_epi8(
        1,-1,-1,-1, 4,-1,-1,-1, 7,-1,-1,-1,10,-1,-1,-1,
        1,-1,-1,-1, 4,-1,-1,-1, 7,-1,-1,-1,10,-1,-1,-1);
    const __m256i shuffle_b = _mm256_setr_epi8(
        2,-1,-1,-1, 5,-1,-1,-1, 8,-1,-1,-1,11,-1,-1,-1,
        2,-1,-1,-1, 5,-1,-1,-1, 8,-1,-1,-1,11,-1,-1,-1);

    const __m256i yr = _mm256_set1_epi32(YCC_YR);
    const __m256i yg = _mm256_set1_epi32(YCC_YG);
    const __m256i cbr = _mm256_set1_epi32(YCC_CBR);
    const __m256i cbg = _mm256_set1_epi32(YCC_CBG);
    const __m256i crr = _mm256_set1_epi32(YCC_CRR);
    const __m256i crg = _mm256_set1_epi32(YCC_CRG);
    const __m256i half   = _mm256_set1_epi32(YCC_HALF);
    const __m256i offset = _mm256_set1_epi32(YCC_OFFSET);

    long i = 0;
    // Stop early: the high lane reads twelve bytes ahead, so the tail
    // is finished by the scalar routine to stay inside the buffer.
    for (; i + 12 <= count; i += 8) {
        const unsigned char *p = rgb + i * 3;
        __m128i lo = _mm_loadu_si128((const __m128i *)(p));
        __m128i hi = _mm_loadu_si128((const __m128i *)(p + 12));
        __m256i packed = _mm256_set_m128i(hi, lo);

        __m256i r = _mm256_shuffle_epi8(packed, shuffle_r);
        __m256i g = _mm256_shuffle_epi8(packed, shuffle_g);
        __m256i b = _mm256_shuffle_epi8(packed, shuffle_b);
        __m256i rb = _mm256_sub_epi32(r, b);
        __m256i gb = _mm256_sub_epi32(g, b);

        // Every coefficient triplet sums to either 1.0 (Y) or zero
        // (chroma).  Factoring B out removes one 32-bit multiply per
        // channel while remaining exactly equivalent in integer arithmetic.
        __m256i luma = _mm256_add_epi32(
            _mm256_add_epi32(_mm256_mullo_epi32(rb, yr),
                             _mm256_mullo_epi32(gb, yg)),
            _mm256_add_epi32(_mm256_slli_epi32(b, YCC_FIX_BITS), half));
        __m256i blue_diff = _mm256_add_epi32(
            _mm256_add_epi32(_mm256_mullo_epi32(rb, cbr),
                             _mm256_mullo_epi32(gb, cbg)), offset);
        __m256i red_diff = _mm256_add_epi32(
            _mm256_add_epi32(_mm256_mullo_epi32(rb, crr),
                             _mm256_mullo_epi32(gb, crg)), offset);

        luma      = _mm256_srai_epi32(luma,      YCC_FIX_BITS);
        blue_diff = _mm256_srai_epi32(blue_diff, YCC_FIX_BITS);
        red_diff  = _mm256_srai_epi32(red_diff,  YCC_FIX_BITS);

        // Packing with unsigned saturation performs the 0..255 clamp
        // for free, so no comparison is needed on the way out.
        __m128i y16 = _mm_packs_epi32(_mm256_castsi256_si128(luma),
                                      _mm256_extracti128_si256(luma, 1));
        __m128i b16 = _mm_packs_epi32(_mm256_castsi256_si128(blue_diff),
                                      _mm256_extracti128_si256(blue_diff, 1));
        __m128i r16 = _mm_packs_epi32(_mm256_castsi256_si128(red_diff),
                                      _mm256_extracti128_si256(red_diff, 1));

        _mm_storel_epi64((__m128i *)(y  + i), _mm_packus_epi16(y16, y16));
        _mm_storel_epi64((__m128i *)(cb + i), _mm_packus_epi16(b16, b16));
        _mm_storel_epi64((__m128i *)(cr + i), _mm_packus_epi16(r16, r16));
    }

    if (i < count)
        rgb_to_ycbcr_scalar(rgb + i*3, count - i, y + i, cb + i, cr + i);
}
#endif

typedef struct {
    const unsigned char *rgb;
    unsigned char *y, *cb, *cr;
    int width;
} ColorJob;

static void rgb_to_ycbcr(const unsigned char *rgb, long count,
                         unsigned char *y, unsigned char *cb, unsigned char *cr) {
#if defined(__x86_64__) || defined(__i386__)
    if (n148_cpu_level() >= N148_CPU_AVX2) {
        rgb_to_ycbcr_avx2(rgb, count, y, cb, cr);
        return;
    }
#endif
    rgb_to_ycbcr_scalar(rgb, count, y, cb, cr);
}

static void color_rows(long start, long end, int worker, void *context) {
    (void) worker;
    ColorJob *job = (ColorJob *) context;
    for (long row = start; row < end; row++) {
        long offset = row * job->width;
        rgb_to_ycbcr(job->rgb + offset * 3, job->width,
                     job->y + offset, job->cb + offset, job->cr + offset);
    }
}

#if defined(__x86_64__) || defined(__i386__)
__attribute__((target("avx2")))
static void downsample_420_rows_avx2(const unsigned char *cb0,
                                     const unsigned char *cb1,
                                     const unsigned char *cr0,
                                     const unsigned char *cr1,
                                     int width, unsigned char *out_cb,
                                     unsigned char *out_cr, int out_width) {
    const __m256i ones = _mm256_set1_epi8(1);
    const __m256i two = _mm256_set1_epi16(2);
    int x = 0;
    for (; x + 16 <= out_width && 2 * x + 32 <= width; x += 16) {
        int source = x * 2;
        __m256i cb_top = _mm256_loadu_si256((const __m256i *)(cb0 + source));
        __m256i cb_bottom = _mm256_loadu_si256((const __m256i *)(cb1 + source));
        __m256i cr_top = _mm256_loadu_si256((const __m256i *)(cr0 + source));
        __m256i cr_bottom = _mm256_loadu_si256((const __m256i *)(cr1 + source));
        __m256i cb_sum = _mm256_add_epi16(_mm256_maddubs_epi16(cb_top, ones),
                                          _mm256_maddubs_epi16(cb_bottom, ones));
        __m256i cr_sum = _mm256_add_epi16(_mm256_maddubs_epi16(cr_top, ones),
                                          _mm256_maddubs_epi16(cr_bottom, ones));
        cb_sum = _mm256_srli_epi16(_mm256_add_epi16(cb_sum, two), 2);
        cr_sum = _mm256_srli_epi16(_mm256_add_epi16(cr_sum, two), 2);
        __m128i cb_bytes = _mm_packus_epi16(_mm256_castsi256_si128(cb_sum),
                                            _mm256_extracti128_si256(cb_sum, 1));
        __m128i cr_bytes = _mm_packus_epi16(_mm256_castsi256_si128(cr_sum),
                                            _mm256_extracti128_si256(cr_sum, 1));
        _mm_storeu_si128((__m128i *)(out_cb + x), cb_bytes);
        _mm_storeu_si128((__m128i *)(out_cr + x), cr_bytes);
    }
    for (; x < out_width; x++) {
        int source = x * 2;
        int next = source + 1 < width ? source + 1 : width - 1;
        out_cb[x] = (unsigned char)((cb0[source] + cb0[next] +
                                     cb1[source] + cb1[next] + 2) >> 2);
        out_cr[x] = (unsigned char)((cr0[source] + cr0[next] +
                                     cr1[source] + cr1[next] + 2) >> 2);
    }
}
#endif

typedef struct {
    const Image *image;
    Plane *y, *cb, *cr;
    int use_avx2;
    int failed;
} Color420Job;

static void color_420_rows(long start, long end, int worker, void *context) {
    (void)worker;
    Color420Job *job = (Color420Job *)context;
    int width = job->image->width;
    int height = job->image->height;

#define COLOR_STACK_WIDTH 2048
    _Alignas(32) unsigned char stack_rows[COLOR_STACK_WIDTH * 4];
    unsigned char *allocated = NULL;
    unsigned char *cb0;
    if (width <= COLOR_STACK_WIDTH) {
        cb0 = stack_rows;
    } else {
        allocated = (unsigned char *)malloc((size_t)width * 4);
        if (!allocated) {
#if defined(__GNUC__) || defined(__clang__)
            __atomic_store_n(&job->failed, 1, __ATOMIC_RELAXED);
#else
            job->failed = 1;
#endif
            return;
        }
        cb0 = allocated;
    }
    unsigned char *cr0 = cb0 + width;
    unsigned char *cb1 = cr0 + width;
    unsigned char *cr1 = cb1 + width;

    for (long cy = start; cy < end; cy++) {
        int row0 = (int)cy * 2;
        int row1 = row0 + 1;
        const unsigned char *rgb0 = job->image->pixels + (long)row0 * width * 3;
        rgb_to_ycbcr(rgb0, width, job->y->data + (long)row0 * width, cb0, cr0);
        if (row1 < height) {
            const unsigned char *rgb1 = job->image->pixels + (long)row1 * width * 3;
            rgb_to_ycbcr(rgb1, width, job->y->data + (long)row1 * width, cb1, cr1);
        } else {
            memcpy(cb1, cb0, (size_t)width);
            memcpy(cr1, cr0, (size_t)width);
        }

        unsigned char *out_cb = job->cb->data + cy * job->cb->width;
        unsigned char *out_cr = job->cr->data + cy * job->cr->width;
#if defined(__x86_64__) || defined(__i386__)
        if (job->use_avx2) {
            downsample_420_rows_avx2(cb0, cb1, cr0, cr1, width,
                                     out_cb, out_cr, job->cb->width);
            continue;
        }
#endif
        for (int x = 0; x < job->cb->width; x++) {
            int source = x * 2;
            int next = source + 1 < width ? source + 1 : width - 1;
            out_cb[x] = (unsigned char)((cb0[source] + cb0[next] +
                                         cb1[source] + cb1[next] + 2) >> 2);
            out_cr[x] = (unsigned char)((cr0[source] + cr0[next] +
                                         cr1[source] + cr1[next] + 2) >> 2);
        }
    }
    free(allocated);
#undef COLOR_STACK_WIDTH
}

int split_channels(Image *image, Plane *y, Plane *cb, Plane *cr,
                   int chroma_mode) {
    int width = image->width;
    int height = image->height;
    long pixel_count = (long)width * height;

    int chroma_width;
    int chroma_height;
    chroma_dimensions(chroma_mode, width, height,
                      &chroma_width, &chroma_height);
    *y = create_plane(width, height);
    *cb = create_plane(chroma_width, chroma_height);
    *cr = create_plane(chroma_width, chroma_height);
    if (!y->data || !cb->data || !cr->data) {
        free_plane(y);
        free_plane(cb);
        free_plane(cr);
        return 0;
    }

    if (chroma_mode == CHROMA_444) {
        ColorJob job;
        job.rgb = image->pixels; job.y = y->data;
        job.cb = cb->data; job.cr = cr->data; job.width = width;
        n148_parallel_for(height, color_rows, &job);
        return 1;
    }

    if (chroma_mode == CHROMA_420) {
        Color420Job job;
        job.image = image; job.y = y; job.cb = cb; job.cr = cr;
        job.failed = 0;
#if defined(__x86_64__) || defined(__i386__)
        job.use_avx2 = (n148_cpu_level() >= N148_CPU_AVX2);
#else
        job.use_avx2 = 0;
#endif
        n148_parallel_for(chroma_height, color_420_rows, &job);
        if (job.failed) {
            free_plane(y); free_plane(cb); free_plane(cr);
            return 0;
        }
        return 1;
    }

    // 4:2:2 keeps the generic full-resolution intermediate.
    unsigned char *cb_full = (unsigned char *)malloc((size_t)pixel_count);
    unsigned char *cr_full = (unsigned char *)malloc((size_t)pixel_count);
    if (!cb_full || !cr_full) {
        free_plane(y); free_plane(cb); free_plane(cr);
        free(cb_full); free(cr_full);
        return 0;
    }
    ColorJob job;
    job.rgb = image->pixels; job.y = y->data;
    job.cb = cb_full; job.cr = cr_full; job.width = width;
    n148_parallel_for(height, color_rows, &job);

    int step_x = (chroma_mode == CHROMA_444) ? 1 : 2;
    int step_y = (chroma_mode == CHROMA_420) ? 2 : 1;
    downsample_plane(cb_full, width, height, cb, step_x, step_y);
    downsample_plane(cr_full, width, height, cr, step_x, step_y);

    free(cb_full);
    free(cr_full);
    return 1;
}

int save_pgm(const char *path, Plane *plane) {
    FILE *file = fopen(path, "wb");
    if (!file) {
        return 0;
    }

    fprintf(file, "P5\n%d %d\n255\n", plane->width, plane->height);
    fwrite(plane->data, 1,
           (size_t)((long)plane->width * plane->height), file);
    fclose(file);
    return 1;
}

Na V2, ele ficou com 1.164 linhas:

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

#include "header.h"
#include <string.h>
#include "ppm.h"
#include "cpu.h"
#include "parallel.h"
#include "perceptual.h"
#include "directional_intra.h"

// PPM header parsing helpers carried forward from article 15.
static void skip_whitespace_and_comments(FILE *file) {
    int character;

    for (;;) {
        character = fgetc(file);
        if (character == '#') {
            while (character != '\n' && character != EOF) {
                character = fgetc(file);
            }
        } else if (character == ' ' || character == '\t' ||
                   character == '\n' || character == '\r') {
            continue;
        } else {
            ungetc(character, file);
            return;
        }
    }
}

static int read_number(FILE *file) {
    skip_whitespace_and_comments(file);

    int value = 0;
    int character;
    int digits = 0;

    while ((character = fgetc(file)) != EOF &&
           character >= '0' && character <= '9') {
        value = value * 10 + (character - '0');
        digits++;
    }

    return digits ? value : -1;
}

int load_ppm(const char *path, Image *image) {
    FILE *file = fopen(path, "rb");
    if (!file) {
        printf("Could not open '%s'. Is the file in the images/ folder?\n", path);
        return 0;
    }

    char magic[3] = {0};
    if (fread(magic, 1, 2, file) != 2) {
        fclose(file);
        return 0;
    }
    if (magic[0] != 'P' || magic[1] != '6') {
        printf("Not a binary PPM (P6). Found '%s'.\n", magic);
        fclose(file);
        return 0;
    }

    int width = read_number(file);
    int height = read_number(file);
    int maxval = read_number(file);

    if (width <= 0 || height <= 0 || maxval != 255) {
        printf("Unsupported PPM header.\n");
        fclose(file);
        return 0;
    }

    long byte_count = (long)width * height * 3;
    unsigned char *pixels = (unsigned char *)malloc((size_t)byte_count);
    if (!pixels) {
        fclose(file);
        return 0;
    }

    if (fread(pixels, 1, (size_t)byte_count, file) != (size_t)byte_count) {
        printf("Pixel data ended too early.\n");
        free(pixels);
        fclose(file);
        return 0;
    }

    fclose(file);
    image->width = width;
    image->height = height;
    image->pixels = pixels;
    return 1;
}

int save_ppm(const char *path, Image *image) {
    FILE *file = fopen(path, "wb");
    if (!file) {
        return 0;
    }

    long byte_count = (long)image->width * image->height * 3;
    int header_ok =
        fprintf(file, "P6\n%d %d\n255\n", image->width, image->height) > 0;
    int pixels_ok =
        fwrite(image->pixels, 1, (size_t)byte_count, file) ==
        (size_t)byte_count;
    int close_ok = fclose(file) == 0;
    return header_ok && pixels_ok && close_ok;
}

void free_image(Image *image) {
    free(image->pixels);
    image->pixels = NULL;
}

Plane create_plane(int width, int height) {
    Plane plane;
    plane.width = width;
    plane.height = height;
    plane.data = (unsigned char *)malloc((size_t)((long)width * height));
    return plane;
}

void free_plane(Plane *plane) {
    free(plane->data);
    plane->data = NULL;
}

// Clamping the coordinates is the padding for partial blocks.
int plane_sample(Plane *plane, int x, int y) {
    if (x < 0) {
        x = 0;
    }
    if (y < 0) {
        y = 0;
    }
    if (x >= plane->width) {
        x = plane->width - 1;
    }
    if (y >= plane->height) {
        y = plane->height - 1;
    }

    return plane->data[(long)y * plane->width + x];
}

void chroma_dimensions(int mode, int width, int height, int *cw, int *ch) {
    switch (mode) {
        case CHROMA_422:
            *cw = width / 2 + (width & 1);
            *ch = height;
            break;
        case CHROMA_420:
            *cw = width / 2 + (width & 1);
            *ch = height / 2 + (height & 1);
            break;
        default:
            *cw = width;
            *ch = height;
            break;
    }
}

// Average all full-resolution samples represented by one stored chroma
// sample. Clamping duplicates the final row or column for odd dimensions.
static void downsample_plane(unsigned char *full, int width, int height,
                             Plane *output, int step_x, int step_y) {
    // The 2x2 case is by far the most common, so it gets a tight loop
    // with no per-sample bounds checks in the interior.
    if (step_x == 2 && step_y == 2 && (width & 1) == 0 && (height & 1) == 0) {
        for (int y = 0; y < output->height; y++) {
            const unsigned char *r0 = full + (long)(y*2)     * width;
            const unsigned char *r1 = full + (long)(y*2 + 1) * width;
            unsigned char *dst = output->data + (long) y * output->width;
            for (int x = 0; x < output->width; x++) {
                int sx = x * 2;
                dst[x] = (unsigned char)((r0[sx] + r0[sx+1] + r1[sx] + r1[sx+1] + 2) >> 2);
            }
        }
        return;
    }
    if (step_x == 1 && step_y == 1) {
        for (int y = 0; y < output->height; y++)
            memcpy(output->data + (long) y * output->width,
                   full + (long) y * width, output->width);
        return;
    }

    for (int y = 0; y < output->height; y++) {
        for (int x = 0; x < output->width; x++) {
            int sum = 0;
            int count = 0;

            for (int dy = 0; dy < step_y; dy++) {
                for (int dx = 0; dx < step_x; dx++) {
                    int source_x = x * step_x + dx;
                    int source_y = y * step_y + dy;
                    if (source_x >= width) {
                        source_x = width - 1;
                    }
                    if (source_y >= height) {
                        source_y = height - 1;
                    }
                    sum += full[(long)source_y * width + source_x];
                    count++;
                }
            }

            output->data[(long)y * output->width + x] =
                (unsigned char)((sum + count / 2) / count);
        }
    }
}

// ============================================================
// RGB -> YCbCr
// ============================================================
//
// The scalar version below is the readable reference. The vector
// version does the same arithmetic on eight pixels at a time, using
// fixed point integers: the coefficients are pre-multiplied by 2^16
// so the whole conversion stays in integer registers, which keeps
// every lane busy and avoids float conversions per pixel.

#define YCC_FIX_BITS 16
#define YCC_FIX(x)   ((int)((x) * (1 << YCC_FIX_BITS) + 0.5))
#define YCC_HALF     (1 << (YCC_FIX_BITS - 1))
#define YCC_OFFSET   ((128 << YCC_FIX_BITS) + YCC_HALF)

static const int YCC_YR =  YCC_FIX(0.299000);
static const int YCC_YG =  YCC_FIX(0.587000);
static const int YCC_YB =  YCC_FIX(0.114000);
static const int YCC_CBR = -YCC_FIX(0.168736);
static const int YCC_CBG = -YCC_FIX(0.331264);
static const int YCC_CBB =  YCC_FIX(0.500000);
static const int YCC_CRR =  YCC_FIX(0.500000);
static const int YCC_CRG = -YCC_FIX(0.418688);
static const int YCC_CRB = -YCC_FIX(0.081312);

static void rgb_to_ycbcr_scalar(const unsigned char *rgb, long count,
                                unsigned char *y, unsigned char *cb,
                                unsigned char *cr) {
    for (long i = 0; i < count; i++) {
        int red   = rgb[i*3 + 0];
        int green = rgb[i*3 + 1];
        int blue  = rgb[i*3 + 2];

        int luma = (YCC_YR * red + YCC_YG * green + YCC_YB * blue + YCC_HALF)
                   >> YCC_FIX_BITS;
        int blue_diff = (YCC_CBR * red + YCC_CBG * green + YCC_CBB * blue
                         + YCC_OFFSET) >> YCC_FIX_BITS;
        int red_diff  = (YCC_CRR * red + YCC_CRG * green + YCC_CRB * blue
                         + YCC_OFFSET) >> YCC_FIX_BITS;

        y[i]  = (unsigned char)(luma      < 0 ? 0 : luma      > 255 ? 255 : luma);
        cb[i] = (unsigned char)(blue_diff < 0 ? 0 : blue_diff > 255 ? 255 : blue_diff);
        cr[i] = (unsigned char)(red_diff  < 0 ? 0 : red_diff  > 255 ? 255 : red_diff);
    }
}

#if defined(__x86_64__) || defined(__i386__)
#include <immintrin.h>

__attribute__((target("avx2"), always_inline))
static inline void convert_rgb8_avx2(const unsigned char *rgb,
                                     __m128i *packed_y,
                                     __m128i *packed_cb,
                                     __m128i *packed_cr) {
    const __m256i shuffle_r = _mm256_setr_epi8(
        0,-1,-1,-1, 3,-1,-1,-1, 6,-1,-1,-1, 9,-1,-1,-1,
        0,-1,-1,-1, 3,-1,-1,-1, 6,-1,-1,-1, 9,-1,-1,-1);
    const __m256i shuffle_g = _mm256_setr_epi8(
        1,-1,-1,-1, 4,-1,-1,-1, 7,-1,-1,-1,10,-1,-1,-1,
        1,-1,-1,-1, 4,-1,-1,-1, 7,-1,-1,-1,10,-1,-1,-1);
    const __m256i shuffle_b = _mm256_setr_epi8(
        2,-1,-1,-1, 5,-1,-1,-1, 8,-1,-1,-1,11,-1,-1,-1,
        2,-1,-1,-1, 5,-1,-1,-1, 8,-1,-1,-1,11,-1,-1,-1);
    __m128i lo = _mm_loadu_si128((const __m128i *)rgb);
    __m128i hi = _mm_loadu_si128((const __m128i *)(rgb + 12));
    __m256i source = _mm256_set_m128i(hi, lo);
    __m256i r = _mm256_shuffle_epi8(source, shuffle_r);
    __m256i g = _mm256_shuffle_epi8(source, shuffle_g);
    __m256i b = _mm256_shuffle_epi8(source, shuffle_b);
    __m256i rb = _mm256_sub_epi32(r, b);
    __m256i gb = _mm256_sub_epi32(g, b);
    __m256i pair_low = _mm256_unpacklo_epi32(rb, gb);
    __m256i pair_high = _mm256_unpackhi_epi32(rb, gb);
    __m256i differences = _mm256_packs_epi32(pair_low, pair_high);
    /* rb and gb fit signed 16 bits. Madd calculates both color terms per
       pixel; correct coefficients above INT16_MAX with one exact shift. */
    const __m256i y_coefficients = _mm256_set1_epi32(
        (int32_t)((uint16_t) YCC_YR | ((uint32_t)(uint16_t) YCC_YG << 16)));
    const __m256i cb_coefficients = _mm256_set1_epi32(
        (int32_t)((uint16_t) YCC_CBR | ((uint32_t)(uint16_t) YCC_CBG << 16)));
    const __m256i cr_coefficients = _mm256_set1_epi32(
        (int32_t)((uint16_t) YCC_CRR | ((uint32_t)(uint16_t) YCC_CRG << 16)));
    __m256i luma = _mm256_add_epi32(
        _mm256_add_epi32(_mm256_madd_epi16(differences, y_coefficients),
                         _mm256_slli_epi32(gb, 16)),
        _mm256_add_epi32(
            _mm256_slli_epi32(b, YCC_FIX_BITS),
            _mm256_set1_epi32(YCC_HALF)));
    __m256i blue_diff = _mm256_add_epi32(
        _mm256_madd_epi16(differences, cb_coefficients),
        _mm256_set1_epi32(YCC_OFFSET));
    __m256i red_diff = _mm256_add_epi32(
        _mm256_add_epi32(_mm256_madd_epi16(differences, cr_coefficients),
                         _mm256_slli_epi32(rb, 16)),
        _mm256_set1_epi32(YCC_OFFSET));
    luma = _mm256_srai_epi32(luma, YCC_FIX_BITS);
    blue_diff = _mm256_srai_epi32(blue_diff, YCC_FIX_BITS);
    red_diff = _mm256_srai_epi32(red_diff, YCC_FIX_BITS);
    __m128i y16 = _mm_packs_epi32(
        _mm256_castsi256_si128(luma), _mm256_extracti128_si256(luma, 1));
    __m128i cb16 = _mm_packs_epi32(
        _mm256_castsi256_si128(blue_diff),
        _mm256_extracti128_si256(blue_diff, 1));
    __m128i cr16 = _mm_packs_epi32(
        _mm256_castsi256_si128(red_diff),
        _mm256_extracti128_si256(red_diff, 1));
    *packed_y = _mm_packus_epi16(y16, y16);
    *packed_cb = _mm_packus_epi16(cb16, cb16);
    *packed_cr = _mm_packus_epi16(cr16, cr16);
}

__attribute__((target("avx2")))
static void rgb_to_ycbcr_avx2(const unsigned char *rgb, long count,
                              unsigned char *y, unsigned char *cb,
                              unsigned char *cr) {
    long i = 0;
    // Stop early: the high lane reads twelve bytes ahead, so the tail
    // is finished by the scalar routine to stay inside the buffer.
    for (; i + 12 <= count; i += 8) {
        const unsigned char *p = rgb + i * 3;
        __m128i y8, cb8, cr8;
        convert_rgb8_avx2(p, &y8, &cb8, &cr8);
        _mm_storel_epi64((__m128i *)(y + i), y8);
        _mm_storel_epi64((__m128i *)(cb + i), cb8);
        _mm_storel_epi64((__m128i *)(cr + i), cr8);
    }

    if (i < count)
        rgb_to_ycbcr_scalar(rgb + i*3, count - i, y + i, cb + i, cr + i);
}
#endif

typedef struct {
    const unsigned char *rgb;
    unsigned char *y, *cb, *cr;
    int width;
    int perceptual_color;
} ColorJob;

static void rgb_to_ycbcr(const unsigned char *rgb, long count,
                         unsigned char *y, unsigned char *cb, unsigned char *cr) {
#if defined(__x86_64__) || defined(__i386__)
    if (n148_cpu_level() >= N148_CPU_AVX2) {
        rgb_to_ycbcr_avx2(rgb, count, y, cb, cr);
        return;
    }
#endif
    rgb_to_ycbcr_scalar(rgb, count, y, cb, cr);
}

static void rgb_to_coding_planes(const unsigned char *rgb, long count,
                                 unsigned char *first,
                                 unsigned char *second,
                                 unsigned char *third,
                                 int perceptual_color) {
    if (perceptual_color) {
        n148_rgb_to_perceptual(rgb, count, first, second, third);
        return;
    }
    rgb_to_ycbcr(rgb, count, first, second, third);
}

static void color_rows(long start, long end, int worker, void *context) {
    (void) worker;
    ColorJob *job = (ColorJob *) context;
    for (long row = start; row < end; row++) {
        long offset = row * job->width;
        rgb_to_coding_planes(job->rgb + offset * 3, job->width,
                             job->y + offset, job->cb + offset,
                             job->cr + offset, job->perceptual_color);
    }
}

#if defined(__x86_64__) || defined(__i386__)
__attribute__((target("avx2")))
static void downsample_420_rows_avx2(const unsigned char *cb0,
                                     const unsigned char *cb1,
                                     const unsigned char *cr0,
                                     const unsigned char *cr1,
                                     int width, unsigned char *out_cb,
                                     unsigned char *out_cr, int out_width) {
    const __m256i ones = _mm256_set1_epi8(1);
    const __m256i two = _mm256_set1_epi16(2);
    int x = 0;
    for (; x + 16 <= out_width && 2 * x + 32 <= width; x += 16) {
        int source = x * 2;
        __m256i cb_top = _mm256_loadu_si256((const __m256i *)(cb0 + source));
        __m256i cb_bottom = _mm256_loadu_si256((const __m256i *)(cb1 + source));
        __m256i cr_top = _mm256_loadu_si256((const __m256i *)(cr0 + source));
        __m256i cr_bottom = _mm256_loadu_si256((const __m256i *)(cr1 + source));
        __m256i cb_sum = _mm256_add_epi16(_mm256_maddubs_epi16(cb_top, ones),
                                          _mm256_maddubs_epi16(cb_bottom, ones));
        __m256i cr_sum = _mm256_add_epi16(_mm256_maddubs_epi16(cr_top, ones),
                                          _mm256_maddubs_epi16(cr_bottom, ones));
        cb_sum = _mm256_srli_epi16(_mm256_add_epi16(cb_sum, two), 2);
        cr_sum = _mm256_srli_epi16(_mm256_add_epi16(cr_sum, two), 2);
        __m128i cb_bytes = _mm_packus_epi16(_mm256_castsi256_si128(cb_sum),
                                            _mm256_extracti128_si256(cb_sum, 1));
        __m128i cr_bytes = _mm_packus_epi16(_mm256_castsi256_si128(cr_sum),
                                            _mm256_extracti128_si256(cr_sum, 1));
        _mm_storeu_si128((__m128i *)(out_cb + x), cb_bytes);
        _mm_storeu_si128((__m128i *)(out_cr + x), cr_bytes);
    }
    for (; x < out_width; x++) {
        int source = x * 2;
        int next = source + 1 < width ? source + 1 : width - 1;
        out_cb[x] = (unsigned char)((cb0[source] + cb0[next] +
                                     cb1[source] + cb1[next] + 2) >> 2);
        out_cr[x] = (unsigned char)((cr0[source] + cr0[next] +
                                     cr1[source] + cr1[next] + 2) >> 2);
    }
}

/* Convert two RGB rows and immediately reduce their chroma to 4:2:0. This
   keeps the exact per-pixel color transform and the existing rounded 2x2
   average while avoiding four full-width temporary chroma rows. */
__attribute__((target("avx2")))
static void rgb_to_ycbcr_420_rows_avx2(
    const unsigned char *rgb0, const unsigned char *rgb1, int width,
    unsigned char *y0, unsigned char *y1,
    unsigned char *out_cb, unsigned char *out_cr, int out_width) {
    const __m128i ones = _mm_set1_epi8(1);
    const __m128i two = _mm_set1_epi16(2);
    int source = 0;
    int output = 0;
    for (; source + 20 <= width; source += 16, output += 8) {
        __m128i y_a, cb_a, cr_a, y_b, cb_b, cr_b;
        __m128i cb_c, cr_c, cb_d, cr_d;
        convert_rgb8_avx2(rgb0 + source * 3, &y_a, &cb_a, &cr_a);
        convert_rgb8_avx2(rgb0 + (source + 8) * 3, &y_b, &cb_b, &cr_b);
        _mm_storeu_si128((__m128i *)(y0 + source),
                         _mm_unpacklo_epi64(y_a, y_b));
        if (rgb1) {
            __m128i y_c, y_d;
            convert_rgb8_avx2(rgb1 + source * 3,
                              &y_c, &cb_c, &cr_c);
            convert_rgb8_avx2(rgb1 + (source + 8) * 3,
                              &y_d, &cb_d, &cr_d);
            _mm_storeu_si128((__m128i *)(y1 + source),
                             _mm_unpacklo_epi64(y_c, y_d));
        } else {
            cb_c = cb_a; cr_c = cr_a;
            cb_d = cb_b; cr_d = cr_b;
        }
        __m128i cb_top = _mm_unpacklo_epi64(cb_a, cb_b);
        __m128i cb_bottom = _mm_unpacklo_epi64(cb_c, cb_d);
        __m128i cr_top = _mm_unpacklo_epi64(cr_a, cr_b);
        __m128i cr_bottom = _mm_unpacklo_epi64(cr_c, cr_d);
        __m128i cb_sum = _mm_add_epi16(
            _mm_maddubs_epi16(cb_top, ones),
            _mm_maddubs_epi16(cb_bottom, ones));
        __m128i cr_sum = _mm_add_epi16(
            _mm_maddubs_epi16(cr_top, ones),
            _mm_maddubs_epi16(cr_bottom, ones));
        cb_sum = _mm_srli_epi16(_mm_add_epi16(cb_sum, two), 2);
        cr_sum = _mm_srli_epi16(_mm_add_epi16(cr_sum, two), 2);
        _mm_storel_epi64((__m128i *)(out_cb + output),
            _mm_packus_epi16(cb_sum, cb_sum));
        _mm_storel_epi64((__m128i *)(out_cr + output),
            _mm_packus_epi16(cr_sum, cr_sum));
    }
    for (; source + 12 <= width; source += 8, output += 4) {
        __m128i top_y, top_cb, top_cr;
        __m128i bottom_y, bottom_cb, bottom_cr;
        convert_rgb8_avx2(rgb0 + source * 3,
                          &top_y, &top_cb, &top_cr);
        _mm_storel_epi64((__m128i *)(y0 + source), top_y);
        if (rgb1) {
            convert_rgb8_avx2(rgb1 + source * 3,
                              &bottom_y, &bottom_cb, &bottom_cr);
            _mm_storel_epi64((__m128i *)(y1 + source), bottom_y);
        } else {
            bottom_cb = top_cb;
            bottom_cr = top_cr;
        }
        __m128i cb_sum = _mm_add_epi16(
            _mm_maddubs_epi16(top_cb, ones),
            _mm_maddubs_epi16(bottom_cb, ones));
        __m128i cr_sum = _mm_add_epi16(
            _mm_maddubs_epi16(top_cr, ones),
            _mm_maddubs_epi16(bottom_cr, ones));
        cb_sum = _mm_srli_epi16(_mm_add_epi16(cb_sum, two), 2);
        cr_sum = _mm_srli_epi16(_mm_add_epi16(cr_sum, two), 2);
        uint32_t cb4 = (uint32_t)_mm_cvtsi128_si32(
            _mm_packus_epi16(cb_sum, cb_sum));
        uint32_t cr4 = (uint32_t)_mm_cvtsi128_si32(
            _mm_packus_epi16(cr_sum, cr_sum));
        memcpy(out_cb + output, &cb4, sizeof(cb4));
        memcpy(out_cr + output, &cr4, sizeof(cr4));
    }

    unsigned char top_cb[12], top_cr[12];
    unsigned char bottom_cb[12], bottom_cr[12];
    int remaining = width - source;
    if (remaining > 0) {
        rgb_to_ycbcr_scalar(rgb0 + source * 3, remaining,
                            y0 + source, top_cb, top_cr);
        if (rgb1) {
            rgb_to_ycbcr_scalar(rgb1 + source * 3, remaining,
                                y1 + source, bottom_cb, bottom_cr);
        } else {
            memcpy(bottom_cb, top_cb, (size_t)remaining);
            memcpy(bottom_cr, top_cr, (size_t)remaining);
        }
    }
    for (; output < out_width; output++) {
        int first = output * 2 - source;
        int next = first + 1;
        if (next >= remaining) next = remaining - 1;
        out_cb[output] = (unsigned char)((top_cb[first] + top_cb[next] +
                                          bottom_cb[first] +
                                          bottom_cb[next] + 2) >> 2);
        out_cr[output] = (unsigned char)((top_cr[first] + top_cr[next] +
                                          bottom_cr[first] +
                                          bottom_cr[next] + 2) >> 2);
    }
}
#endif

typedef struct {
    const Image *image;
    Plane *y, *cb, *cr;
    int use_avx2;
    int perceptual_color;
    int failed;
} Color420Job;

static void color_420_rows(long start, long end, int worker, void *context) {
    (void)worker;
    Color420Job *job = (Color420Job *)context;
    int width = job->image->width;
    int height = job->image->height;

#if defined(__x86_64__) || defined(__i386__)
    if (job->use_avx2 && !job->perceptual_color) {
        for (long cy = start; cy < end; cy++) {
            int row0 = (int)cy * 2;
            int row1 = row0 + 1;
            const unsigned char *rgb0 =
                job->image->pixels + (long)row0 * width * 3;
            const unsigned char *rgb1 = row1 < height ?
                job->image->pixels + (long)row1 * width * 3 : NULL;
            unsigned char *y0 = job->y->data + (long)row0 * width;
            unsigned char *y1 = row1 < height ?
                job->y->data + (long)row1 * width : NULL;
            rgb_to_ycbcr_420_rows_avx2(
                rgb0, rgb1, width, y0, y1,
                job->cb->data + cy * job->cb->width,
                job->cr->data + cy * job->cr->width, job->cb->width);
        }
        return;
    }
#endif

#define COLOR_STACK_WIDTH 2048
    _Alignas(32) unsigned char stack_rows[COLOR_STACK_WIDTH * 4];
    unsigned char *allocated = NULL;
    unsigned char *cb0;
    if (width <= COLOR_STACK_WIDTH) {
        cb0 = stack_rows;
    } else {
        allocated = (unsigned char *)malloc((size_t)width * 4);
        if (!allocated) {
#if defined(__GNUC__) || defined(__clang__)
            __atomic_store_n(&job->failed, 1, __ATOMIC_RELAXED);
#else
            job->failed = 1;
#endif
            return;
        }
        cb0 = allocated;
    }
    unsigned char *cr0 = cb0 + width;
    unsigned char *cb1 = cr0 + width;
    unsigned char *cr1 = cb1 + width;

    for (long cy = start; cy < end; cy++) {
        int row0 = (int)cy * 2;
        int row1 = row0 + 1;
        const unsigned char *rgb0 = job->image->pixels + (long)row0 * width * 3;
        rgb_to_coding_planes(rgb0, width,
                             job->y->data + (long)row0 * width, cb0, cr0,
                             job->perceptual_color);
        if (row1 < height) {
            const unsigned char *rgb1 = job->image->pixels + (long)row1 * width * 3;
            rgb_to_coding_planes(rgb1, width,
                                 job->y->data + (long)row1 * width, cb1, cr1,
                                 job->perceptual_color);
        } else {
            memcpy(cb1, cb0, (size_t)width);
            memcpy(cr1, cr0, (size_t)width);
        }

        unsigned char *out_cb = job->cb->data + cy * job->cb->width;
        unsigned char *out_cr = job->cr->data + cy * job->cr->width;
#if defined(__x86_64__) || defined(__i386__)
        if (job->use_avx2) {
            downsample_420_rows_avx2(cb0, cb1, cr0, cr1, width,
                                     out_cb, out_cr, job->cb->width);
            continue;
        }
#endif
        for (int x = 0; x < job->cb->width; x++) {
            int source = x * 2;
            int next = source + 1 < width ? source + 1 : width - 1;
            out_cb[x] = (unsigned char)((cb0[source] + cb0[next] +
                                         cb1[source] + cb1[next] + 2) >> 2);
            out_cr[x] = (unsigned char)((cr0[source] + cr0[next] +
                                         cr1[source] + cr1[next] + 2) >> 2);
        }
    }
    free(allocated);
#undef COLOR_STACK_WIDTH
}

/* Return one coefficient of the decoder's one-dimensional reconstruction
   kernel. A full-resolution axis is the identity scaled by four; a reduced
   axis uses the decoder's 3:1 interpolation. Keeping both cases on the same
   scale makes the two-dimensional product equal to the decoder's x16 chroma
   representation for both 4:2:2 and 4:2:0. */
static int reconstruction_weight_1d(int source_size, int output_size,
                                    int output_index, int source_index) {
    if (source_size <= 0 || source_index < 0 ||
        source_index >= source_size || output_index < 0 ||
        output_index >= output_size) return 0;
    if (source_size == output_size)
        return source_index == output_index ? 4 : 0;
    if (source_size == 1)
        return source_index == 0 ? 4 : 0;
    if (output_index == 0)
        return source_index == 0 ? 4 : 0;
    if (output_index == 1)
        return source_index == 0 ? 3 : source_index == 1 ? 1 : 0;

    int last = source_size - 1;
    if (output_index >= source_size * 2)
        return source_index == last ? 4 : 0;
    if (output_index == last * 2)
        return source_index == last ? 3 :
            source_index == last - 1 ? 1 : 0;
    if (output_index == last * 2 + 1)
        return source_index == last ? 4 : 0;

    int centre = output_index >> 1;
    if ((output_index & 1) == 0)
        return source_index == centre ? 3 :
            source_index == centre - 1 ? 1 : 0;
    return source_index == centre ? 3 :
        source_index == centre + 1 ? 1 : 0;
}

static void sample_support(int sample, int source_size, int output_size,
                           int *first, int *last) {
    if (source_size == output_size) {
        *first = sample;
        *last = sample;
        return;
    }
    int begin = sample * 2 - 1;
    int end = sample * 2 + 2;
    if (begin < 0) begin = 0;
    if (end >= output_size) end = output_size - 1;
    *first = begin;
    *last = end;
}

typedef struct {
    int first;
    int count;
    int weights[4];
    int squared_sum;
} ChromaReconstructionSupport;

static void prepare_reconstruction_support(
    int sample, int source_size, int output_size,
    ChromaReconstructionSupport *support) {
    int last;
    sample_support(sample, source_size, output_size, &support->first, &last);
    support->count = last - support->first + 1;
    support->squared_sum = 0;
    for (int offset = 0; offset < support->count; offset++) {
        int weight = reconstruction_weight_1d(
            source_size, output_size, support->first + offset, sample);
        support->weights[offset] = weight;
        support->squared_sum += weight * weight;
    }
}

/* Each coordinate solves denominator*x*x - 2*numerator*x on [0,255].
   The nearest integer is the unique minimum except at an exact half-integer.
   The old loop retains old_value on a tie, otherwise the lower tied value. */
static int best_chroma_value(int old_value, long long numerator,
                                 long long denominator) {
    long long rounded = numerator >= 0 ?
        (numerator + denominator / 2) / denominator :
        -((-numerator + denominator / 2) / denominator);
    int candidate = rounded < 0 ? 0 : rounded > 255 ? 255 : (int)rounded;
    if (candidate > 0 && candidate != old_value && !(denominator & 1) &&
        numerator == (long long)candidate * denominator - denominator / 2)
        candidate--;
    return candidate;
}

/* Gather the existing separable 3:1 kernel once per output pixel. The old
   initialization scatters the same four exact products from source supports.
   A full-resolution axis has neighbour == centre, giving weight four. */
static void initialize_chroma(const Plane *stored, int width, int height,
                                   int *reconstruction) {
    for (int y = 0; y < height; y++) {
        int cy = stored->height == height ? y : y/2;
        int ny = stored->height == height ? cy : cy + (y&1 ? 1 : -1);
        if (ny < 0) ny = 0;
        if (ny >= stored->height) ny = stored->height-1;
        const unsigned char *row = stored->data+(long)cy*stored->width;
        const unsigned char *neighbor = stored->data+(long)ny*stored->width;
        for (int x = 0; x < width; x++) {
            int cx = stored->width == width ? x : x/2;
            int nx = stored->width == width ? cx : cx + (x&1 ? 1 : -1);
            if (nx < 0) nx = 0;
            if (nx >= stored->width) nx = stored->width-1;
            reconstruction[(long)y*width+x] =
                9*row[cx] + 3*row[nx] + 3*neighbor[cx] + neighbor[nx];
        }
    }
}

static int best_chroma_reconstruction_value(int old_value,
                                             long long numerator,
                                             long long denominator) {
    return best_chroma_value(old_value,numerator,denominator);
}

#if defined(__x86_64__) || defined(__i386__)
/* A complete 4:2:0 support has the separable weights 1,3,3,1 on each axis.
   Accumulating its 16 exact integer products four pixels at a time avoids
   repeated support traversal in the coordinate-descent sweeps. */
__attribute__((target("avx2")))
static void refine_chroma_sample_simd4(
    const unsigned char *target, int width, Plane *stored,
    int *reconstruction, int sample_x, int sample_y,
    const ChromaReconstructionSupport *x_support,
    const ChromaReconstructionSupport *y_support) {
    long sample_index = (long) sample_y * stored->width + sample_x;
    int old_value = stored->data[sample_index];
    __m128i old_vector = _mm_set1_epi32(old_value);
    __m128i sum = _mm_setzero_si128();
    for (int yi = 0; yi < 4; yi++) {
        int weight_y = yi == 0 || yi == 3 ? 1 : 3;
        __m128i weights = _mm_setr_epi32(
            weight_y, 3 * weight_y, 3 * weight_y, weight_y);
        long index = (long)(y_support->first + yi) * width +
            x_support->first;
        uint32_t packed;
        memcpy(&packed, target + index, sizeof(packed));
        __m128i desired = _mm_slli_epi32(
            _mm_cvtepu8_epi32(_mm_cvtsi32_si128((int) packed)), 4);
        __m128i current = _mm_loadu_si128(
            (const __m128i *)(reconstruction + index));
        __m128i without = _mm_sub_epi32(
            current, _mm_mullo_epi32(weights, old_vector));
        sum = _mm_add_epi32(sum, _mm_mullo_epi32(
            weights, _mm_sub_epi32(desired, without)));
    }
    __m128i high = _mm_srli_si128(sum, 8);
    sum = _mm_add_epi32(sum, high);
    high = _mm_srli_si128(sum, 4);
    sum = _mm_add_epi32(sum, high);
    long long numerator = (int32_t) _mm_cvtsi128_si32(sum);
    /* Four supported samples have weights 1, 3, 3, 1 on each axis.
       Their squared sums are both 20, so the exact divisor is 400.
       Keeping it constant also lets the compiler avoid integer division
       by a value loaded from the support tables for every chroma sample. */
    const long long denominator = 400;
    int best_value = best_chroma_reconstruction_value(
        old_value, numerator, denominator);
    if (best_value == old_value) return;

    int change = best_value - old_value;
    stored->data[sample_index] = (unsigned char) best_value;
    __m128i change_vector = _mm_set1_epi32(change);
    for (int yi = 0; yi < 4; yi++) {
        int weight_y = yi == 0 || yi == 3 ? 1 : 3;
        __m128i weights = _mm_setr_epi32(
            weight_y, 3 * weight_y, 3 * weight_y, weight_y);
        long index = (long)(y_support->first + yi) * width +
            x_support->first;
        __m128i current = _mm_loadu_si128(
            (const __m128i *)(reconstruction + index));
        _mm_storeu_si128((__m128i *)(reconstruction + index),
                        _mm_add_epi32(current,
                            _mm_mullo_epi32(weights, change_vector)));
    }
}
#endif

static void refine_chroma_sample(
    const unsigned char *target, int width,
    Plane *stored, int *reconstruction, int sample_x, int sample_y,
    const ChromaReconstructionSupport *x_support,
    const ChromaReconstructionSupport *y_support, int use_avx2) {
#if defined(__x86_64__) || defined(__i386__)
    if (use_avx2 && x_support->count == 4 && y_support->count == 4) {
        refine_chroma_sample_simd4(target, width, stored, reconstruction,
                                   sample_x, sample_y, x_support, y_support);
        return;
    }
#else
    (void) use_avx2;
#endif
    long sample_index = (long) sample_y * stored->width + sample_x;
    int old_value = stored->data[sample_index];
    long long numerator = 0;
    /* The squared two-dimensional weights factor into the axis sums. */
    long long denominator = (long long) x_support->squared_sum *
                            y_support->squared_sum;

    for (int yi = 0; yi < y_support->count; yi++) {
        int py = y_support->first + yi;
        int weight_y = y_support->weights[yi];
        for (int xi = 0; xi < x_support->count; xi++) {
            int px = x_support->first + xi;
            int weight_x = x_support->weights[xi];
            int weight = weight_x * weight_y;
            if (!weight) continue;
            long index = (long) py * width + px;
            int without_sample = reconstruction[index] - weight * old_value;
            numerator += (long long) weight *
                (((int) target[index] << 4) - without_sample);
        }
    }
    if (!denominator) return;

    int best_value = best_chroma_reconstruction_value(
        old_value, numerator, denominator);
    if (best_value == old_value) return;

    int change = best_value - old_value;
    stored->data[sample_index] = (unsigned char) best_value;
    for (int yi = 0; yi < y_support->count; yi++) {
        int py = y_support->first + yi;
        int weight_y = y_support->weights[yi];
        for (int xi = 0; xi < x_support->count; xi++) {
            int px = x_support->first + xi;
            int weight_x = x_support->weights[xi];
            int weight = weight_x * weight_y;
            if (weight)
                reconstruction[(long) py * width + px] += weight * change;
        }
    }
}

/* Integer coordinate descent solves the decoder-aware least-squares problem.
   The reconstruction buffer carries residual error from one sample to the
   next, so rounding loss is compensated spatially instead of being discarded
   independently in every input sample group. */
static int optimize_chroma_for_reconstruction(
    const unsigned char *target, int width, int height, Plane *stored) {
    if (!target || !stored || !stored->data || width <= 0 || height <= 0 ||
        stored->width <= 0 || stored->height <= 0) return 0;
    size_t pixel_count = (size_t) width * (size_t) height;
    if (pixel_count / (size_t) width != (size_t) height ||
        pixel_count > SIZE_MAX / sizeof(int)) return 0;
    int *reconstruction = (int *) calloc(pixel_count, sizeof(*reconstruction));
    if (!reconstruction) return 0;

    if ((size_t) stored->width > SIZE_MAX / sizeof(ChromaReconstructionSupport) ||
        (size_t) stored->height > SIZE_MAX / sizeof(ChromaReconstructionSupport)) {
        free(reconstruction);
        return 0;
    }
    ChromaReconstructionSupport *x_support = (ChromaReconstructionSupport *)
        malloc((size_t) stored->width * sizeof(*x_support));
    ChromaReconstructionSupport *y_support = (ChromaReconstructionSupport *)
        malloc((size_t) stored->height * sizeof(*y_support));
    if (!x_support || !y_support) {
        free(x_support);
        free(y_support);
        free(reconstruction);
        return 0;
    }
    for (int x = 0; x < stored->width; x++)
        prepare_reconstruction_support(x, stored->width, width,
                                       &x_support[x]);
    for (int y = 0; y < stored->height; y++)
        prepare_reconstruction_support(y, stored->height, height,
                                       &y_support[y]);

    if ((stored->width == width || stored->width == (width+1)/2) &&
        (stored->height == height || stored->height == (height+1)/2)) {
        initialize_chroma(stored,width,height,reconstruction);
    } else {
    for (int sample_y = 0; sample_y < stored->height; sample_y++) {
        const ChromaReconstructionSupport *ys = &y_support[sample_y];
        for (int sample_x = 0; sample_x < stored->width; sample_x++) {
            const ChromaReconstructionSupport *xs = &x_support[sample_x];
            int value = stored->data[
                (long) sample_y * stored->width + sample_x];
            for (int yi = 0; yi < ys->count; yi++) {
                int py = ys->first + yi;
                int weight_y = ys->weights[yi];
                for (int xi = 0; xi < xs->count; xi++) {
                    int px = xs->first + xi;
                    int weight_x = xs->weights[xi];
                    reconstruction[(long) py * width + px] +=
                        weight_x * weight_y * value;
                }
            }
        }
    }

    }

    /* Alternating scan direction reduces raster-order bias. Two complete
       forward/reverse sweeps converge to byte-level stability in practice. */
    int use_avx2 = 0;
#if defined(__x86_64__) || defined(__i386__)
    use_avx2 = n148_cpu_level() >= N148_CPU_AVX2;
#endif
    for (int sweep = 0; sweep < 2; sweep++) {
        for (int sample_y = 0; sample_y < stored->height; sample_y++)
            for (int sample_x = 0; sample_x < stored->width; sample_x++)
                refine_chroma_sample(target, width, stored,
                                     reconstruction, sample_x, sample_y,
                                     &x_support[sample_x], &y_support[sample_y],
                                     use_avx2);
        for (int sample_y = stored->height - 1; sample_y >= 0; sample_y--)
            for (int sample_x = stored->width - 1; sample_x >= 0; sample_x--)
                refine_chroma_sample(target, width, stored,
                                     reconstruction, sample_x, sample_y,
                                     &x_support[sample_x], &y_support[sample_y],
                                     use_avx2);
    }
    free(x_support);
    free(y_support);
    free(reconstruction);
    return 1;
}

int n148_split_channels_reconstruction_aware(Image *image, Plane *y, Plane *cb, Plane *cr,
                           int chroma_mode, int reconstruction_aware) {
    if (!reconstruction_aware || chroma_mode == CHROMA_444)
        return n148_split_channels_ex(image, y, cb, cr, chroma_mode, 0);
    if (!image || !image->pixels || !y || !cb || !cr ||
        image->width <= 0 || image->height <= 0) return 0;

    int width = image->width;
    int height = image->height;
    size_t pixel_count = (size_t) width * (size_t) height;
    if (pixel_count / (size_t) width != (size_t) height) return 0;
    int chroma_width, chroma_height;
    chroma_dimensions(chroma_mode, width, height,
                      &chroma_width, &chroma_height);
    *y = create_plane(width, height);
    *cb = create_plane(chroma_width, chroma_height);
    *cr = create_plane(chroma_width, chroma_height);
    unsigned char *cb_full = (unsigned char *) malloc(pixel_count);
    unsigned char *cr_full = (unsigned char *) malloc(pixel_count);
    if (!y->data || !cb->data || !cr->data || !cb_full || !cr_full) {
        free_plane(y); free_plane(cb); free_plane(cr);
        free(cb_full); free(cr_full);
        return 0;
    }

    ColorJob job;
    job.rgb = image->pixels;
    job.y = y->data;
    job.cb = cb_full;
    job.cr = cr_full;
    job.width = width;
    job.perceptual_color = 0;
    n148_parallel_for(height, color_rows, &job);
    int step_y = chroma_mode == CHROMA_420 ? 2 : 1;
    downsample_plane(cb_full, width, height, cb, 2, step_y);
    downsample_plane(cr_full, width, height, cr, 2, step_y);
    int success = optimize_chroma_for_reconstruction(
        cb_full, width, height, cb) &&
        optimize_chroma_for_reconstruction(cr_full, width, height, cr);
    free(cb_full);
    free(cr_full);
    if (!success) {
        free_plane(y); free_plane(cb); free_plane(cr);
    }
    return success;
}

int n148_split_channels_ex(Image *image, Plane *y, Plane *cb, Plane *cr,
                           int chroma_mode, int perceptual_color) {
    int width = image->width;
    int height = image->height;
    long pixel_count = (long)width * height;

    int chroma_width;
    int chroma_height;
    chroma_dimensions(chroma_mode, width, height,
                      &chroma_width, &chroma_height);
    *y = create_plane(width, height);
    *cb = create_plane(chroma_width, chroma_height);
    *cr = create_plane(chroma_width, chroma_height);
    if (!y->data || !cb->data || !cr->data) {
        free_plane(y);
        free_plane(cb);
        free_plane(cr);
        return 0;
    }
    if (perceptual_color) n148_perceptual_init();

    if (chroma_mode == CHROMA_444) {
        ColorJob job;
        job.rgb = image->pixels; job.y = y->data;
        job.cb = cb->data; job.cr = cr->data; job.width = width;
        job.perceptual_color = perceptual_color;
        n148_parallel_for(height, color_rows, &job);
        return 1;
    }

    if (chroma_mode == CHROMA_420) {
        Color420Job job;
        job.image = image; job.y = y; job.cb = cb; job.cr = cr;
        job.perceptual_color = perceptual_color;
        job.failed = 0;
#if defined(__x86_64__) || defined(__i386__)
        job.use_avx2 = (n148_cpu_level() >= N148_CPU_AVX2);
#else
        job.use_avx2 = 0;
#endif
        n148_parallel_for(chroma_height, color_420_rows, &job);
        if (job.failed) {
            free_plane(y); free_plane(cb); free_plane(cr);
            return 0;
        }
        return 1;
    }

    // 4:2:2 keeps the generic full-resolution intermediate.
    unsigned char *cb_full = (unsigned char *)malloc((size_t)pixel_count);
    unsigned char *cr_full = (unsigned char *)malloc((size_t)pixel_count);
    if (!cb_full || !cr_full) {
        free_plane(y); free_plane(cb); free_plane(cr);
        free(cb_full); free(cr_full);
        return 0;
    }
    ColorJob job;
    job.rgb = image->pixels; job.y = y->data;
    job.cb = cb_full; job.cr = cr_full; job.width = width;
    job.perceptual_color = perceptual_color;
    n148_parallel_for(height, color_rows, &job);

    int step_x = (chroma_mode == CHROMA_444) ? 1 : 2;
    int step_y = (chroma_mode == CHROMA_420) ? 2 : 1;
    downsample_plane(cb_full, width, height, cb, step_x, step_y);
    downsample_plane(cr_full, width, height, cr, step_x, step_y);

    free(cb_full);
    free(cr_full);
    return 1;
}

int split_channels(Image *image, Plane *y, Plane *cb, Plane *cr,
                   int chroma_mode) {
    return n148_split_channels_ex(image, y, cb, cr, chroma_mode, 0);
}

int save_pgm(const char *path, Plane *plane) {
    FILE *file = fopen(path, "wb");
    if (!file) {
        return 0;
    }

    fprintf(file, "P5\n%d %d\n255\n", plane->width, plane->height);
    fwrite(plane->data, 1,
           (size_t)((long)plane->width * plane->height), file);
    fclose(file);
    return 1;
}

/* Continuous RGB SSE projection using the actual quantized, filtered
   chroma reconstruction retained by the encoder. No decoder change. */
#define STRUCTURAL_CHROMA_PROJECTION_STRENGTH 0.625
#include "luma_projection_avx2.inc"
int n148_project_luma_from_chroma(const N148RgbSource *reference,
    const Plane *source,
    const Plane *cb, const Plane *cr, Plane *corrected) {
    if (!reference || !source || !cb || !cr || !corrected ||
        !source->data || source->width <= 0 || source->height <= 0 ||
        !reference->pixels || reference->stride < (size_t)source->width * 3 ||
        reference->width != source->width ||
        reference->height != source->height || !cb->data || !cr->data ||
        cb->width != cr->width || cb->height != cr->height ||
        (cb->width != source->width &&
         cb->width != source->width / 2 + source->width % 2) ||
        (cb->height != source->height &&
         cb->height != source->height / 2 + source->height % 2))
        return 0;
    *corrected = create_plane(source->width,source->height);
    if (!corrected->data) return 0;
    double strength = n148_fidelity_balanced_reconstruction() ? 0.25 :
        STRUCTURAL_CHROMA_PROJECTION_STRENGTH;
    int sx = cb->width != source->width;
    int sy = cb->height != source->height;
    int vector = 0;
#if defined(__x86_64__) || defined(__i386__)
    vector = sx && n148_cpu_level() >= N148_CPU_AVX2;
#endif
    for (int y = 0; y < source->height; y++) {
        int y0 = sy ? y / 2 : y;
        int y1 = sy ? y0 + ((y & 1) ? 1 : -1) : y0;
        if (y1 < 0) y1 = 0;
        if (y1 >= cb->height) y1 = cb->height - 1;
        for (int x = 0; x < source->width; x++) {
#if defined(__x86_64__) || defined(__i386__)
            if (vector && x >= 2 && !(x & 1) &&
                x + 8 < source->width && x / 2 + 7 <= cb->width) {
                size_t top = (size_t)y0 * cb->width + x / 2 - 1;
                size_t other = (size_t)y1 * cb->width + x / 2 - 1;
                size_t index = (size_t)y * source->width + x;
                project_luma8_avx2(reference->pixels + (size_t)y * reference->stride + (size_t)x * 3,
                    source->data + index,cb->data + top,cb->data + other,
                    cr->data + top,cr->data + other,corrected->data + index,strength);
                x += 7;
                continue;
            }
#endif
            int x0 = sx ? x / 2 : x;
            int x1 = sx ? x0 + ((x & 1) ? 1 : -1) : x0;
            if (x1 < 0) x1 = 0;
            if (x1 >= cb->width) x1 = cb->width - 1;
            size_t a = (size_t)y0 * cb->width + x0;
            size_t b = (size_t)y0 * cb->width + x1;
            size_t c = (size_t)y1 * cb->width + x0;
            size_t d = (size_t)y1 * cb->width + x1;
            double blue = (9 * cb->data[a] + 3 * cb->data[b] +
                3 * cb->data[c] + cb->data[d]) / 16.0 - 128.0;
            double red = (9 * cr->data[a] + 3 * cr->data[b] +
                3 * cr->data[c] + cr->data[d]) / 16.0 - 128.0;
            size_t index = (size_t)y * source->width + x;
            const unsigned char *rgb = reference->pixels + (size_t)y * reference->stride + (size_t)x * 3;
            double target = (rgb[0] + rgb[1] + rgb[2] -
                1.427864 * blue - 0.687864 * red) / 3.0;
            target = source->data[index] + strength *
                (target - source->data[index]);
            if (target < 0.0) target = 0.0;
            if (target > 255.0) target = 255.0;
            corrected->data[index] = (unsigned char)(target + 0.5);
        }
    }
    return 1;
}

src/encoder.h

O encoder.h é a interface do encoder da V1, dos artigos 16 e 20. Na V2, ele passou a entregar os coeficientes quantizados em planos, para que o codificador de entropia novo troque o Huffman pelo rANS sem mudar a quantização.

Na V1, o arquivo tinha 22 linhas:

#ifndef ENCODER_H
#define ENCODER_H

#include "huffman.h"
#include "ppm.h"

// Statistics filled in by encode_image() so main.c can report them.
typedef struct {
    long blocks_y;
    long blocks_cb;
    long blocks_cr;
    long table_size;
    long data_size;
} EncodeStats;

// Encodes the three planes into a freshly allocated buffer.
// The caller owns and must free *out_buffer.
int encode_image(Plane *y, Plane *cb, Plane *cr, int quality, int optimize,
                 HuffSpec specs[HUFFMAN_TABLE_COUNT],
                 unsigned char **out_buffer, EncodeStats *stats);

#endif

Na V2, ele ficou com 42 linhas:

#ifndef ENCODER_H
#define ENCODER_H

#include <stdint.h>

#include "huffman.h"
#include "ppm.h"

// Statistics filled in by encode_image() so main.c can report them.
typedef struct {
    long blocks_y;
    long blocks_cb;
    long blocks_cr;
    long table_size;
    long data_size;
} EncodeStats;

/* Internal bridge used by the entropy payload. Values stay in the exact format 1
   zig-zag order so changing the entropy coder cannot change quantization. */
typedef struct {
    short *coefficients;
    unsigned long long *nonzero_masks;
    unsigned char *nonzero_counts;
    long count;
} N148CoeffPlane;

// Encodes the three planes into a freshly allocated buffer.
// The caller owns and must free *out_buffer.
int encode_image(Plane *y, Plane *cb, Plane *cr, int quality, int optimize,
                 HuffSpec specs[HUFFMAN_TABLE_COUNT],
                 unsigned char **out_buffer, EncodeStats *stats);

int n148_quantize_planes(Plane *y, Plane *cb, Plane *cr, int quality,
                         N148CoeffPlane output[3]);

/* Select tables calibrated for the perceptual planes. */
int n148_quantize_planes_ex(Plane *first, Plane *second, Plane *third,
                            int quality, int perceptual_color,
                            N148CoeffPlane output[3]);
void n148_free_coeff_plane(N148CoeffPlane *plane);

#endif

src/encoder.c

O encoder.c continua sendo o encoder do formato 1, e a V2 só acrescentou as funções que quantizam os planos e entregam os coeficientes para os formatos novos.

Na V1, o arquivo tinha 652 linhas:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#if defined(_MSC_VER)
#include <intrin.h>
#endif
#include "encoder.h"
#include "tables.h"
#include "dct.h"
#include "cpu.h"
#include "parallel.h"

// ============================================================
// HUFFMAN TABLES FOR ENCODING
// ============================================================

typedef struct {
    unsigned int code[256];
    unsigned int len[256];
} HuffTable;

static void build_huffman(const HuffSpec *spec, HuffTable *table) {
    for (int i = 0; i < 256; i++) { table->code[i] = 0; table->len[i] = 0; }
    unsigned int code = 0;
    int k = 0;
    for (int length = 1; length <= 16; length++) {
        for (int i = 0; i < spec->bits[length]; i++) {
            unsigned char symbol = spec->values[k++];
            table->code[symbol] = code;
            table->len[symbol]  = length;
            code++;
        }
        code <<= 1;
    }
}

// ============================================================
// BIT WRITER
// ============================================================
//
// Writing one bit at a time is simple but wasteful: a 12 bit code
// costs 12 shifts, 12 masks and 12 branches. Here we keep a 64 bit
// accumulator, drop whole codes into it in a single shift, and only
// touch memory when at least one full byte is ready. That turns the
// inner loop from "per bit" into "per symbol".

typedef struct {
    unsigned char *buffer;
    long capacity;
    long size;
    unsigned long long accumulator;   // bits waiting to be written
    int filled;                       // how many bits the accumulator holds
} BitWriter;

static int bw_init(BitWriter *writer, long capacity) {
    writer->buffer = (unsigned char *) malloc(capacity);
    if (!writer->buffer) return 0;
    writer->capacity = capacity;
    writer->size = 0;
    writer->accumulator = 0;
    writer->filled = 0;
    return 1;
}

static int bw_reserve(BitWriter *writer, long extra) {
    if (writer->size + extra <= writer->capacity) return 1;
    long wanted = writer->capacity * 2;
    while (wanted < writer->size + extra) wanted *= 2;
    unsigned char *grown = (unsigned char *) realloc(writer->buffer, wanted);
    if (!grown) return 0;
    writer->buffer = grown;
    writer->capacity = wanted;
    return 1;
}

// Pushes up to 32 bits at once.
// Emitting the accumulator one byte at a time costs a loop with a
// shift, a store and a test per byte. Once at least four bytes are
// ready they can leave together: take the top 32 bits, put them in
// big endian order and store the whole word.
//
// Callers must have reserved room beforehand (see write_cache), which
// keeps the capacity check out of the inner loop entirely.
static inline void bw_write_bits(BitWriter *writer, unsigned int value, int count) {
    if (count <= 0) return;

    writer->accumulator = (writer->accumulator << count)
                        | (value & ((count >= 32) ? 0xFFFFFFFFu
                                                  : ((1u << count) - 1u)));
    writer->filled += count;

    if (writer->filled >= 32) {
        writer->filled -= 32;
        unsigned int word = (unsigned int)(writer->accumulator >> writer->filled);
#if defined(__GNUC__) || defined(__clang__)
        word = __builtin_bswap32(word);
#else
        word = ((word & 0xFFu) << 24) | ((word & 0xFF00u) << 8) |
               ((word >> 8) & 0xFF00u) | ((word >> 24) & 0xFFu);
#endif
        memcpy(writer->buffer + writer->size, &word, 4);
        writer->size += 4;
    }
}

static void bw_flush(BitWriter *writer) {
    bw_reserve(writer, 8);
    while (writer->filled >= 8) {
        writer->filled -= 8;
        writer->buffer[writer->size++] =
            (unsigned char)(writer->accumulator >> writer->filled);
    }
    if (writer->filled > 0) {                       // pad the last byte
        writer->buffer[writer->size++] =
            (unsigned char)(writer->accumulator << (8 - writer->filled));
        writer->filled = 0;
    }
}

// ============================================================
// CATEGORY / AMPLITUDE
// ============================================================

// How many bits a value needs. The loop version is easy to read but
// runs once per coefficient; counting leading zeros gets the same
// answer in a single instruction on any modern CPU.
static inline int category(int value) {
    unsigned int magnitude = (unsigned int)(value < 0 ? -value : value);
    if (magnitude == 0) return 0;
#if defined(__GNUC__) || defined(__clang__)
    return 32 - __builtin_clz(magnitude);
#else
    int size = 0;
    while (magnitude) { size++; magnitude >>= 1; }
    return size;
#endif
}

static inline unsigned int amplitude(int value, int size) {
    unsigned int mask = (1u << size) - 1u;
    return (value < 0) ? (((unsigned int)(value - 1)) & mask)
                       : (((unsigned int) value) & mask);
}

// ============================================================
// PRE-SCALED QUANTIZATION TABLE
// ============================================================
//
// The fast DCT leaves each coefficient multiplied by a constant.
// Rather than dividing it back out for every block, the constant is
// folded into the table once, and quantizing becomes a multiply.

// The reciprocals are stored in ZIG-ZAG order. That way the
// quantizer can walk its output sequentially and pick up the
// coefficients with a gather, instead of quantizing in natural order
// and then shuffling 64 values around afterwards.
typedef struct { float recip[64]; } FastQuant;

static void build_fast_quant(int quantization[8][8], FastQuant *out) {
    for (int u = 0; u < 8; u++)
        for (int v = 0; v < 8; v++)
            out->recip[u*8+v] =
                (float)(1.0 / (quantization[u][v] * aan_scale_factor(u, v)));
}

// ============================================================
// COEFFICIENT CACHE
// ============================================================
//
// The costly part of a block is the transform, not the bookkeeping.
// Running it once and storing the quantized result lets the symbol
// counting pass and the bit writing pass share the work.

typedef struct {
    short *coefficients;    // 64 quantized values per block, zig-zag order
    unsigned long long *nonzero_masks;
    unsigned char *nonzero_counts;
    long   count;
} CoeffCache;

static inline int trailing_zero_count(unsigned long long value) {
#if defined(_MSC_VER) && defined(_M_X64)
    unsigned long index;
    _BitScanForward64(&index, value);
    return (int) index;
#elif defined(_MSC_VER)
    unsigned long index;
    unsigned long low = (unsigned long) value;
    if (low != 0) {
        _BitScanForward(&index, low);
        return (int) index;
    }
    _BitScanForward(&index, (unsigned long) (value >> 32));
    return (int) index + 32;
#else
    return __builtin_ctzll(value);
#endif
}

static void cache_release(CoeffCache *cache) {
    free(cache->coefficients);
    cache->coefficients = NULL;
    cache->nonzero_masks = NULL;
    cache->nonzero_counts = NULL;
}

#if defined(__x86_64__) || defined(__i386__)
#include <immintrin.h>

// Quantizes straight into zig-zag order: the gather picks the eight
// coefficients that belong at this point in the sequence, and the
// reciprocals are already lined up with them. Packing to 16 bits
// finishes the block without a single scalar pass.
__attribute__((target("avx2")))
static void quantize_avx2(const float coef[64], const float recip[64],
                          const int zigzag[64], short out[64]) {
    // Quantizing in natural order keeps every load contiguous, which
    // matters: a hardware gather looked tempting here but measured
    // more than twice as slow as a plain multiply followed by a
    // sixteen bit reorder. The values are narrowed to short first, so
    // the reordering pass moves half as many bytes.
    short natural[64];
    for (int i = 0; i < 64; i += 16) {
        __m256i low = _mm256_cvtps_epi32(
            _mm256_mul_ps(_mm256_loadu_ps(coef + i), _mm256_loadu_ps(recip + i)));
        __m256i high = _mm256_cvtps_epi32(
            _mm256_mul_ps(_mm256_loadu_ps(coef + i + 8), _mm256_loadu_ps(recip + i + 8)));

        __m256i packed = _mm256_packs_epi32(low, high);
        // packs works within 128 bit lanes, so the halves need one
        // more shuffle to come out in sequence.
        packed = _mm256_permute4x64_epi64(packed, 0xD8);
        _mm256_storeu_si256((__m256i *)(natural + i), packed);
    }

    for (int i = 0; i < 64; i++) out[i] = natural[zigzag[i]];
}

// Loads an 8x8 patch of bytes as floats, one row per instruction.
__attribute__((target("avx2")))
static void load_block_avx2(const unsigned char *src, int stride, float block[64]) {
    for (int r = 0; r < 8; r++, src += stride) {
        __m128i bytes = _mm_loadl_epi64((const __m128i *) src);
        _mm256_storeu_ps(block + r*8,
                         _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(bytes)));
    }
}
#endif

static void quantize_scalar(const float coef[64], const float recip[64],
                            const int zigzag[64], short out[64]) {
    short natural[64];
    for (int i = 0; i < 64; i++) natural[i] = (short) lrintf(coef[i] * recip[i]);
    for (int i = 0; i < 64; i++) out[i] = natural[zigzag[i]];
}

// ============================================================
// NON-ZERO SCAN
// ============================================================
//
// A quantized block is mostly zeros, yet both passes still walked all
// 63 AC slots looking for the few that survived. Building a 64 bit
// mask of the non-zero positions lets the loops jump straight from
// one coefficient to the next: the run length is simply the distance
// between two set bits.

#if defined(__x86_64__) || defined(__i386__)
__attribute__((target("avx2")))
static unsigned long long nonzero_mask_avx2(const short *zz) {
    unsigned long long mask = 0;
    const __m256i zero = _mm256_setzero_si256();
    for (int group = 0; group < 4; group++) {
        __m256i values = _mm256_loadu_si256((const __m256i *)(zz + group * 16));
        __m256i is_zero = _mm256_cmpeq_epi16(values, zero);
        __m128i packed = _mm_packs_epi16(_mm256_castsi256_si128(is_zero),
                                         _mm256_extracti128_si256(is_zero, 1));
        unsigned int bits = (unsigned int) _mm_movemask_epi8(packed);
        mask |= ((unsigned long long)((~bits) & 0xFFFFu)) << (group * 16);
    }
    return mask;
}
#endif

static unsigned long long nonzero_mask_scalar(const short *zz) {
    unsigned long long mask = 0;
    for (int i = 0; i < 64; i++)
        if (zz[i]) mask |= 1ull << i;
    return mask;
}

static inline unsigned long long nonzero_mask(const short *zz, int use_avx2) {
#if defined(__x86_64__) || defined(__i386__)
    if (use_avx2) return nonzero_mask_avx2(zz);
#else
    (void) use_avx2;
#endif
    return nonzero_mask_scalar(zz);
}

#define MAX_WORKERS 32

typedef struct {
    Plane *plane;
    const FastQuant *quant;
    short *coefficients;
    unsigned long long *nonzero_masks;
    unsigned char *nonzero_counts;
    int blocks_x;
    int use_avx2;
    int collect;                     // also gather AC statistics
    long (*ac_freq)[256];            // one row per worker, merged later
} QuantJob;

// Handles one horizontal band of blocks. Bands never overlap, so the
// workers write to disjoint slices of the output buffer.
static void quantize_rows(long start, long end, int worker, void *context) {
    QuantJob *job = (QuantJob *) context;
    Plane *plane = job->plane;

    for (long by = start; by < end; by++) {
        for (int bx = 0; bx < job->blocks_x; bx++) {
            float block[64], coef[64];

            if ((bx + 1) * 8 <= plane->width && (by + 1) * 8 <= plane->height) {
                const unsigned char *src =
                    plane->data + (long)(by * 8) * plane->width + bx * 8;
#if defined(__x86_64__) || defined(__i386__)
                if (job->use_avx2) load_block_avx2(src, plane->width, block);
                else
#endif
                for (int r = 0; r < 8; r++, src += plane->width)
                    for (int c = 0; c < 8; c++)
                        block[r*8+c] = (float) src[c];
            } else {
                for (int r = 0; r < 8; r++)
                    for (int c = 0; c < 8; c++)
                        block[r*8+c] = (float) plane_sample(plane, bx*8 + c,
                                                            (int)(by*8) + r);
            }

#if defined(__x86_64__) || defined(__i386__)
            if (job->use_avx2) dct_block_avx2(block, coef);
            else
#endif
            dct_block_fast(block, coef);

            long block_index = by * job->blocks_x + bx;
            short *out = job->coefficients + block_index * 64;
#if defined(__x86_64__) || defined(__i386__)
            if (job->use_avx2) quantize_avx2(coef, job->quant->recip, ZIGZAG, out);
            else
#endif
            quantize_scalar(coef, job->quant->recip, ZIGZAG, out);

            // The AC statistics do not depend on block order, so they
            // can be gathered right here while the coefficients are
            // still in cache. Counting them later would mean reading
            // the whole coefficient buffer back from memory.
            unsigned long long nonzero = nonzero_mask(out, job->use_avx2);
            job->nonzero_masks[block_index] = nonzero;

            if (job->collect) {
                long *freq = job->ac_freq[worker];
                unsigned long long mask = nonzero & ~1ull;
                unsigned char count = 0;
                int previous = 0;
                while (mask) {
                    int position = trailing_zero_count(mask);
                    int run = position - previous - 1;
                    while (run > 15) { freq[0xF0]++; run -= 16; }
                    freq[(run << 4) | category(out[position])]++;
                    previous = position;
                    count++;
                    mask &= mask - 1;
                }
                if (previous < 63) freq[0x00]++;
                job->nonzero_counts[block_index] = count;
            }
        }
    }
}

static long quantize_plane(Plane *plane, const FastQuant *quant, CoeffCache *cache,
                           int collect, long (*ac_freq)[256]) {
    int blocks_x = (plane->width  + 7) / 8;
    int blocks_y = (plane->height + 7) / 8;
    long total = (long) blocks_x * blocks_y;

    cache->count = total;
    size_t coefficient_bytes = (size_t) total * 64 * sizeof(short);
    size_t mask_bytes = (size_t) total * sizeof(*cache->nonzero_masks);
    size_t count_bytes = collect ? (size_t) total : 0;
    cache->coefficients = (short *) malloc(coefficient_bytes + mask_bytes +
                                           count_bytes);
    if (!cache->coefficients) return 0;
    cache->nonzero_masks = (unsigned long long *)
        ((unsigned char *) cache->coefficients + coefficient_bytes);
    cache->nonzero_counts = collect
        ? (unsigned char *) cache->nonzero_masks + mask_bytes
        : NULL;

    QuantJob job;
    job.plane = plane;
    job.quant = quant;
    job.coefficients = cache->coefficients;
    job.nonzero_masks = cache->nonzero_masks;
    job.nonzero_counts = cache->nonzero_counts;
    job.blocks_x = blocks_x;
    job.collect = collect;
    job.ac_freq = ac_freq;
#if defined(__x86_64__) || defined(__i386__)
    job.use_avx2 = (n148_cpu_level() >= N148_CPU_AVX2);
#else
    job.use_avx2 = 0;
#endif

    n148_parallel_for(blocks_y, quantize_rows, &job);
    return total;
}

// ============================================================
// SYMBOL GENERATION
// ============================================================
//
// Both passes read the cached coefficients through this routine, so
// they can never disagree about which symbols the block produces.



// Only the DC symbols are left for a sequential pass: they depend on
// the running predictor, so their order matters. One read per block.
static void count_dc(const CoeffCache *cache, long dc_freq[256]) {
    int dc_previous = 0;
    for (long b = 0; b < cache->count; b++) {
        int dc = cache->coefficients[b * 64];
        dc_freq[category(dc - dc_previous)]++;
        dc_previous = dc;
    }
}

// Sparse blocks are cheapest when each surviving coefficient is sent straight
// to the bit writer.  Dense blocks have enough short entropy tokens to profit
// from joining several of them into one 32-bit write.  Both paths walk the same
// cached non-zero mask and emit the exact same bits: this is an implementation
// choice, not a bitstream mode.
#ifndef N148_DENSE_AC_THRESHOLD
#define N148_DENSE_AC_THRESHOLD 8
#endif

static inline void write_ac_sparse(BitWriter *writer, const short *zz,
                                   unsigned long long mask,
                                   const HuffTable *ac_table) {
    int previous = 0;
    while (mask) {
        int position = trailing_zero_count(mask);
        int run = position - previous - 1;
        while (run > 15) {
            bw_write_bits(writer, ac_table->code[0xF0], ac_table->len[0xF0]);
            run -= 16;
        }
        int value = zz[position];
        int coefficient_size = category(value);
        int symbol = (run << 4) | coefficient_size;
        bw_write_bits(writer,
                      (ac_table->code[symbol] << coefficient_size)
                          | amplitude(value, coefficient_size),
                      (int) ac_table->len[symbol] + coefficient_size);
        previous = position;
        mask &= mask - 1;
    }
    if (previous < 63)
        bw_write_bits(writer, ac_table->code[0x00], ac_table->len[0x00]);
}

typedef struct {
    unsigned int bits;
    int count;
} AcBitBatch;

static inline void ac_batch_flush(BitWriter *writer, AcBitBatch *batch) {
    if (batch->count > 0) {
        bw_write_bits(writer, batch->bits, batch->count);
        batch->bits = 0;
        batch->count = 0;
    }
}

static inline void ac_batch_put(BitWriter *writer, AcBitBatch *batch,
                                unsigned int value, int count) {
    if (batch->count > 0 && batch->count + count > 32)
        ac_batch_flush(writer, batch);

    if (batch->count == 0) {
        batch->bits = value;
        batch->count = count;
    } else {
        batch->bits = (batch->bits << count) | value;
        batch->count += count;
    }
}

static inline void write_ac_dense(BitWriter *writer, const short *zz,
                                  unsigned long long mask,
                                  const HuffTable *ac_table) {
    AcBitBatch batch = {0, 0};
    int previous = 0;
    while (mask) {
        int position = trailing_zero_count(mask);
        int run = position - previous - 1;
        while (run > 15) {
            ac_batch_put(writer, &batch,
                         ac_table->code[0xF0], ac_table->len[0xF0]);
            run -= 16;
        }
        int value = zz[position];
        int coefficient_size = category(value);
        int symbol = (run << 4) | coefficient_size;
        ac_batch_put(writer, &batch,
                     (ac_table->code[symbol] << coefficient_size)
                         | amplitude(value, coefficient_size),
                     (int) ac_table->len[symbol] + coefficient_size);
        previous = position;
        mask &= mask - 1;
    }
    if (previous < 63)
        ac_batch_put(writer, &batch,
                     ac_table->code[0x00], ac_table->len[0x00]);
    ac_batch_flush(writer, &batch);
}

static long write_cache(BitWriter *writer, const CoeffCache *cache,
                        const HuffTable *dc_table, const HuffTable *ac_table) {
    int dc_previous = 0;

    // Worst case for one block: 64 coefficients, each at most a 16 bit
    // code plus a 16 bit payload, so 256 bytes covers it with room to
    // spare. Reserving once per block lets the writer skip the check.
    const long block_margin = 288;

    for (long b = 0; b < cache->count; b++) {
        if (writer->size + block_margin > writer->capacity) {
            if (!bw_reserve(writer, block_margin)) return b;
        }
        const short *zz = &cache->coefficients[b * 64];

        // --- DC ---
        int difference = zz[0] - dc_previous;
        dc_previous = zz[0];
        int size = category(difference);
        bw_write_bits(writer,
                      (dc_table->code[size] << size) | amplitude(difference, size),
                      (int) dc_table->len[size] + size);

        // --- AC: select the cheapest scan without changing its symbols ---
        unsigned long long mask = cache->nonzero_masks[b] & ~1ull;
        if (cache->nonzero_counts &&
            cache->nonzero_counts[b] >= N148_DENSE_AC_THRESHOLD)
            write_ac_dense(writer, zz, mask, ac_table);
        else
            write_ac_sparse(writer, zz, mask, ac_table);
    }
    return cache->count;
}

// ============================================================
// ENCODE THE WHOLE IMAGE
// ============================================================

int encode_image(Plane *y, Plane *cb, Plane *cr, int quality, int optimize,
                 HuffSpec specs[HUFFMAN_TABLE_COUNT],
                 unsigned char **out_buffer, EncodeStats *stats) {
    init_dct_tables();

    int luma_quant[8][8], chroma_quant[8][8];
    scale_table(Q_LUMA_BASE,   quality, luma_quant);
    scale_table(Q_CHROMA_BASE, quality, chroma_quant);

    FastQuant fast_luma, fast_chroma;
    build_fast_quant(luma_quant,   &fast_luma);
    build_fast_quant(chroma_quant, &fast_chroma);

    CoeffCache cache_y = {0}, cache_cb = {0}, cache_cr = {0};

    long dc_luma_freq[256]   = {0}, ac_luma_freq[256]   = {0};
    long dc_chroma_freq[256] = {0}, ac_chroma_freq[256] = {0};

    // Per worker accumulators, merged once the bands are done.
    static long luma_bins[MAX_WORKERS][256];
    static long chroma_bins[MAX_WORKERS][256];
    int worker_count = n148_thread_count();
    if (worker_count > MAX_WORKERS) worker_count = MAX_WORKERS;
    if (optimize) {
        memset(luma_bins, 0, (size_t)worker_count * sizeof(luma_bins[0]));
        memset(chroma_bins, 0, (size_t)worker_count * sizeof(chroma_bins[0]));
    }

    if (!quantize_plane(y, &fast_luma, &cache_y, optimize, luma_bins)) return 0;
    if (!quantize_plane(cb, &fast_chroma, &cache_cb, optimize, chroma_bins)) {
        cache_release(&cache_y); return 0;
    }
    if (!quantize_plane(cr, &fast_chroma, &cache_cr, optimize, chroma_bins)) {
        cache_release(&cache_y); cache_release(&cache_cb); return 0;
    }

    if (optimize) {
        for (int w = 0; w < worker_count; w++)
            for (int s = 0; s < 256; s++) {
                ac_luma_freq[s]   += luma_bins[w][s];
                ac_chroma_freq[s] += chroma_bins[w][s];
            }

        count_dc(&cache_y,  dc_luma_freq);
        count_dc(&cache_cb, dc_chroma_freq);
        count_dc(&cache_cr, dc_chroma_freq);

        huffman_build_optimized(dc_luma_freq,   &specs[HUFFMAN_DC_LUMA]);
        huffman_build_optimized(ac_luma_freq,   &specs[HUFFMAN_AC_LUMA]);
        huffman_build_optimized(dc_chroma_freq, &specs[HUFFMAN_DC_CHROMA]);
        huffman_build_optimized(ac_chroma_freq, &specs[HUFFMAN_AC_CHROMA]);
    } else {
        huffman_default_specs(specs);
    }

    HuffTable dc_luma, ac_luma, dc_chroma, ac_chroma;
    build_huffman(&specs[HUFFMAN_DC_LUMA],   &dc_luma);
    build_huffman(&specs[HUFFMAN_AC_LUMA],   &ac_luma);
    build_huffman(&specs[HUFFMAN_DC_CHROMA], &dc_chroma);
    build_huffman(&specs[HUFFMAN_AC_CHROMA], &ac_chroma);

    BitWriter writer;
    long guess = (cache_y.count + cache_cb.count + cache_cr.count) * 24 + 4096;
    if (!bw_init(&writer, guess)) {
        cache_release(&cache_y); cache_release(&cache_cb); cache_release(&cache_cr);
        return 0;
    }

    stats->blocks_y  = write_cache(&writer, &cache_y,  &dc_luma,   &ac_luma);
    stats->blocks_cb = write_cache(&writer, &cache_cb, &dc_chroma, &ac_chroma);
    stats->blocks_cr = write_cache(&writer, &cache_cr, &dc_chroma, &ac_chroma);

    bw_flush(&writer);

    cache_release(&cache_y);
    cache_release(&cache_cb);
    cache_release(&cache_cr);

    stats->table_size = optimize ? huffman_tables_size(specs) : 0;
    stats->data_size  = writer.size;
    *out_buffer = writer.buffer;
    return 1;
}

Na V2, ele ficou com 695 linhas:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <limits.h>
#if defined(_MSC_VER)
#include <intrin.h>
#endif
#include "encoder.h"
#include "tables.h"
#include "dct.h"
#include "cpu.h"
#include "parallel.h"

// ============================================================
// HUFFMAN TABLES FOR ENCODING
// ============================================================

typedef struct {
    unsigned int code[256];
    unsigned int len[256];
} HuffTable;

static void build_huffman(const HuffSpec *spec, HuffTable *table) {
    for (int i = 0; i < 256; i++) { table->code[i] = 0; table->len[i] = 0; }
    unsigned int code = 0;
    int k = 0;
    for (int length = 1; length <= 16; length++) {
        for (int i = 0; i < spec->bits[length]; i++) {
            unsigned char symbol = spec->values[k++];
            table->code[symbol] = code;
            table->len[symbol]  = length;
            code++;
        }
        code <<= 1;
    }
}

// ============================================================
// BIT WRITER
// ============================================================
//
// Writing one bit at a time is simple but wasteful: a 12 bit code
// costs 12 shifts, 12 masks and 12 branches. Here we keep a 64 bit
// accumulator, drop whole codes into it in a single shift, and only
// touch memory when at least one full byte is ready. That turns the
// inner loop from "per bit" into "per symbol".

typedef struct {
    unsigned char *buffer;
    long capacity;
    long size;
    unsigned long long accumulator;   // bits waiting to be written
    int filled;                       // how many bits the accumulator holds
} BitWriter;

static int bw_init(BitWriter *writer, long capacity) {
    writer->buffer = (unsigned char *) malloc(capacity);
    if (!writer->buffer) return 0;
    writer->capacity = capacity;
    writer->size = 0;
    writer->accumulator = 0;
    writer->filled = 0;
    return 1;
}

static int bw_reserve(BitWriter *writer, long extra) {
    if (writer->size + extra <= writer->capacity) return 1;
    long wanted = writer->capacity * 2;
    while (wanted < writer->size + extra) wanted *= 2;
    unsigned char *grown = (unsigned char *) realloc(writer->buffer, wanted);
    if (!grown) return 0;
    writer->buffer = grown;
    writer->capacity = wanted;
    return 1;
}

// Pushes up to 32 bits at once.
// Emitting the accumulator one byte at a time costs a loop with a
// shift, a store and a test per byte. Once at least four bytes are
// ready they can leave together: take the top 32 bits, put them in
// big endian order and store the whole word.
//
// Callers must have reserved room beforehand (see write_cache), which
// keeps the capacity check out of the inner loop entirely.
static inline void bw_write_bits(BitWriter *writer, unsigned int value, int count) {
    if (count <= 0) return;

    writer->accumulator = (writer->accumulator << count)
                        | (value & ((count >= 32) ? 0xFFFFFFFFu
                                                  : ((1u << count) - 1u)));
    writer->filled += count;

    if (writer->filled >= 32) {
        writer->filled -= 32;
        unsigned int word = (unsigned int)(writer->accumulator >> writer->filled);
#if defined(__GNUC__) || defined(__clang__)
        word = __builtin_bswap32(word);
#else
        word = ((word & 0xFFu) << 24) | ((word & 0xFF00u) << 8) |
               ((word >> 8) & 0xFF00u) | ((word >> 24) & 0xFFu);
#endif
        memcpy(writer->buffer + writer->size, &word, 4);
        writer->size += 4;
    }
}

static void bw_flush(BitWriter *writer) {
    bw_reserve(writer, 8);
    while (writer->filled >= 8) {
        writer->filled -= 8;
        writer->buffer[writer->size++] =
            (unsigned char)(writer->accumulator >> writer->filled);
    }
    if (writer->filled > 0) {                       // pad the last byte
        writer->buffer[writer->size++] =
            (unsigned char)(writer->accumulator << (8 - writer->filled));
        writer->filled = 0;
    }
}

// ============================================================
// CATEGORY / AMPLITUDE
// ============================================================

// How many bits a value needs. The loop version is easy to read but
// runs once per coefficient; counting leading zeros gets the same
// answer in a single instruction on any modern CPU.
static inline int category(int value) {
    unsigned int magnitude = (unsigned int)(value < 0 ? -value : value);
    if (magnitude == 0) return 0;
#if defined(__GNUC__) || defined(__clang__)
    return 32 - __builtin_clz(magnitude);
#else
    int size = 0;
    while (magnitude) { size++; magnitude >>= 1; }
    return size;
#endif
}

static inline unsigned int amplitude(int value, int size) {
    unsigned int mask = (1u << size) - 1u;
    return (value < 0) ? (((unsigned int)(value - 1)) & mask)
                       : (((unsigned int) value) & mask);
}

// ============================================================
// PRE-SCALED QUANTIZATION TABLE
// ============================================================
//
// The fast DCT leaves each coefficient multiplied by a constant.
// Rather than dividing it back out for every block, the constant is
// folded into the table once, and quantizing becomes a multiply.

// The reciprocals are stored in ZIG-ZAG order. That way the
// quantizer can walk its output sequentially and pick up the
// coefficients with a gather, instead of quantizing in natural order
// and then shuffling 64 values around afterwards.
typedef struct { float recip[64]; } FastQuant;

static void build_fast_quant(int quantization[8][8], FastQuant *out) {
    for (int u = 0; u < 8; u++)
        for (int v = 0; v < 8; v++)
            out->recip[u*8+v] =
                (float)(1.0 / (quantization[u][v] * aan_scale_factor(u, v)));
}

// ============================================================
// COEFFICIENT CACHE
// ============================================================
//
// The costly part of a block is the transform, not the bookkeeping.
// Running it once and storing the quantized result lets the symbol
// counting pass and the bit writing pass share the work.

typedef N148CoeffPlane CoeffCache;

static inline int trailing_zero_count(unsigned long long value) {
#if defined(_MSC_VER) && defined(_M_X64)
    unsigned long index;
    _BitScanForward64(&index, value);
    return (int) index;
#elif defined(_MSC_VER)
    unsigned long index;
    unsigned long low = (unsigned long) value;
    if (low != 0) {
        _BitScanForward(&index, low);
        return (int) index;
    }
    _BitScanForward(&index, (unsigned long) (value >> 32));
    return (int) index + 32;
#else
    return __builtin_ctzll(value);
#endif
}

static void cache_release(CoeffCache *cache) {
    free(cache->coefficients);
    cache->coefficients = NULL;
    cache->nonzero_masks = NULL;
    cache->nonzero_counts = NULL;
}

#if defined(__x86_64__) || defined(__i386__)
#include <immintrin.h>

// Quantizes straight into zig-zag order: the gather picks the eight
// coefficients that belong at this point in the sequence, and the
// reciprocals are already lined up with them. Packing to 16 bits
// finishes the block without a single scalar pass.
__attribute__((target("avx2")))
static void quantize_avx2(const float coef[64], const float recip[64],
                          const int zigzag[64], short out[64]) {
    // Quantizing in natural order keeps every load contiguous, which
    // matters: a hardware gather looked tempting here but measured
    // more than twice as slow as a plain multiply followed by a
    // sixteen bit reorder. The values are narrowed to short first, so
    // the reordering pass moves half as many bytes.
    short natural[64];
    for (int i = 0; i < 64; i += 16) {
        __m256i low = _mm256_cvtps_epi32(
            _mm256_mul_ps(_mm256_loadu_ps(coef + i), _mm256_loadu_ps(recip + i)));
        __m256i high = _mm256_cvtps_epi32(
            _mm256_mul_ps(_mm256_loadu_ps(coef + i + 8), _mm256_loadu_ps(recip + i + 8)));

        __m256i packed = _mm256_packs_epi32(low, high);
        // packs works within 128 bit lanes, so the halves need one
        // more shuffle to come out in sequence.
        packed = _mm256_permute4x64_epi64(packed, 0xD8);
        _mm256_storeu_si256((__m256i *)(natural + i), packed);
    }

    for (int i = 0; i < 64; i++) out[i] = natural[zigzag[i]];
}

// Loads an 8x8 patch of bytes as floats, one row per instruction.
__attribute__((target("avx2")))
static void load_block_avx2(const unsigned char *src, int stride, float block[64]) {
    for (int r = 0; r < 8; r++, src += stride) {
        __m128i bytes = _mm_loadl_epi64((const __m128i *) src);
        _mm256_storeu_ps(block + r*8,
                         _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(bytes)));
    }
}
#endif

static void quantize_scalar(const float coef[64], const float recip[64],
                            const int zigzag[64], short out[64]) {
    short natural[64];
    for (int i = 0; i < 64; i++) natural[i] = (short) lrintf(coef[i] * recip[i]);
    for (int i = 0; i < 64; i++) out[i] = natural[zigzag[i]];
}

// ============================================================
// NON-ZERO SCAN
// ============================================================
//
// A quantized block is mostly zeros, yet both passes still walked all
// 63 AC slots looking for the few that survived. Building a 64 bit
// mask of the non-zero positions lets the loops jump straight from
// one coefficient to the next: the run length is simply the distance
// between two set bits.

#if defined(__x86_64__) || defined(__i386__)
__attribute__((target("avx2")))
static unsigned long long nonzero_mask_avx2(const short *zz) {
    unsigned long long mask = 0;
    const __m256i zero = _mm256_setzero_si256();
    for (int group = 0; group < 4; group++) {
        __m256i values = _mm256_loadu_si256((const __m256i *)(zz + group * 16));
        __m256i is_zero = _mm256_cmpeq_epi16(values, zero);
        __m128i packed = _mm_packs_epi16(_mm256_castsi256_si128(is_zero),
                                         _mm256_extracti128_si256(is_zero, 1));
        unsigned int bits = (unsigned int) _mm_movemask_epi8(packed);
        mask |= ((unsigned long long)((~bits) & 0xFFFFu)) << (group * 16);
    }
    return mask;
}
#endif

static unsigned long long nonzero_mask_scalar(const short *zz) {
    unsigned long long mask = 0;
    for (int i = 0; i < 64; i++)
        if (zz[i]) mask |= 1ull << i;
    return mask;
}

static inline unsigned long long nonzero_mask(const short *zz, int use_avx2) {
#if defined(__x86_64__) || defined(__i386__)
    if (use_avx2) return nonzero_mask_avx2(zz);
#else
    (void) use_avx2;
#endif
    return nonzero_mask_scalar(zz);
}

#define MAX_WORKERS 32

typedef struct {
    Plane *plane;
    const FastQuant *quant;
    short *coefficients;
    unsigned long long *nonzero_masks;
    unsigned char *nonzero_counts;
    int blocks_x;
    int use_avx2;
    int collect;                     // also gather AC statistics
    long (*ac_freq)[256];            // one row per worker, merged later
} QuantJob;

// Handles one horizontal band of blocks. Bands never overlap, so the
// workers write to disjoint slices of the output buffer.
static void quantize_rows(long start, long end, int worker, void *context) {
    QuantJob *job = (QuantJob *) context;
    Plane *plane = job->plane;

    for (long by = start; by < end; by++) {
        for (int bx = 0; bx < job->blocks_x; bx++) {
            float block[64], coef[64];

            if ((bx + 1) * 8 <= plane->width && (by + 1) * 8 <= plane->height) {
                const unsigned char *src =
                    plane->data + (long)(by * 8) * plane->width + bx * 8;
#if defined(__x86_64__) || defined(__i386__)
                if (job->use_avx2) load_block_avx2(src, plane->width, block);
                else
#endif
                for (int r = 0; r < 8; r++, src += plane->width)
                    for (int c = 0; c < 8; c++)
                        block[r*8+c] = (float) src[c];
            } else {
                for (int r = 0; r < 8; r++)
                    for (int c = 0; c < 8; c++)
                        block[r*8+c] = (float) plane_sample(plane, bx*8 + c,
                                                            (int)(by*8) + r);
            }

#if defined(__x86_64__) || defined(__i386__)
            if (job->use_avx2) dct_block_avx2(block, coef);
            else
#endif
            dct_block_fast(block, coef);

            long block_index = by * job->blocks_x + bx;
            short *out = job->coefficients + block_index * 64;
#if defined(__x86_64__) || defined(__i386__)
            if (job->use_avx2) quantize_avx2(coef, job->quant->recip, ZIGZAG, out);
            else
#endif
            quantize_scalar(coef, job->quant->recip, ZIGZAG, out);

            // The AC statistics do not depend on block order, so they
            // can be gathered right here while the coefficients are
            // still in cache. Counting them later would mean reading
            // the whole coefficient buffer back from memory.
            unsigned long long nonzero = nonzero_mask(out, job->use_avx2);
            job->nonzero_masks[block_index] = nonzero;

            if (job->collect) {
                long *freq = job->ac_freq[worker];
                unsigned long long mask = nonzero & ~1ull;
                unsigned char count = 0;
                int previous = 0;
                while (mask) {
                    int position = trailing_zero_count(mask);
                    int run = position - previous - 1;
                    while (run > 15) { freq[0xF0]++; run -= 16; }
                    freq[(run << 4) | category(out[position])]++;
                    previous = position;
                    count++;
                    mask &= mask - 1;
                }
                if (previous < 63) freq[0x00]++;
                job->nonzero_counts[block_index] = count;
            }
        }
    }
}

static long quantize_plane(Plane *plane, const FastQuant *quant, CoeffCache *cache,
                           int collect, long (*ac_freq)[256]) {
    int blocks_x = plane->width / 8 + (plane->width % 8 != 0);
    int blocks_y = plane->height / 8 + (plane->height % 8 != 0);
    if (blocks_x <= 0 || blocks_y <= 0 ||
        (size_t) blocks_x > SIZE_MAX / (size_t) blocks_y) return 0;
    size_t block_count = (size_t) blocks_x * (size_t) blocks_y;
    if (block_count > LONG_MAX ||
        block_count > SIZE_MAX / (64 * sizeof(short)) ||
        block_count > SIZE_MAX / sizeof(*cache->nonzero_masks)) return 0;
    long total = (long) block_count;

    cache->count = total;
    size_t coefficient_bytes = block_count * 64 * sizeof(short);
    size_t mask_bytes = block_count * sizeof(*cache->nonzero_masks);
    size_t count_bytes = collect ? block_count : 0;
    if (coefficient_bytes > SIZE_MAX - mask_bytes ||
        coefficient_bytes + mask_bytes > SIZE_MAX - count_bytes) return 0;
    cache->coefficients = (short *) malloc(coefficient_bytes + mask_bytes +
                                           count_bytes);
    if (!cache->coefficients) return 0;
    cache->nonzero_masks = (unsigned long long *)
        ((unsigned char *) cache->coefficients + coefficient_bytes);
    cache->nonzero_counts = collect
        ? (unsigned char *) cache->nonzero_masks + mask_bytes
        : NULL;

    QuantJob job;
    job.plane = plane;
    job.quant = quant;
    job.coefficients = cache->coefficients;
    job.nonzero_masks = cache->nonzero_masks;
    job.nonzero_counts = cache->nonzero_counts;
    job.blocks_x = blocks_x;
    job.collect = collect;
    job.ac_freq = ac_freq;
#if defined(__x86_64__) || defined(__i386__)
    job.use_avx2 = (n148_cpu_level() >= N148_CPU_AVX2);
#else
    job.use_avx2 = 0;
#endif

    n148_parallel_for(blocks_y, quantize_rows, &job);
    return total;
}

// ============================================================
// SYMBOL GENERATION
// ============================================================
//
// Both passes read the cached coefficients through this routine, so
// they can never disagree about which symbols the block produces.



// Only the DC symbols are left for a sequential pass: they depend on
// the running predictor, so their order matters. One read per block.
static void count_dc(const CoeffCache *cache, long dc_freq[256]) {
    int dc_previous = 0;
    for (long b = 0; b < cache->count; b++) {
        int dc = cache->coefficients[b * 64];
        dc_freq[category(dc - dc_previous)]++;
        dc_previous = dc;
    }
}

// Sparse blocks are cheapest when each surviving coefficient is sent straight
// to the bit writer.  Dense blocks have enough short entropy tokens to profit
// from joining several of them into one 32-bit write.  Both paths walk the same
// cached non-zero mask and emit the exact same bits: this is an implementation
// choice, not a bitstream mode.
#ifndef N148_DENSE_AC_THRESHOLD
#define N148_DENSE_AC_THRESHOLD 8
#endif

static inline void write_ac_sparse(BitWriter *writer, const short *zz,
                                   unsigned long long mask,
                                   const HuffTable *ac_table) {
    int previous = 0;
    while (mask) {
        int position = trailing_zero_count(mask);
        int run = position - previous - 1;
        while (run > 15) {
            bw_write_bits(writer, ac_table->code[0xF0], ac_table->len[0xF0]);
            run -= 16;
        }
        int value = zz[position];
        int coefficient_size = category(value);
        int symbol = (run << 4) | coefficient_size;
        bw_write_bits(writer,
                      (ac_table->code[symbol] << coefficient_size)
                          | amplitude(value, coefficient_size),
                      (int) ac_table->len[symbol] + coefficient_size);
        previous = position;
        mask &= mask - 1;
    }
    if (previous < 63)
        bw_write_bits(writer, ac_table->code[0x00], ac_table->len[0x00]);
}

typedef struct {
    unsigned int bits;
    int count;
} AcBitBatch;

static inline void ac_batch_flush(BitWriter *writer, AcBitBatch *batch) {
    if (batch->count > 0) {
        bw_write_bits(writer, batch->bits, batch->count);
        batch->bits = 0;
        batch->count = 0;
    }
}

static inline void ac_batch_put(BitWriter *writer, AcBitBatch *batch,
                                unsigned int value, int count) {
    if (batch->count > 0 && batch->count + count > 32)
        ac_batch_flush(writer, batch);

    if (batch->count == 0) {
        batch->bits = value;
        batch->count = count;
    } else {
        batch->bits = (batch->bits << count) | value;
        batch->count += count;
    }
}

static inline void write_ac_dense(BitWriter *writer, const short *zz,
                                  unsigned long long mask,
                                  const HuffTable *ac_table) {
    AcBitBatch batch = {0, 0};
    int previous = 0;
    while (mask) {
        int position = trailing_zero_count(mask);
        int run = position - previous - 1;
        while (run > 15) {
            ac_batch_put(writer, &batch,
                         ac_table->code[0xF0], ac_table->len[0xF0]);
            run -= 16;
        }
        int value = zz[position];
        int coefficient_size = category(value);
        int symbol = (run << 4) | coefficient_size;
        ac_batch_put(writer, &batch,
                     (ac_table->code[symbol] << coefficient_size)
                         | amplitude(value, coefficient_size),
                     (int) ac_table->len[symbol] + coefficient_size);
        previous = position;
        mask &= mask - 1;
    }
    if (previous < 63)
        ac_batch_put(writer, &batch,
                     ac_table->code[0x00], ac_table->len[0x00]);
    ac_batch_flush(writer, &batch);
}

static long write_cache(BitWriter *writer, const CoeffCache *cache,
                        const HuffTable *dc_table, const HuffTable *ac_table) {
    int dc_previous = 0;

    // Worst case for one block: 64 coefficients, each at most a 16 bit
    // code plus a 16 bit payload, so 256 bytes covers it with room to
    // spare. Reserving once per block lets the writer skip the check.
    const long block_margin = 288;

    for (long b = 0; b < cache->count; b++) {
        if (writer->size + block_margin > writer->capacity) {
            if (!bw_reserve(writer, block_margin)) return b;
        }
        const short *zz = &cache->coefficients[b * 64];

        // --- DC ---
        int difference = zz[0] - dc_previous;
        dc_previous = zz[0];
        int size = category(difference);
        bw_write_bits(writer,
                      (dc_table->code[size] << size) | amplitude(difference, size),
                      (int) dc_table->len[size] + size);

        // --- AC: select the cheapest scan without changing its symbols ---
        unsigned long long mask = cache->nonzero_masks[b] & ~1ull;
        if (cache->nonzero_counts &&
            cache->nonzero_counts[b] >= N148_DENSE_AC_THRESHOLD)
            write_ac_dense(writer, zz, mask, ac_table);
        else
            write_ac_sparse(writer, zz, mask, ac_table);
    }
    return cache->count;
}

// ============================================================
// ENCODE THE WHOLE IMAGE
// ============================================================

int encode_image(Plane *y, Plane *cb, Plane *cr, int quality, int optimize,
                 HuffSpec specs[HUFFMAN_TABLE_COUNT],
                 unsigned char **out_buffer, EncodeStats *stats) {
    init_dct_tables();

    int luma_quant[8][8], chroma_quant[8][8];
    scale_table(Q_LUMA_BASE,   quality, luma_quant);
    scale_table(Q_CHROMA_BASE, quality, chroma_quant);

    FastQuant fast_luma, fast_chroma;
    build_fast_quant(luma_quant,   &fast_luma);
    build_fast_quant(chroma_quant, &fast_chroma);

    CoeffCache cache_y = {0}, cache_cb = {0}, cache_cr = {0};

    long dc_luma_freq[256]   = {0}, ac_luma_freq[256]   = {0};
    long dc_chroma_freq[256] = {0}, ac_chroma_freq[256] = {0};

    // Per worker accumulators, merged once the bands are done.
    static long luma_bins[MAX_WORKERS][256];
    static long chroma_bins[MAX_WORKERS][256];
    int worker_count = n148_thread_count();
    if (worker_count > MAX_WORKERS) worker_count = MAX_WORKERS;
    if (optimize) {
        memset(luma_bins, 0, (size_t)worker_count * sizeof(luma_bins[0]));
        memset(chroma_bins, 0, (size_t)worker_count * sizeof(chroma_bins[0]));
    }

    if (!quantize_plane(y, &fast_luma, &cache_y, optimize, luma_bins)) return 0;
    if (!quantize_plane(cb, &fast_chroma, &cache_cb, optimize, chroma_bins)) {
        cache_release(&cache_y); return 0;
    }
    if (!quantize_plane(cr, &fast_chroma, &cache_cr, optimize, chroma_bins)) {
        cache_release(&cache_y); cache_release(&cache_cb); return 0;
    }

    if (optimize) {
        for (int w = 0; w < worker_count; w++)
            for (int s = 0; s < 256; s++) {
                ac_luma_freq[s]   += luma_bins[w][s];
                ac_chroma_freq[s] += chroma_bins[w][s];
            }

        count_dc(&cache_y,  dc_luma_freq);
        count_dc(&cache_cb, dc_chroma_freq);
        count_dc(&cache_cr, dc_chroma_freq);

        huffman_build_optimized(dc_luma_freq,   &specs[HUFFMAN_DC_LUMA]);
        huffman_build_optimized(ac_luma_freq,   &specs[HUFFMAN_AC_LUMA]);
        huffman_build_optimized(dc_chroma_freq, &specs[HUFFMAN_DC_CHROMA]);
        huffman_build_optimized(ac_chroma_freq, &specs[HUFFMAN_AC_CHROMA]);
    } else {
        huffman_default_specs(specs);
    }

    HuffTable dc_luma, ac_luma, dc_chroma, ac_chroma;
    build_huffman(&specs[HUFFMAN_DC_LUMA],   &dc_luma);
    build_huffman(&specs[HUFFMAN_AC_LUMA],   &ac_luma);
    build_huffman(&specs[HUFFMAN_DC_CHROMA], &dc_chroma);
    build_huffman(&specs[HUFFMAN_AC_CHROMA], &ac_chroma);

    BitWriter writer;
    long guess = (cache_y.count + cache_cb.count + cache_cr.count) * 24 + 4096;
    if (!bw_init(&writer, guess)) {
        cache_release(&cache_y); cache_release(&cache_cb); cache_release(&cache_cr);
        return 0;
    }

    stats->blocks_y  = write_cache(&writer, &cache_y,  &dc_luma,   &ac_luma);
    stats->blocks_cb = write_cache(&writer, &cache_cb, &dc_chroma, &ac_chroma);
    stats->blocks_cr = write_cache(&writer, &cache_cr, &dc_chroma, &ac_chroma);

    bw_flush(&writer);

    cache_release(&cache_y);
    cache_release(&cache_cb);
    cache_release(&cache_cr);

    stats->table_size = optimize ? huffman_tables_size(specs) : 0;
    stats->data_size  = writer.size;
    *out_buffer = writer.buffer;
    return 1;
}

int n148_quantize_planes_ex(Plane *y, Plane *cb, Plane *cr, int quality,
                            int perceptual_color,
                            N148CoeffPlane output[3]) {
    if (!y || !cb || !cr || !output || !y->data || !cb->data || !cr->data)
        return 0;
    memset(output, 0, 3 * sizeof(*output));
    init_dct_tables();

    int luma_quant[8][8], chroma_quant[8][8];
    const int (*luma_base)[8] = perceptual_color ?
        Q_PERCEPTUAL_INTENSITY_BASE : Q_LUMA_BASE;
    const int (*chroma_base)[8] = perceptual_color ?
        Q_PERCEPTUAL_OPPONENT_BASE : Q_CHROMA_BASE;
    scale_table(luma_base, quality, luma_quant);
    scale_table(chroma_base, quality, chroma_quant);
    FastQuant fast_luma, fast_chroma;
    build_fast_quant(luma_quant, &fast_luma);
    build_fast_quant(chroma_quant, &fast_chroma);

    if (!quantize_plane(y, &fast_luma, &output[0], 0, NULL) ||
        !quantize_plane(cb, &fast_chroma, &output[1], 0, NULL) ||
        !quantize_plane(cr, &fast_chroma, &output[2], 0, NULL)) {
        for (int index = 0; index < 3; index++) cache_release(&output[index]);
        return 0;
    }
    return 1;
}

int n148_quantize_planes(Plane *y, Plane *cb, Plane *cr, int quality,
                         N148CoeffPlane output[3]) {
    return n148_quantize_planes_ex(y, cb, cr, quality, 0, output);
}

void n148_free_coeff_plane(N148CoeffPlane *plane) {
    if (!plane) return;
    cache_release(plane);
    memset(plane, 0, sizeof(*plane));
}

src/decoder.h

O decoder.h é a interface do decoder da V1, dos artigos 17 e 21. Na V2, ele ganhou funções para reconstruir um plano a partir dos coeficientes e para montar o RGB com a transformada de cor opcional.

Na V1, o arquivo tinha 25 linhas:

#ifndef DECODER_H
#define DECODER_H

#include "huffman.h"
#include "ppm.h"

typedef struct {
    long blocks_y;
    long blocks_cb;
    long blocks_cr;
    long bytes_consumed;
} DecodeStats;

// Decodes a compressed buffer into three newly allocated planes.
// The caller owns and must free the returned planes.
int decode_image(unsigned char *buffer, long buffer_size,
                 int width, int height, int quality, int chroma,
                 const HuffSpec specs[HUFFMAN_TABLE_COUNT],
                 Plane *y, Plane *cb, Plane *cr, DecodeStats *stats);

// Rebuilds an RGB image, upsampling chroma to full resolution.
int merge_channels(Plane *y, Plane *cb, Plane *cr,
                   int smooth, Image *output);

#endif

Na V2, ele ficou com 39 linhas:

#ifndef DECODER_H
#define DECODER_H

#include "huffman.h"
#include "ppm.h"

typedef struct {
    long blocks_y;
    long blocks_cb;
    long blocks_cr;
    long bytes_consumed;
} DecodeStats;

// Decodes a compressed buffer into three newly allocated planes.
// The caller owns and must free the returned planes.
int decode_image(unsigned char *buffer, long buffer_size,
                 int width, int height, int quality, int chroma,
                 const HuffSpec specs[HUFFMAN_TABLE_COUNT],
                 Plane *y, Plane *cb, Plane *cr, DecodeStats *stats);

/* Reconstruct one plane from format-1-compatible quantized coefficients. */
int n148_reconstruct_coeff_plane(const short *coefficients, long count,
                                 int width, int height, int quality,
                                 int chroma_plane, Plane *output);

int n148_reconstruct_coeff_plane_ex(const short *coefficients, long count,
                                    int width, int height, int quality,
                                    int chroma_plane, int perceptual_color,
                                    Plane *output);

// Rebuilds an RGB image, upsampling chroma to full resolution.
int merge_channels(Plane *y, Plane *cb, Plane *cr,
                   int smooth, Image *output);

/* Rebuild RGB with the flagged perceptual inverse transform. */
int n148_merge_channels_ex(Plane *first, Plane *second, Plane *third,
                           int smooth, int perceptual_color, Image *output);

#endif

src/decoder.c

O decoder.c continua lendo o formato 1, e a V2 acrescentou a reconstrução de um plano a partir dos coeficientes e a montagem do RGB com a transformada de cor opcional.

Na V1, o arquivo tinha 954 linhas:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "decoder.h"
#include "tables.h"
#include "dct.h"
#include "cpu.h"
#include "parallel.h"

#if defined(__x86_64__) || defined(__i386__)
#include <immintrin.h>
#endif

// ============================================================
// HUFFMAN DECODING TABLES
// ============================================================
//
// Two structures work together here.
//
// The slow path walks the canonical ranges one length at a time,
// exactly as the JPEG specification describes.
//
// The fast path is a flat lookup: we peek at the next LOOKUP_BITS
// bits and, for every code short enough to fit, read the symbol and
// its length straight out of an array. Most symbols in a real image
// are short, so this resolves the large majority of them without a
// single loop iteration.

#ifndef N148_LOOKUP_BITS
#define N148_LOOKUP_BITS 10
#endif
#define LOOKUP_BITS N148_LOOKUP_BITS
#define LOOKUP_SIZE (1 << LOOKUP_BITS)

typedef struct {
    int min_code[17];
    int max_code[17];        // -1 when no code has this length
    int value_index[17];
    const unsigned char *values;

    /* This table has two entry forms.  A resolved entry folds the Huffman
       code, amplitude and sign into one lookup.  A partial entry retains
       code length and symbol when the amplitude extends past the lookup
       window.  Zero alone selects the long-code path. */
    unsigned int action[LOOKUP_SIZE];
} HuffDecoder;

#define ACTION_BITS_SHIFT 16
#define ACTION_RUN_SHIFT  21
#define ACTION_EOB        (1u << 25)
#define ACTION_ZRL        (1u << 26)
#define ACTION_PARTIAL    (1u << 31)

static void build_decoder(const HuffSpec *spec, HuffDecoder *decoder,
                          int is_ac) {
    decoder->values = spec->values;

    int code = 0, k = 0;
    for (int length = 1; length <= 16; length++) {
        if (spec->bits[length] == 0) {
            decoder->max_code[length] = -1;
        } else {
            decoder->value_index[length] = k;
            decoder->min_code[length] = code;
            code += spec->bits[length];
            k    += spec->bits[length];
            decoder->max_code[length] = code - 1;
        }
        code <<= 1;
    }

    memset(decoder->action, 0, sizeof(decoder->action));

    // Fill every lookup slot whose prefix matches a short code.
    code = 0; k = 0;
    for (int length = 1; length <= 16; length++) {
        for (int i = 0; i < spec->bits[length]; i++, k++, code++) {
            if (length <= LOOKUP_BITS) {
                int shift = LOOKUP_BITS - length;
                int start = code << shift;
                int end   = start + (1 << shift);
                for (int slot = start; slot < end; slot++) {
                    decoder->action[slot] = ACTION_PARTIAL |
                        ((unsigned int) length << ACTION_BITS_SHIFT) |
                        spec->values[k];
                }
            }

            int symbol = spec->values[k];
            int amplitude_size = is_ac ? (symbol & 0x0F) : symbol;
            int special = is_ac && (symbol == 0x00 || symbol == 0xF0);
            int total = length + (special ? 0 : amplitude_size);
            if (total > LOOKUP_BITS || (!special && amplitude_size == 0))
                continue;

            int amplitudes = special ? 1 : (1 << amplitude_size);
            int suffix_bits = LOOKUP_BITS - total;
            for (int amplitude = 0; amplitude < amplitudes; amplitude++) {
                int value = amplitude;
                if (!special && amplitude < (1 << (amplitude_size - 1)))
                    value += 1 - (1 << amplitude_size);

                unsigned int action = (unsigned short) value;
                action |= (unsigned int) total << ACTION_BITS_SHIFT;
                if (is_ac) {
                    action |= (unsigned int)(symbol >> 4) << ACTION_RUN_SHIFT;
                    if (symbol == 0x00) action |= ACTION_EOB;
                    if (symbol == 0xF0) action |= ACTION_ZRL;
                }

                int prefix = ((code << (special ? 0 : amplitude_size)) |
                              amplitude) << suffix_bits;
                int repeat = 1 << suffix_bits;
                for (int slot = prefix; slot < prefix + repeat; slot++)
                    decoder->action[slot] = action;
            }
        }
        code <<= 1;
    }
}

// ============================================================
// BIT READER
// ============================================================
//
// The accumulator is kept left aligned: the next bit to be consumed
// always sits at the top. Peeking is then a single shift, and a
// refill can pull eight bytes in one read instead of looping a byte
// at a time.

typedef struct {
    const unsigned char *buffer;
    long size;
    long position;
    unsigned long long accumulator;
    int available;                    // valid bits, counted from the top
    int padding;                      // synthetic zero bits after the payload
} BitReader;

static void br_init(BitReader *reader, const unsigned char *buffer, long size) {
    reader->buffer = buffer;
    reader->size = size;
    reader->position = 0;
    reader->accumulator = 0;
    reader->available = 0;
    reader->padding = 0;
}

static inline unsigned int load_be32(const unsigned char *p) {
    unsigned int v;
    memcpy(&v, p, sizeof(v));
#if defined(__GNUC__) || defined(__clang__)
    return __builtin_bswap32(v);
#else
    return ((v & 0x000000FFu) << 24) | ((v & 0x0000FF00u) << 8) |
           ((v & 0x00FF0000u) >> 8)  | ((v & 0xFF000000u) >> 24);
#endif
}

static inline void br_refill(BitReader *reader) {
    /* A Huffman code plus its amplitude uses at most 31 bits.  Keeping
       32 ready avoids the old overlapping 64-bit load before every symbol. */
    if (reader->available >= 32) return;

    if (reader->position + 4 <= reader->size) {
        unsigned int next = load_be32(reader->buffer + reader->position);
        reader->accumulator |=
            (unsigned long long) next << (32 - reader->available);
        reader->position += 4;
        reader->available += 32;
        return;
    }

    while (reader->available < 32) {
        unsigned long long byte = 0;
        if (reader->position < reader->size) {
            byte = reader->buffer[reader->position++];
        } else {
            reader->padding += 8;
        }
        reader->accumulator |= byte << (56 - reader->available);
        reader->available += 8;
    }
}

static inline unsigned int br_peek(BitReader *reader, int count) {
    return (unsigned int)(reader->accumulator >> (64 - count));
}

static inline void br_skip(BitReader *reader, int count) {
    reader->accumulator <<= count;
    reader->available -= count;
}

static inline unsigned int br_read(BitReader *reader, int count) {
    if (count == 0) return 0;
    unsigned int value = br_peek(reader, count);
    br_skip(reader, count);
    return value;
}

/* Returns length in the high byte and symbol in the low byte, without
   consuming either the code or its amplitude. */
static int br_read_code_slow(BitReader *reader, const HuffDecoder *decoder) {
    unsigned int bits = br_peek(reader, 16);
    for (int length = LOOKUP_BITS + 1; length <= 16; length++) {
        int code = (int)(bits >> (16 - length));
        if (decoder->max_code[length] >= 0 &&
            code >= decoder->min_code[length] &&
            code <= decoder->max_code[length]) {
            int offset = decoder->value_index[length]
                       + (code - decoder->min_code[length]);
            return (length << 8) | decoder->values[offset];
        }
    }
    br_skip(reader, 16);             // preserve progress on malformed input
    return 0;
}

#if defined(__GNUC__) || defined(__clang__)
__attribute__((always_inline))
#endif
static inline int br_read_code_fallback(BitReader *reader,
                                        const HuffDecoder *decoder,
                                        unsigned int entry) {
    if (entry & ACTION_PARTIAL)
        return (int)(((entry >> ACTION_BITS_SHIFT) & 31) << 8) |
                     (int)(entry & 0xFF);
    return br_read_code_slow(reader, decoder);
}

/* Consumes a Huffman code and its amplitude together, then restores sign. */
static inline int br_read_amplitude(BitReader *reader, int code_length,
                                    int size) {
    if (size == 0) {
        br_skip(reader, code_length);
        return 0;
    }
    int total = code_length + size;
    unsigned int mask = (1u << size) - 1u;
    int value = (int)(br_peek(reader, total) & mask);
    br_skip(reader, total);
    int threshold = 1 << (size - 1);
    unsigned int negative = (unsigned int)-(value < threshold);
    return value + (int)(negative & (1u - (1u << size)));
}

// ============================================================
// DEQUANTIZATION TABLE FOR THE FAST INVERSE TRANSFORM
// ============================================================

typedef struct { float multiplier[64]; } FastDequant;

static void build_fast_dequant(int quantization[8][8], FastDequant *out) {
    for (int u = 0; u < 8; u++)
        for (int v = 0; v < 8; v++)
            out->multiplier[u*8+v] =
                (float)(quantization[u][v] * aan_scale_factor(u, v) / 64.0);
}

// ============================================================
// BLOCK RECONSTRUCTION
// ============================================================

#define SPARSE_TWO_BASE   64
#define SPARSE_THREE_BASE (64 + 4096)

/* Returns the flat byte value plus one for a DC-only block, zero for the full
   transform, or a negative sparse descriptor.  Sparse descriptors pack one,
   two or three six-bit natural-order indices into disjoint integer ranges. */
static int decode_block(BitReader *reader, float block[64],
                        const FastDequant *dequant,
                        const HuffDecoder *dc_decoder,
                        const HuffDecoder *ac_decoder,
                        int *dc_previous) {
    // Coefficients are dequantized as they are read. Writing straight
    // into the natural order array removes the separate 64 step
    // reordering pass: only the handful that survived are touched.
    float *coefficients = block;

    br_refill(reader);
    unsigned int action = dc_decoder->action[br_peek(reader, LOOKUP_BITS)];
    int code;
    int difference;
    if (action && !(action & ACTION_PARTIAL)) {
        br_skip(reader, (action >> ACTION_BITS_SHIFT) & 31);
        difference = (short) action;
    } else {
        code = br_read_code_fallback(reader, dc_decoder, action);
        int size = code & 0xFF;
        difference = br_read_amplitude(reader, code >> 8, size);
    }
    int dc = *dc_previous + difference;
    *dc_previous = dc;
    float dc_coefficient = dc * dequant->multiplier[0];

    int nonzero_ac = 0;
    int single_ac_index = 0;
    int second_ac_index = 0;
    int third_ac_index = 0;
    int position = 1;
    while (position < 64) {
        br_refill(reader);
        action = ac_decoder->action[br_peek(reader, LOOKUP_BITS)];
        int value;
        if (action && !(action & ACTION_PARTIAL)) {
            br_skip(reader, (action >> ACTION_BITS_SHIFT) & 31);
            if (action & ACTION_EOB) break;
            if (action & ACTION_ZRL) {
                position += 16;
                continue;
            }
            position += (action >> ACTION_RUN_SHIFT) & 15;
            value = (short) action;
        } else {
            code = br_read_code_fallback(reader, ac_decoder, action);
            if (code == 0) break;
            int code_length = code >> 8;
            int symbol = code & 0xFF;
            if (symbol == 0x00) {                          // EOB
                br_skip(reader, code_length);
                break;
            }
            if (symbol == 0xF0) {                          // ZRL
                br_skip(reader, code_length);
                position += 16;
                continue;
            }

            position += symbol >> 4;
            int coefficient_size = symbol & 0x0F;
            value = br_read_amplitude(reader, code_length, coefficient_size);
        }
        if (position >= 64) {
            break;
        }

        int index = ZIGZAG[position];
        if (nonzero_ac == 0) {
            /* Most low-frequency blocks end at EOB.  Delay clearing the
               transform workspace until an AC coefficient proves it is
               actually needed. */
            memset(coefficients, 0, 64 * sizeof(*coefficients));
            coefficients[0] = dc_coefficient;
            single_ac_index = index;
        } else if (nonzero_ac == 1) {
            second_ac_index = index;
        } else if (nonzero_ac == 2) {
            third_ac_index = index;
        }
        coefficients[index] = value * dequant->multiplier[index];
        nonzero_ac++;
        position++;
    }

    // A block whose AC coefficients all vanished reconstructs to one
    // flat value, so the transform can be skipped entirely. At lower
    // quality settings this covers a large share of the image.
    if (nonzero_ac == 0) {
        float flat = dc_coefficient + 128.0f;   // the 1/8 lives in the table
        if (flat < 0.0f)   flat = 0.0f;
        if (flat > 255.0f) flat = 255.0f;
        return (int)(flat + 0.5f) + 1;
    }

    if (nonzero_ac == 1) return -single_ac_index;
    if (nonzero_ac == 2)
        return -(SPARSE_TWO_BASE +
                 (single_ac_index << 6) + second_ac_index);
    if (nonzero_ac == 3)
        return -(SPARSE_THREE_BASE + (single_ac_index << 12) +
                 (second_ac_index << 6) + third_ac_index);

    return 0;
}

static long decode_plane(BitReader *reader, Plane *plane,
                         const FastDequant *dequant,
                         const HuffDecoder *dc_decoder,
                         const HuffDecoder *ac_decoder) {
    int blocks_x = (plane->width  + 7) / 8;
    int blocks_y = (plane->height + 7) / 8;
    int dc_previous = 0;
    int use_avx2 = 0;
#if defined(__x86_64__) || defined(__i386__)
    use_avx2 = (n148_cpu_level() >= N148_CPU_AVX2);
#endif

    for (int by = 0; by < blocks_y; by++) {
        for (int bx = 0; bx < blocks_x; bx++) {
            float block[64];
            int max_x = bx*8 + 8 <= plane->width  ? 8 : plane->width  - bx*8;
            int max_y = by*8 + 8 <= plane->height ? 8 : plane->height - by*8;
            unsigned char *block_dst =
                plane->data + (long)(by * 8) * plane->width + bx * 8;
            int flat = decode_block(reader, block, dequant, dc_decoder,
                                    ac_decoder, &dc_previous);

            if (flat > 0) {
                unsigned char *dst = block_dst;
                if (max_x == 8) {
                    unsigned long long packed = 0x0101010101010101ull *
                                                (unsigned int)(flat - 1);
                    for (int r = 0; r < max_y; r++, dst += plane->width)
                        memcpy(dst, &packed, sizeof(packed));
                } else {
                    for (int r = 0; r < max_y; r++, dst += plane->width)
                        memset(dst, flat - 1, (size_t) max_x);
                }
                continue;
            }

#if defined(__x86_64__) || defined(__i386__)
            if (flat < 0 && max_x == 8 && max_y == 8 && use_avx2) {
                int sparse = -flat;
                if (sparse >= SPARSE_THREE_BASE) {
                    sparse -= SPARSE_THREE_BASE;
                    int first = sparse >> 12;
                    int second = (sparse >> 6) & 63;
                    int third = sparse & 63;
                    idct_block_store_three_avx2(
                        block[0], block[first], first,
                        block[second], second, block[third], third,
                        block_dst, plane->width);
                } else if (sparse >= SPARSE_TWO_BASE) {
                    sparse -= SPARSE_TWO_BASE;
                    int first = sparse >> 6;
                    int second = sparse & 63;
                    idct_block_store_two_avx2(
                        block[0], block[first], first,
                        block[second], second, block_dst, plane->width);
                } else {
                    idct_block_store_single_avx2(
                        block[0], block[sparse], sparse,
                        block_dst, plane->width);
                }
                continue;
            }
#endif

#if defined(__x86_64__) || defined(__i386__)
            if (max_x == 8 && max_y == 8 && use_avx2) {
                idct_block_store_avx2(block, block_dst, plane->width);
                continue;
            }
            if (use_avx2) idct_block_avx2(block, block);
            else
#endif
            idct_block_fast(block, block);

            for (int r = 0; r < max_y; r++) {
                unsigned char *dst =
                    plane->data + (long)(by*8 + r) * plane->width + bx*8;
                const float *src = &block[r*8];
                for (int c = 0; c < max_x; c++) {
                    float value = src[c];
                    if (value < 0.0f)   value = 0.0f;
                    if (value > 255.0f) value = 255.0f;
                    dst[c] = (unsigned char)(value + 0.5f);
                }
            }
        }
    }
    return (long) blocks_x * blocks_y;
}

int decode_image(unsigned char *buffer, long buffer_size,
                 int width, int height, int quality, int chroma,
                 const HuffSpec specs[HUFFMAN_TABLE_COUNT],
                 Plane *y, Plane *cb, Plane *cr, DecodeStats *stats) {
    init_dct_tables();

    HuffDecoder dc_luma, ac_luma, dc_chroma, ac_chroma;
    build_decoder(&specs[HUFFMAN_DC_LUMA],   &dc_luma,   0);
    build_decoder(&specs[HUFFMAN_AC_LUMA],   &ac_luma,   1);
    build_decoder(&specs[HUFFMAN_DC_CHROMA], &dc_chroma, 0);
    build_decoder(&specs[HUFFMAN_AC_CHROMA], &ac_chroma, 1);

    int luma_quant[8][8], chroma_quant[8][8];
    scale_table(Q_LUMA_BASE,   quality, luma_quant);
    scale_table(Q_CHROMA_BASE, quality, chroma_quant);

    FastDequant dequant_luma, dequant_chroma;
    build_fast_dequant(luma_quant,   &dequant_luma);
    build_fast_dequant(chroma_quant, &dequant_chroma);

    int chroma_width, chroma_height;
    chroma_dimensions(chroma, width, height, &chroma_width, &chroma_height);

    *y  = create_plane(width, height);
    *cb = create_plane(chroma_width, chroma_height);
    *cr = create_plane(chroma_width, chroma_height);
    if (!y->data || !cb->data || !cr->data) return 0;

    BitReader reader;
    br_init(&reader, buffer, buffer_size);

    stats->blocks_y  = decode_plane(&reader, y,  &dequant_luma,   &dc_luma,   &ac_luma);
    stats->blocks_cb = decode_plane(&reader, cb, &dequant_chroma, &dc_chroma, &ac_chroma);
    stats->blocks_cr = decode_plane(&reader, cr, &dequant_chroma, &dc_chroma, &ac_chroma);

    long consumed_bits = reader.position * 8L -
                         (reader.available - reader.padding);
    stats->bytes_consumed = (consumed_bits + 7) >> 3;
    return 1;
}

// ============================================================
// YCbCr -> RGB
// ============================================================

static unsigned char clamp_byte(float value) {
    if (value < 0.0f)   return 0;
    if (value > 255.0f) return 255;
    return (unsigned char)(value + 0.5f);
}

// ============================================================
// CHROMA UPSAMPLING
// ============================================================
//
// For the subsampled modes the bilinear weights are not arbitrary:
// mapping pixel centres between a full resolution grid and a half
// resolution one always lands on the same 3:1 split. Knowing that in
// advance turns the interpolation into integer arithmetic with fixed
// weights, far cheaper than the general bilinear formula.
//
//   horizontal only:  (3*near + far) * 4        -> scaled by 16
//   vertical only:    (3*near + far) * 4        -> scaled by 16
//   both:             9*a + 3*b + 3*c + d       -> scaled by 16
//
// The rows stay at that 16x scale and reach the colour stage
// unrounded: collapsing them to a byte first would discard the
// fractional part the conversion still needs.

#define CHROMA_SHIFT 4                 /* rows carry value * 16 */

#if defined(__x86_64__) || defined(__i386__)
// Vertical blend of two chroma rows, sixteen samples per pass.
__attribute__((target("avx2")))
static void blend_rows_avx2(const unsigned char *near_row,
                            const unsigned char *far_row,
                            int count, unsigned short *out) {
    const __m256i three = _mm256_set1_epi16(3);
    int x = 0;
    for (; x + 16 <= count; x += 16) {
        __m256i n = _mm256_cvtepu8_epi16(_mm_loadu_si128((const __m128i *)(near_row + x)));
        __m256i f = _mm256_cvtepu8_epi16(_mm_loadu_si128((const __m128i *)(far_row  + x)));
        _mm256_storeu_si256((__m256i *)(out + x),
                            _mm256_add_epi16(_mm256_mullo_epi16(n, three), f));
    }
    for (; x < count; x++)
        out[x] = (unsigned short)(3 * near_row[x] + far_row[x]);
}

// Horizontal stretch: every source sample produces the two outputs it
// dominates, so both are computed as vectors and interleaved back.
__attribute__((target("avx2")))
static void stretch_avx2(const unsigned short *src, int first, int last,
                         unsigned short *dst) {
    const __m256i three = _mm256_set1_epi16(3);
    int k = first;
    for (; k + 16 <= last; k += 16) {
        __m256i cur  = _mm256_loadu_si256((const __m256i *)(src + k));
        __m256i prev = _mm256_loadu_si256((const __m256i *)(src + k - 1));
        __m256i next = _mm256_loadu_si256((const __m256i *)(src + k + 1));

        __m256i scaled = _mm256_mullo_epi16(cur, three);
        __m256i even = _mm256_add_epi16(scaled, prev);
        __m256i odd  = _mm256_add_epi16(scaled, next);

        __m256i lo = _mm256_unpacklo_epi16(even, odd);
        __m256i hi = _mm256_unpackhi_epi16(even, odd);
        _mm256_storeu_si256((__m256i *)(dst + 2*k),
                            _mm256_permute2x128_si256(lo, hi, 0x20));
        _mm256_storeu_si256((__m256i *)(dst + 2*k + 16),
                            _mm256_permute2x128_si256(lo, hi, 0x31));
    }
    for (; k < last; k++) {
        int centre = src[k] * 3;
        dst[2*k]     = (unsigned short)(centre + src[k-1]);
        dst[2*k + 1] = (unsigned short)(centre + src[k+1]);
    }
}
#endif

static void expand_h(const unsigned char *src, int src_width,
                     unsigned short *dst, int dst_width) {
    if (src_width == 1) {
        unsigned short v = (unsigned short)(src[0] << CHROMA_SHIFT);
        for (int x = 0; x < dst_width; x++) dst[x] = v;
        return;
    }

    dst[0] = (unsigned short)(src[0] * 16);
    if (dst_width > 1) dst[1] = (unsigned short)(src[0] * 12 + src[1] * 4);

    for (int k = 1; k < src_width - 1; k++) {
        int centre = src[k] * 12;
        dst[2*k]     = (unsigned short)(centre + src[k-1] * 4);
        dst[2*k + 1] = (unsigned short)(centre + src[k+1] * 4);
    }

    int last = src_width - 1;
    int centre = src[last] * 12;
    if (2*last     < dst_width) dst[2*last]     = (unsigned short)(centre + src[last-1] * 4);
    if (2*last + 1 < dst_width) dst[2*last + 1] = (unsigned short)(centre + src[last] * 4);
    for (int x = 2*src_width; x < dst_width; x++)
        dst[x] = (unsigned short)(src[src_width-1] << CHROMA_SHIFT);
}

static void expand_hv(const unsigned char *near_row, const unsigned char *far_row,
                      int src_width, unsigned short *scratch,
                      unsigned short *dst, int dst_width, int use_avx2) {
    int blended = 0;
#if defined(__x86_64__) || defined(__i386__)
    if (use_avx2) {
        blend_rows_avx2(near_row, far_row, src_width, scratch);
        blended = 1;
    }
#else
    (void) use_avx2;
#endif
    if (!blended) {
        for (int x = 0; x < src_width; x++)
            scratch[x] = (unsigned short)(3 * near_row[x] + far_row[x]);
    }

    if (src_width == 1) {
        unsigned short v = (unsigned short)(scratch[0] * 4);
        for (int x = 0; x < dst_width; x++) dst[x] = v;
        return;
    }

    dst[0] = (unsigned short)(scratch[0] * 4);
    if (dst_width > 1) dst[1] = (unsigned short)(scratch[0] * 3 + scratch[1]);

    int stretched = 0;
#if defined(__x86_64__) || defined(__i386__)
    if (use_avx2) {
        stretch_avx2(scratch, 1, src_width - 1, dst);
        stretched = 1;
    }
#endif
    if (!stretched) {
        for (int k = 1; k < src_width - 1; k++) {
            int centre = scratch[k] * 3;
            dst[2*k]     = (unsigned short)(centre + scratch[k-1]);
            dst[2*k + 1] = (unsigned short)(centre + scratch[k+1]);
        }
    }

    int last = src_width - 1;
    int centre = scratch[last] * 3;
    if (2*last     < dst_width) dst[2*last]     = (unsigned short)(centre + scratch[last-1]);
    if (2*last + 1 < dst_width) dst[2*last + 1] = (unsigned short)(centre + scratch[last]);
    for (int x = 2*src_width; x < dst_width; x++)
        dst[x] = (unsigned short)(scratch[src_width-1] * 4);
}

// Produces one chroma row for output line py, scaled by 16.
static void expand_chroma_row(Plane *plane, int py, int dst_width,
                              int stretch_x, int stretch_y,
                              unsigned short *scratch, unsigned short *dst,
                              int use_avx2) {
    if (stretch_y) {
        int near = py >> 1;
        int far  = (py & 1) ? near + 1 : near - 1;
        if (far < 0) far = 0;
        if (far >= plane->height) far = plane->height - 1;
        if (near >= plane->height) near = plane->height - 1;

        const unsigned char *near_row = plane->data + (long) near * plane->width;
        const unsigned char *far_row  = plane->data + (long) far  * plane->width;

        if (stretch_x) {
            expand_hv(near_row, far_row, plane->width, scratch, dst, dst_width, use_avx2);
        } else {
            for (int x = 0; x < dst_width; x++) {
                int sx = x < plane->width ? x : plane->width - 1;
                dst[x] = (unsigned short)((3 * near_row[sx] + far_row[sx]) * 4);
            }
        }
        return;
    }

    int sy = py < plane->height ? py : plane->height - 1;
    const unsigned char *row = plane->data + (long) sy * plane->width;

    if (stretch_x) {
        expand_h(row, plane->width, dst, dst_width);
    } else {
        for (int x = 0; x < dst_width; x++) {
            int sx = x < plane->width ? x : plane->width - 1;
            dst[x] = (unsigned short)(row[sx] << CHROMA_SHIFT);
        }
    }
}

// ============================================================
// COLOUR CONVERSION
// ============================================================

#if defined(__x86_64__) || defined(__i386__)
// Interleaves eight pixels worth of separate R, G and B bytes into
// the 24 packed bytes the output image expects.
__attribute__((target("avx2")))
static inline void store_rgb8(unsigned char *out, __m128i r, __m128i g, __m128i b) {
    __m128i rg = _mm_unpacklo_epi8(r, g);
    const __m128i mrg0 = _mm_setr_epi8(
         0, 1,-1, 2, 3,-1, 4, 5,-1, 6, 7,-1, 8, 9,-1,10);
    const __m128i mb0 = _mm_setr_epi8(
        -1,-1, 0,-1,-1, 1,-1,-1, 2,-1,-1, 3,-1,-1, 4,-1);
    _mm_storeu_si128((__m128i *) out,
        _mm_or_si128(_mm_shuffle_epi8(rg, mrg0), _mm_shuffle_epi8(b, mb0)));

    const __m128i mrg1 = _mm_setr_epi8(
        11,-1,12,13,-1,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1);
    const __m128i mb1 = _mm_setr_epi8(
        -1, 5,-1,-1, 6,-1,-1, 7,-1,-1,-1,-1,-1,-1,-1,-1);
    _mm_storel_epi64((__m128i *)(out + 16),
        _mm_or_si128(_mm_shuffle_epi8(rg, mrg1), _mm_shuffle_epi8(b, mb1)));
}

__attribute__((target("avx2"), always_inline))
static inline void finish_ycbcr8_avx2(__m256 yf, __m256 cbf, __m256 crf,
                                      __m256 rf, __m256 bf,
                                      unsigned char *out) {
    const __m256 k_g_cb = _mm256_set1_ps(-0.344136f);
    const __m256 k_g_cr = _mm256_set1_ps(-0.714136f);
    const __m256 round  = _mm256_set1_ps(0.5f);
    rf = _mm256_add_ps(rf, round);
    bf = _mm256_add_ps(bf, round);
    __m256 gf = _mm256_add_ps(_mm256_add_ps(yf,
                   _mm256_add_ps(_mm256_mul_ps(cbf, k_g_cb),
                                 _mm256_mul_ps(crf, k_g_cr))), round);

    __m256i r = _mm256_cvttps_epi32(rf);
    __m256i g = _mm256_cvttps_epi32(gf);
    __m256i b = _mm256_cvttps_epi32(bf);
    __m128i r16 = _mm_packs_epi32(_mm256_castsi256_si128(r),
                                  _mm256_extracti128_si256(r, 1));
    __m128i g16 = _mm_packs_epi32(_mm256_castsi256_si128(g),
                                  _mm256_extracti128_si256(g, 1));
    __m128i b16 = _mm_packs_epi32(_mm256_castsi256_si128(b),
                                  _mm256_extracti128_si256(b, 1));
    store_rgb8(out, _mm_packus_epi16(r16, r16),
                    _mm_packus_epi16(g16, g16),
                    _mm_packus_epi16(b16, b16));
}

__attribute__((target("avx2"), always_inline))
static inline void convert_ycbcr8_avx2(const unsigned char *luma,
                                        __m128i blue, __m128i red,
                                        unsigned char *out) {
    const __m256 inv    = _mm256_set1_ps(1.0f / (1 << CHROMA_SHIFT));
    const __m256 half   = _mm256_set1_ps(128.0f);
    const __m256 k_r_cr = _mm256_set1_ps(1.402f);
    const __m256 k_b_cb = _mm256_set1_ps(1.772f);

    __m128i y8 = _mm_loadl_epi64((const __m128i *) luma);
    __m256 yf  = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(y8));
    __m256 cbf = _mm256_sub_ps(
        _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepu16_epi32(blue)), inv), half);
    __m256 crf = _mm256_sub_ps(
        _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepu16_epi32(red)), inv), half);

    __m256 rf = _mm256_add_ps(yf, _mm256_mul_ps(crf, k_r_cr));
    __m256 bf = _mm256_add_ps(yf, _mm256_mul_ps(cbf, k_b_cb));
    finish_ycbcr8_avx2(yf, cbf, crf, rf, bf, out);
}

__attribute__((target("avx2,fma"), always_inline))
static inline void convert_ycbcr8_fma(const unsigned char *luma,
                                      __m128i blue, __m128i red,
                                      unsigned char *out) {
    const __m256 inv    = _mm256_set1_ps(1.0f / (1 << CHROMA_SHIFT));
    const __m256 half   = _mm256_set1_ps(128.0f);
    const __m256 k_r_cr = _mm256_set1_ps(1.402f);
    const __m256 k_b_cb = _mm256_set1_ps(1.772f);

    __m128i y8 = _mm_loadl_epi64((const __m128i *) luma);
    __m256 yf  = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(y8));
    __m256 cbf = _mm256_sub_ps(
        _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepu16_epi32(blue)), inv), half);
    __m256 crf = _mm256_sub_ps(
        _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepu16_epi32(red)), inv), half);

    __m256 rf = _mm256_fmadd_ps(crf, k_r_cr, yf);
    __m256 bf = _mm256_fmadd_ps(cbf, k_b_cb, yf);
    finish_ycbcr8_avx2(yf, cbf, crf, rf, bf, out);
}

// Eight pixels per iteration. The chroma rows arrive scaled by 16 so
// no precision is lost on the way in.
__attribute__((target("avx2")))
static void ycbcr_row_avx2(const unsigned char *luma,
                           const unsigned short *blue, const unsigned short *red,
                           unsigned char *out, int count) {
    int i = 0;
    // Each interleaved store writes exactly the 24 bytes for this group.
    for (; i + 8 <= count; i += 8) {
        __m128i cb16 = _mm_loadu_si128((const __m128i *)(blue + i));
        __m128i cr16 = _mm_loadu_si128((const __m128i *)(red  + i));
        convert_ycbcr8_avx2(luma + i, cb16, cr16, out + i * 3);
    }

    const float inv_s = 1.0f / (1 << CHROMA_SHIFT);
    for (; i < count; i++) {
        float yf  = luma[i];
        float cbf = blue[i] * inv_s - 128.0f;
        float crf = red[i]  * inv_s - 128.0f;
        out[i*3+0] = clamp_byte(yf + 1.402f * crf);
        float green = (-0.344136f * cbf) + (-0.714136f * crf);
        out[i*3+1] = clamp_byte(yf + green);
        out[i*3+2] = clamp_byte(yf + 1.772f * cbf);
    }
}

__attribute__((target("avx2,fma")))
static void ycbcr_row_fma(const unsigned char *luma,
                          const unsigned short *blue,
                          const unsigned short *red,
                          unsigned char *out, int count) {
    int i = 0;
    for (; i + 8 <= count; i += 8) {
        __m128i cb16 = _mm_loadu_si128((const __m128i *)(blue + i));
        __m128i cr16 = _mm_loadu_si128((const __m128i *)(red  + i));
        convert_ycbcr8_fma(luma + i, cb16, cr16, out + i * 3);
    }

    /* Keep the rare tail on the non-FMA implementation: fusing the green
       channel changes a handful of exact half-way rounding cases. */
    if (i < count)
        ycbcr_row_avx2(luma + i, blue + i, red + i,
                       out + i * 3, count - i);
}

#endif

// ============================================================
// RECONSTRUCTION
// ============================================================

typedef struct {
    Plane *y, *cb, *cr;
    Image *output;
    int smooth, stretch_x, stretch_y, use_avx2, use_fma;
} MergeJob;

// Reconstructs a band of output rows. Every worker keeps its own
// scratch rows so nothing is shared between them.
static void merge_rows(long start, long end, int worker, void *context) {
    (void) worker;
    MergeJob *job = (MergeJob *) context;
    Plane *y = job->y, *cb = job->cb, *cr = job->cr;
    int width = y->width;

#define MERGE_STACK_WIDTH 2048
    _Alignas(32) unsigned short stack_rows[(MERGE_STACK_WIDTH + 32) * 3];
    unsigned short *allocated = NULL;
    unsigned short *row_cb;
    if (width <= MERGE_STACK_WIDTH && cb->width <= MERGE_STACK_WIDTH) {
        row_cb = stack_rows;
    } else {
        size_t samples = (size_t)(width + 32) * 2 + (size_t)cb->width + 32;
        allocated = (unsigned short *) malloc(samples * sizeof(unsigned short));
        if (!allocated) return;
        row_cb = allocated;
    }
    unsigned short *row_cr = row_cb + width + 32;
    unsigned short *scratch = row_cr + width + 32;

    const float inv_scale = 1.0f / (1 << CHROMA_SHIFT);

    for (long py = start; py < end; py++) {
        unsigned char *out = job->output->pixels + py * width * 3;
        const unsigned char *luma = y->data + py * width;

        if (job->smooth) {
            expand_chroma_row(cb, (int) py, width, job->stretch_x, job->stretch_y,
                              scratch, row_cb, job->use_avx2);
            expand_chroma_row(cr, (int) py, width, job->stretch_x, job->stretch_y,
                              scratch, row_cr, job->use_avx2);
        } else {
            int cy = job->stretch_y ? (int)(py >> 1) : (int) py;
            if (cy >= cb->height) cy = cb->height - 1;
            const unsigned char *src_cb = cb->data + (long) cy * cb->width;
            const unsigned char *src_cr = cr->data + (long) cy * cr->width;
            for (int px = 0; px < width; px++) {
                int cx = job->stretch_x ? (px >> 1) : px;
                if (cx >= cb->width) cx = cb->width - 1;
                row_cb[px] = (unsigned short)(src_cb[cx] << CHROMA_SHIFT);
                row_cr[px] = (unsigned short)(src_cr[cx] << CHROMA_SHIFT);
            }
        }

#if defined(__x86_64__) || defined(__i386__)
        if (job->use_fma) { ycbcr_row_fma(luma, row_cb, row_cr, out, width); continue; }
        if (job->use_avx2) { ycbcr_row_avx2(luma, row_cb, row_cr, out, width); continue; }
#endif
        for (int px = 0; px < width; px++) {
            float value = luma[px];
            float blue_difference = row_cb[px] * inv_scale - 128.0f;
            float red_difference  = row_cr[px] * inv_scale - 128.0f;
            out[px*3+0] = clamp_byte(value + 1.402f * red_difference);
            float green = (-0.344136f * blue_difference) +
                          (-0.714136f * red_difference);
            out[px*3+1] = clamp_byte(value + green);
            out[px*3+2] = clamp_byte(value + 1.772f * blue_difference);
        }
    }

    free(allocated);
#undef MERGE_STACK_WIDTH
}

int merge_channels(Plane *y, Plane *cb, Plane *cr, int smooth, Image *output) {
    int width = y->width, height = y->height;

    if (width <= 0 || height <= 0 || !y->data || !cb->data || !cr->data ||
        cb->width != cr->width || cb->height != cr->height) {
        return 0;
    }

    output->width  = width;
    output->height = height;
    output->pixels = (unsigned char *) malloc((size_t)((long) width * height * 3));
    if (!output->pixels) return 0;

    MergeJob job;
    job.y = y; job.cb = cb; job.cr = cr; job.output = output;
    job.smooth = smooth;
    job.stretch_x = (cb->width  < width);
    job.stretch_y = (cb->height < height);
#if defined(__x86_64__) || defined(__i386__)
    int cpu_level = n148_cpu_level();
    job.use_avx2 = (cpu_level >= N148_CPU_AVX2);
    job.use_fma = (cpu_level >= N148_CPU_AVX2_FMA);
#else
    job.use_avx2 = 0;
    job.use_fma = 0;
#endif

    /* On small images the colour merge is only a few tenths of a
       millisecond; dispatching it to a pool costs more than the work saved,
       especially on hybrid CPUs.  Larger frames still scale across cores. */
    if ((long) width * height < 512L * 1024L)
        merge_rows(0, height, 0, &job);
    else
        n148_parallel_for(height, merge_rows, &job);
    return 1;
}

Na V2, ele ficou com 1.059 linhas:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <limits.h>
#include <stdint.h>
#include "decoder.h"
#include "tables.h"
#include "dct.h"
#include "cpu.h"
#include "parallel.h"
#include "perceptual.h"

#if defined(__x86_64__) || defined(__i386__)
#include <immintrin.h>
#endif

// ============================================================
// HUFFMAN DECODING TABLES
// ============================================================
//
// Two structures work together here.
//
// The slow path walks the canonical ranges one length at a time,
// exactly as the JPEG specification describes.
//
// The fast path is a flat lookup: we peek at the next LOOKUP_BITS
// bits and, for every code short enough to fit, read the symbol and
// its length straight out of an array. Most symbols in a real image
// are short, so this resolves the large majority of them without a
// single loop iteration.

#ifndef N148_LOOKUP_BITS
#define N148_LOOKUP_BITS 10
#endif
#define LOOKUP_BITS N148_LOOKUP_BITS
#define LOOKUP_SIZE (1 << LOOKUP_BITS)

typedef struct {
    int min_code[17];
    int max_code[17];        // -1 when no code has this length
    int value_index[17];
    const unsigned char *values;

    /* This table has two entry forms.  A resolved entry folds the Huffman
       code, amplitude and sign into one lookup.  A partial entry retains
       code length and symbol when the amplitude extends past the lookup
       window.  Zero alone selects the long-code path. */
    unsigned int action[LOOKUP_SIZE];
} HuffDecoder;

#define ACTION_BITS_SHIFT 16
#define ACTION_RUN_SHIFT  21
#define ACTION_EOB        (1u << 25)
#define ACTION_ZRL        (1u << 26)
#define ACTION_PARTIAL    (1u << 31)

static void build_decoder(const HuffSpec *spec, HuffDecoder *decoder,
                          int is_ac) {
    decoder->values = spec->values;

    int code = 0, k = 0;
    for (int length = 1; length <= 16; length++) {
        if (spec->bits[length] == 0) {
            decoder->max_code[length] = -1;
        } else {
            decoder->value_index[length] = k;
            decoder->min_code[length] = code;
            code += spec->bits[length];
            k    += spec->bits[length];
            decoder->max_code[length] = code - 1;
        }
        code <<= 1;
    }

    memset(decoder->action, 0, sizeof(decoder->action));

    // Fill every lookup slot whose prefix matches a short code.
    code = 0; k = 0;
    for (int length = 1; length <= 16; length++) {
        for (int i = 0; i < spec->bits[length]; i++, k++, code++) {
            if (length <= LOOKUP_BITS) {
                int shift = LOOKUP_BITS - length;
                int start = code << shift;
                int end   = start + (1 << shift);
                for (int slot = start; slot < end; slot++) {
                    decoder->action[slot] = ACTION_PARTIAL |
                        ((unsigned int) length << ACTION_BITS_SHIFT) |
                        spec->values[k];
                }
            }

            int symbol = spec->values[k];
            int amplitude_size = is_ac ? (symbol & 0x0F) : symbol;
            int special = is_ac && (symbol == 0x00 || symbol == 0xF0);
            int total = length + (special ? 0 : amplitude_size);
            if (total > LOOKUP_BITS || (!special && amplitude_size == 0))
                continue;

            int amplitudes = special ? 1 : (1 << amplitude_size);
            int suffix_bits = LOOKUP_BITS - total;
            for (int amplitude = 0; amplitude < amplitudes; amplitude++) {
                int value = amplitude;
                if (!special && amplitude < (1 << (amplitude_size - 1)))
                    value += 1 - (1 << amplitude_size);

                unsigned int action = (unsigned short) value;
                action |= (unsigned int) total << ACTION_BITS_SHIFT;
                if (is_ac) {
                    action |= (unsigned int)(symbol >> 4) << ACTION_RUN_SHIFT;
                    if (symbol == 0x00) action |= ACTION_EOB;
                    if (symbol == 0xF0) action |= ACTION_ZRL;
                }

                int prefix = ((code << (special ? 0 : amplitude_size)) |
                              amplitude) << suffix_bits;
                int repeat = 1 << suffix_bits;
                for (int slot = prefix; slot < prefix + repeat; slot++)
                    decoder->action[slot] = action;
            }
        }
        code <<= 1;
    }
}

// ============================================================
// BIT READER
// ============================================================
//
// The accumulator is kept left aligned: the next bit to be consumed
// always sits at the top. Peeking is then a single shift, and a
// refill can pull eight bytes in one read instead of looping a byte
// at a time.

typedef struct {
    const unsigned char *buffer;
    long size;
    long position;
    unsigned long long accumulator;
    int available;                    // valid bits, counted from the top
    int padding;                      // synthetic zero bits after the payload
} BitReader;

static void br_init(BitReader *reader, const unsigned char *buffer, long size) {
    reader->buffer = buffer;
    reader->size = size;
    reader->position = 0;
    reader->accumulator = 0;
    reader->available = 0;
    reader->padding = 0;
}

static inline unsigned int load_be32(const unsigned char *p) {
    unsigned int v;
    memcpy(&v, p, sizeof(v));
#if defined(__GNUC__) || defined(__clang__)
    return __builtin_bswap32(v);
#else
    return ((v & 0x000000FFu) << 24) | ((v & 0x0000FF00u) << 8) |
           ((v & 0x00FF0000u) >> 8)  | ((v & 0xFF000000u) >> 24);
#endif
}

static inline void br_refill(BitReader *reader) {
    /* A Huffman code plus its amplitude uses at most 31 bits.  Keeping
       32 ready avoids the old overlapping 64-bit load before every symbol. */
    if (reader->available >= 32) return;

    if (reader->position + 4 <= reader->size) {
        unsigned int next = load_be32(reader->buffer + reader->position);
        reader->accumulator |=
            (unsigned long long) next << (32 - reader->available);
        reader->position += 4;
        reader->available += 32;
        return;
    }

    while (reader->available < 32) {
        unsigned long long byte = 0;
        if (reader->position < reader->size) {
            byte = reader->buffer[reader->position++];
        } else {
            reader->padding += 8;
        }
        reader->accumulator |= byte << (56 - reader->available);
        reader->available += 8;
    }
}

static inline unsigned int br_peek(BitReader *reader, int count) {
    return (unsigned int)(reader->accumulator >> (64 - count));
}

static inline void br_skip(BitReader *reader, int count) {
    reader->accumulator <<= count;
    reader->available -= count;
}

static inline unsigned int br_read(BitReader *reader, int count) {
    if (count == 0) return 0;
    unsigned int value = br_peek(reader, count);
    br_skip(reader, count);
    return value;
}

/* Returns length in the high byte and symbol in the low byte, without
   consuming either the code or its amplitude. */
static int br_read_code_slow(BitReader *reader, const HuffDecoder *decoder) {
    unsigned int bits = br_peek(reader, 16);
    for (int length = LOOKUP_BITS + 1; length <= 16; length++) {
        int code = (int)(bits >> (16 - length));
        if (decoder->max_code[length] >= 0 &&
            code >= decoder->min_code[length] &&
            code <= decoder->max_code[length]) {
            int offset = decoder->value_index[length]
                       + (code - decoder->min_code[length]);
            return (length << 8) | decoder->values[offset];
        }
    }
    br_skip(reader, 16);             // preserve progress on malformed input
    return 0;
}

#if defined(__GNUC__) || defined(__clang__)
__attribute__((always_inline))
#endif
static inline int br_read_code_fallback(BitReader *reader,
                                        const HuffDecoder *decoder,
                                        unsigned int entry) {
    if (entry & ACTION_PARTIAL)
        return (int)(((entry >> ACTION_BITS_SHIFT) & 31) << 8) |
                     (int)(entry & 0xFF);
    return br_read_code_slow(reader, decoder);
}

/* Consumes a Huffman code and its amplitude together, then restores sign. */
static inline int br_read_amplitude(BitReader *reader, int code_length,
                                    int size) {
    if (size == 0) {
        br_skip(reader, code_length);
        return 0;
    }
    int total = code_length + size;
    unsigned int mask = (1u << size) - 1u;
    int value = (int)(br_peek(reader, total) & mask);
    br_skip(reader, total);
    int threshold = 1 << (size - 1);
    unsigned int negative = (unsigned int)-(value < threshold);
    return value + (int)(negative & (1u - (1u << size)));
}

// ============================================================
// DEQUANTIZATION TABLE FOR THE FAST INVERSE TRANSFORM
// ============================================================

typedef struct { float multiplier[64]; } FastDequant;

static void build_fast_dequant(int quantization[8][8], FastDequant *out) {
    for (int u = 0; u < 8; u++)
        for (int v = 0; v < 8; v++)
            out->multiplier[u*8+v] =
                (float)(quantization[u][v] * aan_scale_factor(u, v) / 64.0);
}

// ============================================================
// BLOCK RECONSTRUCTION
// ============================================================

#define SPARSE_TWO_BASE   64
#define SPARSE_THREE_BASE (64 + 4096)

/* Returns the flat byte value plus one for a DC-only block, zero for the full
   transform, or a negative sparse descriptor.  Sparse descriptors pack one,
   two or three six-bit natural-order indices into disjoint integer ranges. */
static int decode_block(BitReader *reader, float block[64],
                        const FastDequant *dequant,
                        const HuffDecoder *dc_decoder,
                        const HuffDecoder *ac_decoder,
                        int *dc_previous) {
    // Coefficients are dequantized as they are read. Writing straight
    // into the natural order array removes the separate 64 step
    // reordering pass: only the handful that survived are touched.
    float *coefficients = block;

    br_refill(reader);
    unsigned int action = dc_decoder->action[br_peek(reader, LOOKUP_BITS)];
    int code;
    int difference;
    if (action && !(action & ACTION_PARTIAL)) {
        br_skip(reader, (action >> ACTION_BITS_SHIFT) & 31);
        difference = (short) action;
    } else {
        code = br_read_code_fallback(reader, dc_decoder, action);
        int size = code & 0xFF;
        difference = br_read_amplitude(reader, code >> 8, size);
    }
    int dc = *dc_previous + difference;
    *dc_previous = dc;
    float dc_coefficient = dc * dequant->multiplier[0];

    int nonzero_ac = 0;
    int single_ac_index = 0;
    int second_ac_index = 0;
    int third_ac_index = 0;
    int position = 1;
    while (position < 64) {
        br_refill(reader);
        action = ac_decoder->action[br_peek(reader, LOOKUP_BITS)];
        int value;
        if (action && !(action & ACTION_PARTIAL)) {
            br_skip(reader, (action >> ACTION_BITS_SHIFT) & 31);
            if (action & ACTION_EOB) break;
            if (action & ACTION_ZRL) {
                position += 16;
                continue;
            }
            position += (action >> ACTION_RUN_SHIFT) & 15;
            value = (short) action;
        } else {
            code = br_read_code_fallback(reader, ac_decoder, action);
            if (code == 0) break;
            int code_length = code >> 8;
            int symbol = code & 0xFF;
            if (symbol == 0x00) {                          // EOB
                br_skip(reader, code_length);
                break;
            }
            if (symbol == 0xF0) {                          // ZRL
                br_skip(reader, code_length);
                position += 16;
                continue;
            }

            position += symbol >> 4;
            int coefficient_size = symbol & 0x0F;
            value = br_read_amplitude(reader, code_length, coefficient_size);
        }
        if (position >= 64) {
            break;
        }

        int index = ZIGZAG[position];
        if (nonzero_ac == 0) {
            /* Most low-frequency blocks end at EOB.  Delay clearing the
               transform workspace until an AC coefficient proves it is
               actually needed. */
            memset(coefficients, 0, 64 * sizeof(*coefficients));
            coefficients[0] = dc_coefficient;
            single_ac_index = index;
        } else if (nonzero_ac == 1) {
            second_ac_index = index;
        } else if (nonzero_ac == 2) {
            third_ac_index = index;
        }
        coefficients[index] = value * dequant->multiplier[index];
        nonzero_ac++;
        position++;
    }

    // A block whose AC coefficients all vanished reconstructs to one
    // flat value, so the transform can be skipped entirely. At lower
    // quality settings this covers a large share of the image.
    if (nonzero_ac == 0) {
        float flat = dc_coefficient + 128.0f;   // the 1/8 lives in the table
        if (flat < 0.0f)   flat = 0.0f;
        if (flat > 255.0f) flat = 255.0f;
        return (int)(flat + 0.5f) + 1;
    }

    if (nonzero_ac == 1) return -single_ac_index;
    if (nonzero_ac == 2)
        return -(SPARSE_TWO_BASE +
                 (single_ac_index << 6) + second_ac_index);
    if (nonzero_ac == 3)
        return -(SPARSE_THREE_BASE + (single_ac_index << 12) +
                 (second_ac_index << 6) + third_ac_index);

    return 0;
}

static long decode_plane(BitReader *reader, Plane *plane,
                         const FastDequant *dequant,
                         const HuffDecoder *dc_decoder,
                         const HuffDecoder *ac_decoder) {
    int blocks_x = plane->width / 8 + (plane->width % 8 != 0);
    int blocks_y = plane->height / 8 + (plane->height % 8 != 0);
    int dc_previous = 0;
    int use_avx2 = 0;
#if defined(__x86_64__) || defined(__i386__)
    use_avx2 = (n148_cpu_level() >= N148_CPU_AVX2);
#endif

    for (int by = 0; by < blocks_y; by++) {
        for (int bx = 0; bx < blocks_x; bx++) {
            float block[64];
            int max_x = bx*8 + 8 <= plane->width  ? 8 : plane->width  - bx*8;
            int max_y = by*8 + 8 <= plane->height ? 8 : plane->height - by*8;
            unsigned char *block_dst =
                plane->data + (long)(by * 8) * plane->width + bx * 8;
            int flat = decode_block(reader, block, dequant, dc_decoder,
                                    ac_decoder, &dc_previous);

            if (flat > 0) {
                unsigned char *dst = block_dst;
                if (max_x == 8) {
                    unsigned long long packed = 0x0101010101010101ull *
                                                (unsigned int)(flat - 1);
                    for (int r = 0; r < max_y; r++, dst += plane->width)
                        memcpy(dst, &packed, sizeof(packed));
                } else {
                    for (int r = 0; r < max_y; r++, dst += plane->width)
                        memset(dst, flat - 1, (size_t) max_x);
                }
                continue;
            }

#if defined(__x86_64__) || defined(__i386__)
            if (flat < 0 && max_x == 8 && max_y == 8 && use_avx2) {
                int sparse = -flat;
                if (sparse >= SPARSE_THREE_BASE) {
                    sparse -= SPARSE_THREE_BASE;
                    int first = sparse >> 12;
                    int second = (sparse >> 6) & 63;
                    int third = sparse & 63;
                    idct_block_store_three_avx2(
                        block[0], block[first], first,
                        block[second], second, block[third], third,
                        block_dst, plane->width);
                } else if (sparse >= SPARSE_TWO_BASE) {
                    sparse -= SPARSE_TWO_BASE;
                    int first = sparse >> 6;
                    int second = sparse & 63;
                    idct_block_store_two_avx2(
                        block[0], block[first], first,
                        block[second], second, block_dst, plane->width);
                } else {
                    idct_block_store_single_avx2(
                        block[0], block[sparse], sparse,
                        block_dst, plane->width);
                }
                continue;
            }
#endif

#if defined(__x86_64__) || defined(__i386__)
            if (max_x == 8 && max_y == 8 && use_avx2) {
                idct_block_store_avx2(block, block_dst, plane->width);
                continue;
            }
            if (use_avx2) idct_block_avx2(block, block);
            else
#endif
            idct_block_fast(block, block);

            for (int r = 0; r < max_y; r++) {
                unsigned char *dst =
                    plane->data + (long)(by*8 + r) * plane->width + bx*8;
                const float *src = &block[r*8];
                for (int c = 0; c < max_x; c++) {
                    float value = src[c];
                    if (value < 0.0f)   value = 0.0f;
                    if (value > 255.0f) value = 255.0f;
                    dst[c] = (unsigned char)(value + 0.5f);
                }
            }
        }
    }
    return (long) blocks_x * blocks_y;
}

int n148_reconstruct_coeff_plane_ex(const short *quantized, long count,
                                    int width, int height, int quality,
                                    int chroma_plane, int perceptual_color,
                                    Plane *output) {
    if (!quantized || !output || width <= 0 || height <= 0) return 0;
    int blocks_x = width / 8 + (width % 8 != 0);
    int blocks_y = height / 8 + (height % 8 != 0);
    if ((size_t) blocks_x > SIZE_MAX / (size_t) blocks_y) return 0;
    size_t block_count = (size_t) blocks_x * (size_t) blocks_y;
    if (block_count > LONG_MAX || count != (long) block_count) return 0;

    init_dct_tables();
    int quantization[8][8];
    const int (*base)[8];
    if (perceptual_color) {
        base = chroma_plane ? Q_PERCEPTUAL_OPPONENT_BASE :
                              Q_PERCEPTUAL_INTENSITY_BASE;
    } else {
        base = chroma_plane ? Q_CHROMA_BASE : Q_LUMA_BASE;
    }
    scale_table(base, quality, quantization);
    FastDequant dequant;
    build_fast_dequant(quantization, &dequant);
    *output = create_plane(width, height);
    if (!output->data) return 0;

    int use_avx2 = 0;
#if defined(__x86_64__) || defined(__i386__)
    use_avx2 = n148_cpu_level() >= N148_CPU_AVX2;
#endif
    for (int by = 0; by < blocks_y; by++) {
        for (int bx = 0; bx < blocks_x; bx++) {
            const short *zz = quantized +
                ((long) by * blocks_x + bx) * 64;
            int max_x = bx * 8 + 8 <= width ? 8 : width - bx * 8;
            int max_y = by * 8 + 8 <= height ? 8 : height - by * 8;
            unsigned char *destination = output->data +
                (long)(by * 8) * width + bx * 8;

            int nonzero_ac = 0;
            for (int position = 1; position < 64; position++)
                nonzero_ac += zz[position] != 0;
            if (nonzero_ac == 0) {
                float flat = zz[0] * dequant.multiplier[0] + 128.0f;
                if (flat < 0.0f) flat = 0.0f;
                if (flat > 255.0f) flat = 255.0f;
                unsigned char value = (unsigned char)(flat + 0.5f);
                for (int row = 0; row < max_y; row++)
                    memset(destination + (long) row * width, value,
                           (size_t) max_x);
                continue;
            }

            float block[64] = {0};
            for (int position = 0; position < 64; position++) {
                int natural = ZIGZAG[position];
                block[natural] = zz[position] * dequant.multiplier[natural];
            }
#if defined(__x86_64__) || defined(__i386__)
            if (max_x == 8 && max_y == 8 && use_avx2) {
                idct_block_store_avx2(block, destination, width);
                continue;
            }
            if (use_avx2) idct_block_avx2(block, block);
            else
#endif
            idct_block_fast(block, block);
            for (int row = 0; row < max_y; row++) {
                unsigned char *target = destination + (long) row * width;
                for (int column = 0; column < max_x; column++) {
                    float value = block[row * 8 + column];
                    if (value < 0.0f) value = 0.0f;
                    if (value > 255.0f) value = 255.0f;
                    target[column] = (unsigned char)(value + 0.5f);
                }
            }
        }
    }
    return 1;
}

int n148_reconstruct_coeff_plane(const short *quantized, long count,
                                 int width, int height, int quality,
                                 int chroma_plane, Plane *output) {
    return n148_reconstruct_coeff_plane_ex(quantized, count, width, height,
                                            quality, chroma_plane, 0, output);
}

int decode_image(unsigned char *buffer, long buffer_size,
                 int width, int height, int quality, int chroma,
                 const HuffSpec specs[HUFFMAN_TABLE_COUNT],
                 Plane *y, Plane *cb, Plane *cr, DecodeStats *stats) {
    init_dct_tables();

    HuffDecoder dc_luma, ac_luma, dc_chroma, ac_chroma;
    build_decoder(&specs[HUFFMAN_DC_LUMA],   &dc_luma,   0);
    build_decoder(&specs[HUFFMAN_AC_LUMA],   &ac_luma,   1);
    build_decoder(&specs[HUFFMAN_DC_CHROMA], &dc_chroma, 0);
    build_decoder(&specs[HUFFMAN_AC_CHROMA], &ac_chroma, 1);

    int luma_quant[8][8], chroma_quant[8][8];
    scale_table(Q_LUMA_BASE,   quality, luma_quant);
    scale_table(Q_CHROMA_BASE, quality, chroma_quant);

    FastDequant dequant_luma, dequant_chroma;
    build_fast_dequant(luma_quant,   &dequant_luma);
    build_fast_dequant(chroma_quant, &dequant_chroma);

    int chroma_width, chroma_height;
    chroma_dimensions(chroma, width, height, &chroma_width, &chroma_height);

    *y  = create_plane(width, height);
    *cb = create_plane(chroma_width, chroma_height);
    *cr = create_plane(chroma_width, chroma_height);
    if (!y->data || !cb->data || !cr->data) return 0;

    BitReader reader;
    br_init(&reader, buffer, buffer_size);

    stats->blocks_y  = decode_plane(&reader, y,  &dequant_luma,   &dc_luma,   &ac_luma);
    stats->blocks_cb = decode_plane(&reader, cb, &dequant_chroma, &dc_chroma, &ac_chroma);
    stats->blocks_cr = decode_plane(&reader, cr, &dequant_chroma, &dc_chroma, &ac_chroma);

    long consumed_bits = reader.position * 8L -
                         (reader.available - reader.padding);
    stats->bytes_consumed = (consumed_bits + 7) >> 3;
    return 1;
}

// ============================================================
// YCbCr -> RGB
// ============================================================

static unsigned char clamp_byte(float value) {
    if (value < 0.0f)   return 0;
    if (value > 255.0f) return 255;
    return (unsigned char)(value + 0.5f);
}

// ============================================================
// CHROMA UPSAMPLING
// ============================================================
//
// For the subsampled modes the bilinear weights are not arbitrary:
// mapping pixel centres between a full resolution grid and a half
// resolution one always lands on the same 3:1 split. Knowing that in
// advance turns the interpolation into integer arithmetic with fixed
// weights, far cheaper than the general bilinear formula.
//
//   horizontal only:  (3*near + far) * 4        -> scaled by 16
//   vertical only:    (3*near + far) * 4        -> scaled by 16
//   both:             9*a + 3*b + 3*c + d       -> scaled by 16
//
// The rows stay at that 16x scale and reach the colour stage
// unrounded: collapsing them to a byte first would discard the
// fractional part the conversion still needs.

#define CHROMA_SHIFT 4                 /* rows carry value * 16 */

#if defined(__x86_64__) || defined(__i386__)
// Vertical blend of two chroma rows, sixteen samples per pass.
__attribute__((target("avx2")))
static void blend_rows_avx2(const unsigned char *near_row,
                            const unsigned char *far_row,
                            int count, unsigned short *out) {
    const __m256i three = _mm256_set1_epi16(3);
    int x = 0;
    for (; x + 16 <= count; x += 16) {
        __m256i n = _mm256_cvtepu8_epi16(_mm_loadu_si128((const __m128i *)(near_row + x)));
        __m256i f = _mm256_cvtepu8_epi16(_mm_loadu_si128((const __m128i *)(far_row  + x)));
        _mm256_storeu_si256((__m256i *)(out + x),
                            _mm256_add_epi16(_mm256_mullo_epi16(n, three), f));
    }
    for (; x < count; x++)
        out[x] = (unsigned short)(3 * near_row[x] + far_row[x]);
}

// Horizontal stretch: every source sample produces the two outputs it
// dominates, so both are computed as vectors and interleaved back.
__attribute__((target("avx2")))
static void stretch_avx2(const unsigned short *src, int first, int last,
                         unsigned short *dst) {
    const __m256i three = _mm256_set1_epi16(3);
    int k = first;
    for (; k + 16 <= last; k += 16) {
        __m256i cur  = _mm256_loadu_si256((const __m256i *)(src + k));
        __m256i prev = _mm256_loadu_si256((const __m256i *)(src + k - 1));
        __m256i next = _mm256_loadu_si256((const __m256i *)(src + k + 1));

        __m256i scaled = _mm256_mullo_epi16(cur, three);
        __m256i even = _mm256_add_epi16(scaled, prev);
        __m256i odd  = _mm256_add_epi16(scaled, next);

        __m256i lo = _mm256_unpacklo_epi16(even, odd);
        __m256i hi = _mm256_unpackhi_epi16(even, odd);
        _mm256_storeu_si256((__m256i *)(dst + 2*k),
                            _mm256_permute2x128_si256(lo, hi, 0x20));
        _mm256_storeu_si256((__m256i *)(dst + 2*k + 16),
                            _mm256_permute2x128_si256(lo, hi, 0x31));
    }
    for (; k < last; k++) {
        int centre = src[k] * 3;
        dst[2*k]     = (unsigned short)(centre + src[k-1]);
        dst[2*k + 1] = (unsigned short)(centre + src[k+1]);
    }
}
#endif

static void expand_h(const unsigned char *src, int src_width,
                     unsigned short *dst, int dst_width) {
    if (src_width == 1) {
        unsigned short v = (unsigned short)(src[0] << CHROMA_SHIFT);
        for (int x = 0; x < dst_width; x++) dst[x] = v;
        return;
    }

    dst[0] = (unsigned short)(src[0] * 16);
    if (dst_width > 1) dst[1] = (unsigned short)(src[0] * 12 + src[1] * 4);

    for (int k = 1; k < src_width - 1; k++) {
        int centre = src[k] * 12;
        dst[2*k]     = (unsigned short)(centre + src[k-1] * 4);
        dst[2*k + 1] = (unsigned short)(centre + src[k+1] * 4);
    }

    int last = src_width - 1;
    int centre = src[last] * 12;
    if (2*last     < dst_width) dst[2*last]     = (unsigned short)(centre + src[last-1] * 4);
    if (2*last + 1 < dst_width) dst[2*last + 1] = (unsigned short)(centre + src[last] * 4);
    for (int x = 2*src_width; x < dst_width; x++)
        dst[x] = (unsigned short)(src[src_width-1] << CHROMA_SHIFT);
}

static void expand_hv(const unsigned char *near_row, const unsigned char *far_row,
                      int src_width, unsigned short *scratch,
                      unsigned short *dst, int dst_width, int use_avx2) {
    int blended = 0;
#if defined(__x86_64__) || defined(__i386__)
    if (use_avx2) {
        blend_rows_avx2(near_row, far_row, src_width, scratch);
        blended = 1;
    }
#else
    (void) use_avx2;
#endif
    if (!blended) {
        for (int x = 0; x < src_width; x++)
            scratch[x] = (unsigned short)(3 * near_row[x] + far_row[x]);
    }

    if (src_width == 1) {
        unsigned short v = (unsigned short)(scratch[0] * 4);
        for (int x = 0; x < dst_width; x++) dst[x] = v;
        return;
    }

    dst[0] = (unsigned short)(scratch[0] * 4);
    if (dst_width > 1) dst[1] = (unsigned short)(scratch[0] * 3 + scratch[1]);

    int stretched = 0;
#if defined(__x86_64__) || defined(__i386__)
    if (use_avx2) {
        stretch_avx2(scratch, 1, src_width - 1, dst);
        stretched = 1;
    }
#endif
    if (!stretched) {
        for (int k = 1; k < src_width - 1; k++) {
            int centre = scratch[k] * 3;
            dst[2*k]     = (unsigned short)(centre + scratch[k-1]);
            dst[2*k + 1] = (unsigned short)(centre + scratch[k+1]);
        }
    }

    int last = src_width - 1;
    int centre = scratch[last] * 3;
    if (2*last     < dst_width) dst[2*last]     = (unsigned short)(centre + scratch[last-1]);
    if (2*last + 1 < dst_width) dst[2*last + 1] = (unsigned short)(centre + scratch[last]);
    for (int x = 2*src_width; x < dst_width; x++)
        dst[x] = (unsigned short)(scratch[src_width-1] * 4);
}

// Produces one chroma row for output line py, scaled by 16.
static void expand_chroma_row(Plane *plane, int py, int dst_width,
                              int stretch_x, int stretch_y,
                              unsigned short *scratch, unsigned short *dst,
                              int use_avx2) {
    if (stretch_y) {
        int near = py >> 1;
        int far  = (py & 1) ? near + 1 : near - 1;
        if (far < 0) far = 0;
        if (far >= plane->height) far = plane->height - 1;
        if (near >= plane->height) near = plane->height - 1;

        const unsigned char *near_row = plane->data + (long) near * plane->width;
        const unsigned char *far_row  = plane->data + (long) far  * plane->width;

        if (stretch_x) {
            expand_hv(near_row, far_row, plane->width, scratch, dst, dst_width, use_avx2);
        } else {
            for (int x = 0; x < dst_width; x++) {
                int sx = x < plane->width ? x : plane->width - 1;
                dst[x] = (unsigned short)((3 * near_row[sx] + far_row[sx]) * 4);
            }
        }
        return;
    }

    int sy = py < plane->height ? py : plane->height - 1;
    const unsigned char *row = plane->data + (long) sy * plane->width;

    if (stretch_x) {
        expand_h(row, plane->width, dst, dst_width);
    } else {
        for (int x = 0; x < dst_width; x++) {
            int sx = x < plane->width ? x : plane->width - 1;
            dst[x] = (unsigned short)(row[sx] << CHROMA_SHIFT);
        }
    }
}

// ============================================================
// COLOUR CONVERSION
// ============================================================

#if defined(__x86_64__) || defined(__i386__)
// Interleaves eight pixels worth of separate R, G and B bytes into
// the 24 packed bytes the output image expects.
__attribute__((target("avx2")))
static inline void store_rgb8(unsigned char *out, __m128i r, __m128i g, __m128i b) {
    __m128i rg = _mm_unpacklo_epi8(r, g);
    const __m128i mrg0 = _mm_setr_epi8(
         0, 1,-1, 2, 3,-1, 4, 5,-1, 6, 7,-1, 8, 9,-1,10);
    const __m128i mb0 = _mm_setr_epi8(
        -1,-1, 0,-1,-1, 1,-1,-1, 2,-1,-1, 3,-1,-1, 4,-1);
    _mm_storeu_si128((__m128i *) out,
        _mm_or_si128(_mm_shuffle_epi8(rg, mrg0), _mm_shuffle_epi8(b, mb0)));

    const __m128i mrg1 = _mm_setr_epi8(
        11,-1,12,13,-1,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1);
    const __m128i mb1 = _mm_setr_epi8(
        -1, 5,-1,-1, 6,-1,-1, 7,-1,-1,-1,-1,-1,-1,-1,-1);
    _mm_storel_epi64((__m128i *)(out + 16),
        _mm_or_si128(_mm_shuffle_epi8(rg, mrg1), _mm_shuffle_epi8(b, mb1)));
}

__attribute__((target("avx2"), always_inline))
static inline void finish_ycbcr8_avx2(__m256 yf, __m256 cbf, __m256 crf,
                                      __m256 rf, __m256 bf,
                                      unsigned char *out) {
    const __m256 k_g_cb = _mm256_set1_ps(-0.344136f);
    const __m256 k_g_cr = _mm256_set1_ps(-0.714136f);
    const __m256 round  = _mm256_set1_ps(0.5f);
    rf = _mm256_add_ps(rf, round);
    bf = _mm256_add_ps(bf, round);
    __m256 gf = _mm256_add_ps(_mm256_add_ps(yf,
                   _mm256_add_ps(_mm256_mul_ps(cbf, k_g_cb),
                                 _mm256_mul_ps(crf, k_g_cr))), round);

    __m256i r = _mm256_cvttps_epi32(rf);
    __m256i g = _mm256_cvttps_epi32(gf);
    __m256i b = _mm256_cvttps_epi32(bf);
    __m128i r16 = _mm_packs_epi32(_mm256_castsi256_si128(r),
                                  _mm256_extracti128_si256(r, 1));
    __m128i g16 = _mm_packs_epi32(_mm256_castsi256_si128(g),
                                  _mm256_extracti128_si256(g, 1));
    __m128i b16 = _mm_packs_epi32(_mm256_castsi256_si128(b),
                                  _mm256_extracti128_si256(b, 1));
    store_rgb8(out, _mm_packus_epi16(r16, r16),
                    _mm_packus_epi16(g16, g16),
                    _mm_packus_epi16(b16, b16));
}

__attribute__((target("avx2"), always_inline))
static inline void convert_ycbcr8_avx2(const unsigned char *luma,
                                        __m128i blue, __m128i red,
                                        unsigned char *out) {
    const __m256 inv    = _mm256_set1_ps(1.0f / (1 << CHROMA_SHIFT));
    const __m256 half   = _mm256_set1_ps(128.0f);
    const __m256 k_r_cr = _mm256_set1_ps(1.402f);
    const __m256 k_b_cb = _mm256_set1_ps(1.772f);

    __m128i y8 = _mm_loadl_epi64((const __m128i *) luma);
    __m256 yf  = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(y8));
    __m256 cbf = _mm256_sub_ps(
        _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepu16_epi32(blue)), inv), half);
    __m256 crf = _mm256_sub_ps(
        _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepu16_epi32(red)), inv), half);

    __m256 rf = _mm256_add_ps(yf, _mm256_mul_ps(crf, k_r_cr));
    __m256 bf = _mm256_add_ps(yf, _mm256_mul_ps(cbf, k_b_cb));
    finish_ycbcr8_avx2(yf, cbf, crf, rf, bf, out);
}

__attribute__((target("avx2,fma"), always_inline))
static inline void convert_ycbcr8_fma(const unsigned char *luma,
                                      __m128i blue, __m128i red,
                                      unsigned char *out) {
    const __m256 inv    = _mm256_set1_ps(1.0f / (1 << CHROMA_SHIFT));
    const __m256 half   = _mm256_set1_ps(128.0f);
    const __m256 k_r_cr = _mm256_set1_ps(1.402f);
    const __m256 k_b_cb = _mm256_set1_ps(1.772f);

    __m128i y8 = _mm_loadl_epi64((const __m128i *) luma);
    __m256 yf  = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(y8));
    __m256 cbf = _mm256_sub_ps(
        _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepu16_epi32(blue)), inv), half);
    __m256 crf = _mm256_sub_ps(
        _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepu16_epi32(red)), inv), half);

    __m256 rf = _mm256_fmadd_ps(crf, k_r_cr, yf);
    __m256 bf = _mm256_fmadd_ps(cbf, k_b_cb, yf);
    finish_ycbcr8_avx2(yf, cbf, crf, rf, bf, out);
}

// Eight pixels per iteration. The chroma rows arrive scaled by 16 so
// no precision is lost on the way in.
__attribute__((target("avx2")))
static void ycbcr_row_avx2(const unsigned char *luma,
                           const unsigned short *blue, const unsigned short *red,
                           unsigned char *out, int count) {
    int i = 0;
    // Each interleaved store writes exactly the 24 bytes for this group.
    for (; i + 8 <= count; i += 8) {
        __m128i cb16 = _mm_loadu_si128((const __m128i *)(blue + i));
        __m128i cr16 = _mm_loadu_si128((const __m128i *)(red  + i));
        convert_ycbcr8_avx2(luma + i, cb16, cr16, out + i * 3);
    }

    const float inv_s = 1.0f / (1 << CHROMA_SHIFT);
    for (; i < count; i++) {
        float yf  = luma[i];
        float cbf = blue[i] * inv_s - 128.0f;
        float crf = red[i]  * inv_s - 128.0f;
        out[i*3+0] = clamp_byte(yf + 1.402f * crf);
        float green = (-0.344136f * cbf) + (-0.714136f * crf);
        out[i*3+1] = clamp_byte(yf + green);
        out[i*3+2] = clamp_byte(yf + 1.772f * cbf);
    }
}

__attribute__((target("avx2,fma")))
static void ycbcr_row_fma(const unsigned char *luma,
                          const unsigned short *blue,
                          const unsigned short *red,
                          unsigned char *out, int count) {
    int i = 0;
    for (; i + 8 <= count; i += 8) {
        __m128i cb16 = _mm_loadu_si128((const __m128i *)(blue + i));
        __m128i cr16 = _mm_loadu_si128((const __m128i *)(red  + i));
        convert_ycbcr8_fma(luma + i, cb16, cr16, out + i * 3);
    }

    /* Keep the rare tail on the non-FMA implementation: fusing the green
       channel changes a handful of exact half-way rounding cases. */
    if (i < count)
        ycbcr_row_avx2(luma + i, blue + i, red + i,
                       out + i * 3, count - i);
}

#endif

// ============================================================
// RECONSTRUCTION
// ============================================================

typedef struct {
    Plane *y, *cb, *cr;
    Image *output;
    int smooth, stretch_x, stretch_y, use_avx2, use_fma, perceptual_color;
} MergeJob;

// Reconstructs a band of output rows. Every worker keeps its own
// scratch rows so nothing is shared between them.
static void merge_rows(long start, long end, int worker, void *context) {
    (void) worker;
    MergeJob *job = (MergeJob *) context;
    Plane *y = job->y, *cb = job->cb, *cr = job->cr;
    int width = y->width;

#define MERGE_STACK_WIDTH 2048
    _Alignas(32) unsigned short stack_rows[(MERGE_STACK_WIDTH + 32) * 3];
    unsigned short *allocated = NULL;
    unsigned short *row_cb;
    if (width <= MERGE_STACK_WIDTH && cb->width <= MERGE_STACK_WIDTH) {
        row_cb = stack_rows;
    } else {
        size_t samples = (size_t)(width + 32) * 2 + (size_t)cb->width + 32;
        allocated = (unsigned short *) malloc(samples * sizeof(unsigned short));
        if (!allocated) return;
        row_cb = allocated;
    }
    unsigned short *row_cr = row_cb + width + 32;
    unsigned short *scratch = row_cr + width + 32;

    const float inv_scale = 1.0f / (1 << CHROMA_SHIFT);

    for (long py = start; py < end; py++) {
        unsigned char *out = job->output->pixels + py * width * 3;
        const unsigned char *luma = y->data + py * width;

        if (job->smooth) {
            expand_chroma_row(cb, (int) py, width, job->stretch_x, job->stretch_y,
                              scratch, row_cb, job->use_avx2);
            expand_chroma_row(cr, (int) py, width, job->stretch_x, job->stretch_y,
                              scratch, row_cr, job->use_avx2);
        } else {
            int cy = job->stretch_y ? (int)(py >> 1) : (int) py;
            if (cy >= cb->height) cy = cb->height - 1;
            const unsigned char *src_cb = cb->data + (long) cy * cb->width;
            const unsigned char *src_cr = cr->data + (long) cy * cr->width;
            for (int px = 0; px < width; px++) {
                int cx = job->stretch_x ? (px >> 1) : px;
                if (cx >= cb->width) cx = cb->width - 1;
                row_cb[px] = (unsigned short)(src_cb[cx] << CHROMA_SHIFT);
                row_cr[px] = (unsigned short)(src_cr[cx] << CHROMA_SHIFT);
            }
        }

        if (job->perceptual_color) {
            for (int px = 0; px < width; px++)
                n148_perceptual_to_rgb(luma[px], row_cb[px], row_cr[px],
                                       out + px * 3);
            continue;
        }

#if defined(__x86_64__) || defined(__i386__)
        if (job->use_fma) { ycbcr_row_fma(luma, row_cb, row_cr, out, width); continue; }
        if (job->use_avx2) { ycbcr_row_avx2(luma, row_cb, row_cr, out, width); continue; }
#endif
        for (int px = 0; px < width; px++) {
            float value = luma[px];
            float blue_difference = row_cb[px] * inv_scale - 128.0f;
            float red_difference  = row_cr[px] * inv_scale - 128.0f;
            out[px*3+0] = clamp_byte(value + 1.402f * red_difference);
            float green = (-0.344136f * blue_difference) +
                          (-0.714136f * red_difference);
            out[px*3+1] = clamp_byte(value + green);
            out[px*3+2] = clamp_byte(value + 1.772f * blue_difference);
        }
    }

    free(allocated);
#undef MERGE_STACK_WIDTH
}

int n148_merge_channels_ex(Plane *y, Plane *cb, Plane *cr, int smooth,
                           int perceptual_color, Image *output) {
    int width = y->width, height = y->height;

    if (width <= 0 || height <= 0 || !y->data || !cb->data || !cr->data ||
        cb->width != cr->width || cb->height != cr->height) {
        return 0;
    }

    output->width  = width;
    output->height = height;
    output->pixels = (unsigned char *) malloc((size_t)((long) width * height * 3));
    if (!output->pixels) return 0;

    MergeJob job;
    job.y = y; job.cb = cb; job.cr = cr; job.output = output;
    job.smooth = smooth;
    job.perceptual_color = perceptual_color;
    job.stretch_x = (cb->width  < width);
    job.stretch_y = (cb->height < height);
#if defined(__x86_64__) || defined(__i386__)
    int cpu_level = n148_cpu_level();
    job.use_avx2 = (cpu_level >= N148_CPU_AVX2);
    job.use_fma = (cpu_level >= N148_CPU_AVX2_FMA);
#else
    job.use_avx2 = 0;
    job.use_fma = 0;
#endif
    if (perceptual_color) n148_perceptual_init();

    /* On small images the colour merge is only a few tenths of a
       millisecond; dispatching it to a pool costs more than the work saved,
       especially on hybrid CPUs.  Larger frames still scale across cores. */
    if ((long) width * height < 512L * 1024L)
        merge_rows(0, height, 0, &job);
    else
        n148_parallel_for(height, merge_rows, &job);
    return 1;
}

int merge_channels(Plane *y, Plane *cb, Plane *cr, int smooth, Image *output) {
    return n148_merge_channels_ex(y, cb, cr, smooth, 0, output);
}

src/n148i.c

O n148i.c implementa a API pública da biblioteca, do artigo 26. Na V2, ele mais que dobrou de tamanho, porque passou a escolher o formato e o perfil de cada arquivo, a decidir sozinho o layout da cor, como vimos no artigo 35, e a ler todos os formatos de 1 a 7.

Na V1, o arquivo tinha 428 linhas:

/*
 * N.148i public memory-to-memory API
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#include "n148i.h"

#include <limits.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#include "cpu.h"
#include "decoder.h"
#include "encoder.h"
#include "header.h"
#include "huffman.h"
#include "parallel.h"
#include "ppm.h"

typedef struct {
    uint32_t width;
    uint32_t height;
    uint32_t payload_size;
    size_t payload_offset;
    uint8_t version;
    uint8_t quality;
    uint8_t chroma;
    uint8_t optimized;
    HuffSpec specs[HUFFMAN_TABLE_COUNT];
} ParsedHeader;

static void memory_write_u32(uint8_t *destination, uint32_t value) {
    destination[0] = (uint8_t) (value & 0xffu);
    destination[1] = (uint8_t) ((value >> 8) & 0xffu);
    destination[2] = (uint8_t) ((value >> 16) & 0xffu);
    destination[3] = (uint8_t) ((value >> 24) & 0xffu);
}

static uint32_t memory_read_u32(const uint8_t *source) {
    return (uint32_t) source[0] |
        ((uint32_t) source[1] << 8) |
        ((uint32_t) source[2] << 16) |
        ((uint32_t) source[3] << 24);
}

static int valid_chroma(int chroma) {
    return chroma == CHROMA_444 || chroma == CHROMA_422 ||
        chroma == CHROMA_420;
}

static int multiplication_overflows(size_t first, size_t second) {
    return second != 0 && first > SIZE_MAX / second;
}

static n148i_result_t parse_header(const uint8_t *encoded,
                                   size_t encoded_size,
                                   ParsedHeader *parsed) {
    if (!encoded || !parsed) return N148I_ERROR_INVALID_ARGUMENT;
    if (encoded_size < N148I_HEADER_SIZE) return N148I_ERROR_TRUNCATED_DATA;
    if (memcmp(encoded, N148I_MAGIC, N148I_MAGIC_LEN) != 0)
        return N148I_ERROR_INVALID_FORMAT;

    memset(parsed, 0, sizeof(*parsed));
    parsed->version = encoded[5];
    if (parsed->version != N148I_VERSION)
        return N148I_ERROR_UNSUPPORTED_VERSION;

    parsed->width = memory_read_u32(encoded + 6);
    parsed->height = memory_read_u32(encoded + 10);
    parsed->quality = encoded[14];
    parsed->chroma = encoded[15];
    parsed->optimized = encoded[16];
    parsed->payload_size = memory_read_u32(encoded + 17);

    if (parsed->width == 0 || parsed->width > INT_MAX ||
        parsed->height == 0 || parsed->height > INT_MAX ||
        parsed->quality < 1 || parsed->quality > 100 ||
        !valid_chroma(parsed->chroma) || parsed->optimized > 1 ||
        parsed->payload_size == 0) {
        return N148I_ERROR_INVALID_FORMAT;
    }
#if LONG_MAX < UINT32_MAX
    if (parsed->payload_size > (uint32_t) LONG_MAX)
        return N148I_ERROR_SIZE_OVERFLOW;
#endif

    size_t offset = N148I_HEADER_SIZE;
    if (parsed->optimized) {
        for (int table = 0; table < HUFFMAN_TABLE_COUNT; table++) {
            HuffSpec *spec = &parsed->specs[table];
            if (encoded_size - offset < 16)
                return N148I_ERROR_TRUNCATED_DATA;
            for (int length = 1; length <= 16; length++) {
                int count = encoded[offset++];
                spec->bits[length] = count;
                spec->value_count += count;
                if (spec->value_count > HUFFMAN_MAX_SYMBOLS)
                    return N148I_ERROR_CORRUPT_DATA;
            }
            if (spec->value_count == 0)
                return N148I_ERROR_CORRUPT_DATA;
            if ((size_t) spec->value_count > encoded_size - offset)
                return N148I_ERROR_TRUNCATED_DATA;
            memcpy(spec->values, encoded + offset,
                   (size_t) spec->value_count);
            offset += (size_t) spec->value_count;
            if (!huffman_spec_is_valid(spec))
                return N148I_ERROR_CORRUPT_DATA;
        }
    } else {
        huffman_default_specs(parsed->specs);
    }

    if ((size_t) parsed->payload_size > encoded_size - offset)
        return N148I_ERROR_TRUNCATED_DATA;
    if ((size_t) parsed->payload_size != encoded_size - offset)
        return N148I_ERROR_CORRUPT_DATA;
    parsed->payload_offset = offset;
    return N148I_OK;
}

static n148i_result_t normalize_options(
    const n148i_encode_options_t *input,
    n148i_encode_options_t *output) {
    n148i_encode_options_init(output);
    if (!input) return N148I_OK;

    if (input->struct_size <
        offsetof(n148i_encode_options_t, quality) + sizeof(input->quality)) {
        return N148I_ERROR_INVALID_ARGUMENT;
    }
    size_t copy_size = input->struct_size;
    if (copy_size > sizeof(*output)) copy_size = sizeof(*output);
    memcpy(output, input, copy_size);
    output->struct_size = sizeof(*output);

    if (output->quality < 1 || output->quality > 100 ||
        !valid_chroma(output->chroma) ||
        (output->optimize_huffman != 0 && output->optimize_huffman != 1) ||
        output->thread_count < 0 || output->thread_count > N148I_MAX_THREADS) {
        return N148I_ERROR_INVALID_ARGUMENT;
    }
    return N148I_OK;
}

void n148i_encode_options_init(n148i_encode_options_t *options) {
    if (!options) return;
    memset(options, 0, sizeof(*options));
    options->struct_size = sizeof(*options);
    options->quality = 50;
    options->chroma = N148I_CHROMA_420;
    options->optimize_huffman = 1;
    options->thread_count = 0;
}

n148i_result_t n148i_encode_memory(const n148i_image_t *image,
                                   const n148i_encode_options_t *options,
                                   uint8_t **encoded,
                                   size_t *encoded_size) {
    if (!image || !image->pixels || !encoded || !encoded_size ||
        image->width == 0 || image->width > INT_MAX ||
        image->height == 0 || image->height > INT_MAX) {
        return N148I_ERROR_INVALID_ARGUMENT;
    }
    *encoded = NULL;
    *encoded_size = 0;

    n148i_encode_options_t settings;
    n148i_result_t result = normalize_options(options, &settings);
    if (result != N148I_OK) return result;

    size_t width = image->width;
    size_t height = image->height;
    if (multiplication_overflows(width, 3))
        return N148I_ERROR_SIZE_OVERFLOW;
    size_t tight_stride = width * 3;
    size_t source_stride = image->stride ? image->stride : tight_stride;
    if (source_stride < tight_stride ||
        (height > 1 &&
         source_stride > (SIZE_MAX - tight_stride) / (height - 1)) ||
        multiplication_overflows(tight_stride, height) ||
        multiplication_overflows(width, height)) {
        return N148I_ERROR_SIZE_OVERFLOW;
    }
    size_t pixel_count = width * height;
#if LONG_MAX < SIZE_MAX
    if (pixel_count > (size_t) LONG_MAX)
        return N148I_ERROR_SIZE_OVERFLOW;
#endif

    uint8_t *compact = NULL;
    Image internal_image;
    internal_image.width = (int) image->width;
    internal_image.height = (int) image->height;
    internal_image.pixels = image->pixels;
    if (source_stride != tight_stride) {
        compact = (uint8_t *) malloc(tight_stride * height);
        if (!compact) return N148I_ERROR_OUT_OF_MEMORY;
        for (size_t row = 0; row < height; row++) {
            memcpy(compact + row * tight_stride,
                   image->pixels + row * source_stride, tight_stride);
        }
        internal_image.pixels = compact;
    }

    if (settings.thread_count > 0)
        n148_set_thread_count(settings.thread_count);

    Plane y = {0}, cb = {0}, cr = {0};
    HuffSpec specs[HUFFMAN_TABLE_COUNT];
    EncodeStats stats;
    uint8_t *payload = NULL;
    int ok = split_channels(&internal_image, &y, &cb, &cr, settings.chroma);
    free(compact);
    if (ok) {
        ok = encode_image(&y, &cb, &cr, settings.quality,
                          settings.optimize_huffman, specs, &payload, &stats);
    }
    free_plane(&y);
    free_plane(&cb);
    free_plane(&cr);
    if (!ok) {
        free(payload);
        return N148I_ERROR_ENCODE_FAILED;
    }

    if (stats.data_size <= 0 || stats.data_size > UINT32_MAX ||
        stats.table_size < 0) {
        free(payload);
        return N148I_ERROR_SIZE_OVERFLOW;
    }
#if LONG_MAX > UINT32_MAX
    if ((unsigned long) stats.data_size > UINT32_MAX) {
        free(payload);
        return N148I_ERROR_SIZE_OVERFLOW;
    }
#endif
    size_t table_size = (size_t) stats.table_size;
    size_t payload_size = (size_t) stats.data_size;
    if (table_size > SIZE_MAX - N148I_HEADER_SIZE ||
        payload_size > SIZE_MAX - N148I_HEADER_SIZE - table_size) {
        free(payload);
        return N148I_ERROR_SIZE_OVERFLOW;
    }
    size_t complete_size = N148I_HEADER_SIZE + table_size + payload_size;
    uint8_t *complete = (uint8_t *) malloc(complete_size);
    if (!complete) {
        free(payload);
        return N148I_ERROR_OUT_OF_MEMORY;
    }

    memcpy(complete, N148I_MAGIC, N148I_MAGIC_LEN);
    complete[5] = N148I_VERSION;
    memory_write_u32(complete + 6, image->width);
    memory_write_u32(complete + 10, image->height);
    complete[14] = (uint8_t) settings.quality;
    complete[15] = (uint8_t) settings.chroma;
    complete[16] = (uint8_t) settings.optimize_huffman;
    memory_write_u32(complete + 17, (uint32_t) stats.data_size);

    size_t offset = N148I_HEADER_SIZE;
    if (settings.optimize_huffman) {
        for (int table = 0; table < HUFFMAN_TABLE_COUNT; table++) {
            if (!huffman_spec_is_valid(&specs[table])) {
                free(payload);
                free(complete);
                return N148I_ERROR_ENCODE_FAILED;
            }
            for (int length = 1; length <= 16; length++)
                complete[offset++] = (uint8_t) specs[table].bits[length];
            memcpy(complete + offset, specs[table].values,
                   (size_t) specs[table].value_count);
            offset += (size_t) specs[table].value_count;
        }
    }
    if (offset != N148I_HEADER_SIZE + table_size) {
        free(payload);
        free(complete);
        return N148I_ERROR_ENCODE_FAILED;
    }
    memcpy(complete + offset, payload, payload_size);
    free(payload);

    *encoded = complete;
    *encoded_size = complete_size;
    return N148I_OK;
}

n148i_result_t n148i_decode_memory(const uint8_t *encoded,
                                   size_t encoded_size,
                                   n148i_image_t *image) {
    if (!image) return N148I_ERROR_INVALID_ARGUMENT;
    ParsedHeader parsed;
    n148i_result_t result = parse_header(encoded, encoded_size, &parsed);
    if (result != N148I_OK) return result;

    size_t width = parsed.width;
    size_t height = parsed.height;
    if (multiplication_overflows(width, 3) ||
        multiplication_overflows(width * 3, height) ||
        multiplication_overflows(width, height)) {
        return N148I_ERROR_SIZE_OVERFLOW;
    }
    size_t pixel_count = width * height;
#if LONG_MAX < SIZE_MAX
    if (pixel_count > (size_t) LONG_MAX)
        return N148I_ERROR_SIZE_OVERFLOW;
#endif

    Plane y = {0}, cb = {0}, cr = {0};
    DecodeStats stats;
    Image decoded = {0};
    int ok = decode_image((uint8_t *) encoded + parsed.payload_offset,
                          (long) parsed.payload_size,
                          (int) parsed.width, (int) parsed.height,
                          parsed.quality, parsed.chroma, parsed.specs,
                          &y, &cb, &cr, &stats);
    if (ok && stats.bytes_consumed != (long) parsed.payload_size)
        ok = 0;
    if (ok) ok = merge_channels(&y, &cb, &cr, 1, &decoded);
    free_plane(&y);
    free_plane(&cb);
    free_plane(&cr);
    if (!ok) {
        free_image(&decoded);
        return N148I_ERROR_DECODE_FAILED;
    }
    if (decoded.width != (int) parsed.width ||
        decoded.height != (int) parsed.height || !decoded.pixels) {
        free_image(&decoded);
        return N148I_ERROR_CORRUPT_DATA;
    }

    image->pixels = decoded.pixels;
    image->width = parsed.width;
    image->height = parsed.height;
    image->stride = width * 3;
    return N148I_OK;
}

n148i_result_t n148i_read_header(const uint8_t *encoded,
                                 size_t encoded_size,
                                 n148i_image_info_t *info) {
    if (!info) return N148I_ERROR_INVALID_ARGUMENT;
    ParsedHeader parsed;
    n148i_result_t result = parse_header(encoded, encoded_size, &parsed);
    if (result != N148I_OK) return result;

    info->width = parsed.width;
    info->height = parsed.height;
    info->payload_size = parsed.payload_size;
    info->encoded_header_size = parsed.payload_offset;
    info->format_version = parsed.version;
    info->quality = parsed.quality;
    info->chroma = (n148i_chroma_t) parsed.chroma;
    info->optimized_huffman = parsed.optimized;
    return N148I_OK;
}

void n148i_free_buffer(void *buffer) {
    free(buffer);
}

void n148i_free_image(n148i_image_t *image) {
    if (!image) return;
    free(image->pixels);
    image->pixels = NULL;
    image->width = 0;
    image->height = 0;
    image->stride = 0;
}

const char *n148i_result_string(n148i_result_t result) {
    switch (result) {
        case N148I_OK: return "success";
        case N148I_ERROR_INVALID_ARGUMENT: return "invalid argument";
        case N148I_ERROR_OUT_OF_MEMORY: return "out of memory";
        case N148I_ERROR_INVALID_FORMAT: return "invalid N.148i format";
        case N148I_ERROR_UNSUPPORTED_VERSION: return "unsupported format version";
        case N148I_ERROR_TRUNCATED_DATA: return "truncated data";
        case N148I_ERROR_CORRUPT_DATA: return "corrupt data";
        case N148I_ERROR_SIZE_OVERFLOW: return "image or buffer is too large";
        case N148I_ERROR_ENCODE_FAILED: return "encoding failed";
        case N148I_ERROR_DECODE_FAILED: return "decoding failed";
        case N148I_ERROR_UNSUPPORTED_SIMD: return "SIMD level is not supported";
        default: return "unknown N.148i error";
    }
}

const char *n148i_library_version(void) {
    return N148I_VERSION_STRING;
}

uint32_t n148i_format_version(void) {
    return N148I_FORMAT_VERSION;
}

n148i_simd_level_t n148i_simd_level(void) {
    return (n148i_simd_level_t) n148_cpu_level();
}

const char *n148i_simd_name(n148i_simd_level_t level) {
    switch (level) {
        case N148I_SIMD_AUTO: return "automatic";
        case N148I_SIMD_SCALAR: return "scalar";
        case N148I_SIMD_SSE2: return "SSE2";
        case N148I_SIMD_AVX2: return "AVX2";
        case N148I_SIMD_AVX2_FMA: return "AVX2+FMA";
        default: return "unknown";
    }
}

n148i_result_t n148i_simd_force(n148i_simd_level_t level) {
    if (level == N148I_SIMD_AUTO) {
        n148_cpu_force(-1);
        return N148I_OK;
    }
    if (level < N148I_SIMD_SCALAR || level > N148I_SIMD_AVX2_FMA)
        return N148I_ERROR_INVALID_ARGUMENT;
    if ((int) level > n148_cpu_detected_level())
        return N148I_ERROR_UNSUPPORTED_SIMD;
    n148_cpu_force((int) level);
    return N148I_OK;
}

Na V2, ele ficou com 993 linhas:

/*
 * N.148i public memory-to-memory API
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#include "n148i.h"

#include <float.h>
#include <limits.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#include "cpu.h"
#include "decoder.h"
#include "encoder.h"
#include "header.h"
#include "huffman.h"
#include "parallel.h"
#include "ppm.h"
#include "tables.h"
#include "entropy_payload.h"
#include "predictive_codec.h"
#include "chroma_profile.h"
#include "luma_profile.h"
#include "fidelity_profile.h"
#include "entropy_profile.h" /* explicit detail-profile marker */
#include "directional_intra.h"

typedef struct {
    uint32_t width;
    uint32_t height;
    uint32_t payload_size;
    size_t payload_offset;
    size_t metadata_offset;
    uint32_t metadata_size;
    uint32_t feature_flags;
    uint8_t version;
    uint8_t quality;
    uint8_t chroma_quality;
    uint8_t chroma;
    uint8_t optimized;
    uint8_t effort;
    HuffSpec specs[HUFFMAN_TABLE_COUNT];
} ParsedHeader;

static void memory_write_u16(uint8_t *destination, uint16_t value) {
    destination[0] = (uint8_t) value;
    destination[1] = (uint8_t) (value >> 8);
}

static void memory_write_u32(uint8_t *destination, uint32_t value) {
    destination[0] = (uint8_t) (value & 0xffu);
    destination[1] = (uint8_t) ((value >> 8) & 0xffu);
    destination[2] = (uint8_t) ((value >> 16) & 0xffu);
    destination[3] = (uint8_t) ((value >> 24) & 0xffu);
}

static uint32_t memory_read_u32(const uint8_t *source) {
    return (uint32_t) source[0] |
        ((uint32_t) source[1] << 8) |
        ((uint32_t) source[2] << 16) |
        ((uint32_t) source[3] << 24);
}

static uint16_t memory_read_u16(const uint8_t *source) {
    return (uint16_t)(source[0] | ((uint16_t) source[1] << 8));
}

static int valid_stored_chroma(int chroma) {
    return chroma == CHROMA_444 || chroma == CHROMA_422 ||
        chroma == CHROMA_420;
}

static int valid_encoder_chroma(int chroma) {
    return valid_stored_chroma(chroma) || chroma == N148I_CHROMA_AUTO;
}

static int multiplication_overflows(size_t first, size_t second) {
    return second != 0 && first > SIZE_MAX / second;
}

static int effective_chroma_quality(
    const n148i_encode_options_t *settings) {
    if (!(settings->feature_flags &
          N148_FEATURE_CALIBRATED_CHROMA_QUANT))
        return settings->quality;
    if (settings->chroma_quality)
        return settings->chroma_quality;
    if (settings->format_version == N148I_FORMAT_VERSION_7 &&
        (settings->feature_flags & N148I_FORMAT_7_STRUCTURAL_LUMA_QUANT))
        return settings->quality;
    return settings->quality > 95 ? 100 : settings->quality + 5;
}

static n148i_result_t parse_header(const uint8_t *encoded,
                                   size_t encoded_size,
                                   ParsedHeader *parsed) {
    if (!encoded || !parsed) return N148I_ERROR_INVALID_ARGUMENT;
    if (encoded_size < N148I_MAGIC_LEN + 1u)
        return N148I_ERROR_TRUNCATED_DATA;
    if (memcmp(encoded, N148I_MAGIC, N148I_MAGIC_LEN) != 0)
        return N148I_ERROR_INVALID_FORMAT;

    memset(parsed, 0, sizeof(*parsed));
    parsed->version = encoded[5];
    if (parsed->version != N148I_FORMAT_VERSION_1 &&
        parsed->version != N148I_FORMAT_VERSION_2 &&
        parsed->version != N148I_FORMAT_VERSION_3 &&
        parsed->version != N148I_FORMAT_VERSION_4 &&
        parsed->version != N148I_FORMAT_VERSION_5 &&
        parsed->version != N148I_FORMAT_VERSION_6 &&
        parsed->version != N148I_FORMAT_VERSION_7)
        return N148I_ERROR_UNSUPPORTED_VERSION;

    if (parsed->version == N148I_FORMAT_VERSION_2 ||
        parsed->version == N148I_FORMAT_VERSION_3 ||
        parsed->version == N148I_FORMAT_VERSION_4 ||
        parsed->version == N148I_FORMAT_VERSION_5 ||
        parsed->version == N148I_FORMAT_VERSION_6 ||
        parsed->version == N148I_FORMAT_VERSION_7) {
        if (encoded_size < N148_EXTENDED_HEADER_SIZE)
            return N148I_ERROR_TRUNCATED_DATA;
        uint16_t header_size = memory_read_u16(encoded + 6);
        parsed->width = memory_read_u32(encoded + 8);
        parsed->height = memory_read_u32(encoded + 12);
        parsed->payload_size = memory_read_u32(encoded + 16);
        parsed->feature_flags = memory_read_u32(encoded + 20);
        parsed->quality = encoded[24];
        parsed->chroma = encoded[25];
        parsed->effort = encoded[26];
        parsed->chroma_quality = encoded[27];
        parsed->metadata_size = memory_read_u32(encoded + 28);
        int unsupported_features = parsed->version == N148I_FORMAT_VERSION_2 ?
            (parsed->feature_flags & ~N148_FORMAT_2_SUPPORTED_FEATURES) != 0 :
            parsed->version == N148I_FORMAT_VERSION_3 ?
            (parsed->feature_flags & ~N148_FORMAT_3_SUPPORTED_FEATURES) != 0 :
            parsed->version == N148I_FORMAT_VERSION_4 ?
            (parsed->feature_flags & ~N148_FORMAT_4_SUPPORTED_FEATURES) != 0 :
            parsed->version == N148I_FORMAT_VERSION_5 ?
            (parsed->feature_flags & ~N148_FORMAT_5_SUPPORTED_FEATURES) != 0 :
            parsed->version == N148I_FORMAT_VERSION_6 ?
            (parsed->feature_flags & ~N148_FORMAT_6_SUPPORTED_FEATURES) != 0 :
            (parsed->feature_flags & ~N148_FORMAT_7_SUPPORTED_FEATURES) != 0;
        int valid_features = parsed->version == N148I_FORMAT_VERSION_2 ?
            !unsupported_features &&
            !((parsed->feature_flags &
               (N148_FEATURE_CONTEXT | N148_FEATURE_INTRA |
                N148_FEATURE_PERCEPTUAL_COLOR |
                N148_FEATURE_ADAPTIVE_QUANT |
                N148_FEATURE_VARIABLE_TRANSFORM |
                N148_FEATURE_RDO | N148_FEATURE_LOOP_FILTER)) &&
              !(parsed->feature_flags & N148_FEATURE_RANS)) &&
            !((parsed->feature_flags & N148_FEATURE_ADAPTIVE_QUANT) &&
              !(parsed->feature_flags & N148_FEATURE_INTRA)) &&
            !((parsed->feature_flags & N148_FEATURE_VARIABLE_TRANSFORM) &&
              !(parsed->feature_flags & N148_FEATURE_INTRA)) &&
            !((parsed->feature_flags & N148_FEATURE_RDO) &&
              !(parsed->feature_flags & N148_FEATURE_INTRA)) &&
            !((parsed->feature_flags & N148_FEATURE_LOOP_FILTER) &&
              !(parsed->feature_flags & N148_FEATURE_INTRA)) :
            parsed->version == N148I_FORMAT_VERSION_3 ?
            n148_format_3_features_valid(parsed->feature_flags) :
            parsed->version == N148I_FORMAT_VERSION_4 ?
            n148_format_4_features_valid(parsed->feature_flags) :
            parsed->version == N148I_FORMAT_VERSION_5 ?
            n148_format_5_features_valid(parsed->feature_flags) :
            parsed->version == N148I_FORMAT_VERSION_6 ?
            n148_format_6_features_valid(parsed->feature_flags) :
            n148_format_7_features_valid(parsed->feature_flags);
        if (parsed->width == 0 || parsed->width > INT_MAX ||
            parsed->height == 0 || parsed->height > INT_MAX ||
            parsed->payload_size == 0 || parsed->metadata_size == 0 ||
            parsed->quality < 1 || parsed->quality > 100 ||
            !valid_stored_chroma(parsed->chroma) || parsed->effort > 9 ||
            ((parsed->version == N148I_FORMAT_VERSION_4 ||
              parsed->version == N148I_FORMAT_VERSION_5 ||
              parsed->version == N148I_FORMAT_VERSION_6 ||
              parsed->version == N148I_FORMAT_VERSION_7) &&
             (parsed->feature_flags &
              N148_FEATURE_RECONSTRUCTION_AWARE_CHROMA) &&
             parsed->chroma == CHROMA_444) ||
            (((parsed->version == N148I_FORMAT_VERSION_4 ||
               parsed->version == N148I_FORMAT_VERSION_5 ||
               parsed->version == N148I_FORMAT_VERSION_6 ||
               parsed->version == N148I_FORMAT_VERSION_7) &&
              (parsed->feature_flags &
               N148_FEATURE_CALIBRATED_CHROMA_QUANT)) ?
                (parsed->chroma_quality < 1 ||
                 parsed->chroma_quality > 100) :
                parsed->chroma_quality != 0) ||
            !valid_features) {
            return unsupported_features ?
                N148I_ERROR_UNSUPPORTED_FEATURE : N148I_ERROR_INVALID_FORMAT;
        }
        if (parsed->metadata_size > UINT16_MAX - N148_EXTENDED_HEADER_SIZE ||
            header_size != N148_EXTENDED_HEADER_SIZE + parsed->metadata_size)
            return N148I_ERROR_INVALID_FORMAT;
        if (header_size > encoded_size ||
            parsed->payload_size > encoded_size - header_size)
            return N148I_ERROR_TRUNCATED_DATA;
        if (parsed->payload_size != encoded_size - header_size)
            return N148I_ERROR_CORRUPT_DATA;
        parsed->metadata_offset = N148_EXTENDED_HEADER_SIZE;
        parsed->payload_offset = header_size;
        if (parsed->chroma_quality == 0)
            parsed->chroma_quality = parsed->quality;
        return N148I_OK;
    }

    if (encoded_size < N148_FORMAT_1_HEADER_SIZE)
        return N148I_ERROR_TRUNCATED_DATA;

    parsed->width = memory_read_u32(encoded + 6);
    parsed->height = memory_read_u32(encoded + 10);
    parsed->quality = encoded[14];
    parsed->chroma_quality = parsed->quality;
    parsed->chroma = encoded[15];
    parsed->optimized = encoded[16];
    parsed->payload_size = memory_read_u32(encoded + 17);

    if (parsed->width == 0 || parsed->width > INT_MAX ||
        parsed->height == 0 || parsed->height > INT_MAX ||
        parsed->quality < 1 || parsed->quality > 100 ||
        !valid_stored_chroma(parsed->chroma) || parsed->optimized > 1 ||
        parsed->payload_size == 0) {
        return N148I_ERROR_INVALID_FORMAT;
    }
#if LONG_MAX < UINT32_MAX
    if (parsed->payload_size > (uint32_t) LONG_MAX)
        return N148I_ERROR_SIZE_OVERFLOW;
#endif

    size_t offset = N148_FORMAT_1_HEADER_SIZE;
    if (parsed->optimized) {
        for (int table = 0; table < HUFFMAN_TABLE_COUNT; table++) {
            HuffSpec *spec = &parsed->specs[table];
            if (encoded_size - offset < 16)
                return N148I_ERROR_TRUNCATED_DATA;
            for (int length = 1; length <= 16; length++) {
                int count = encoded[offset++];
                spec->bits[length] = count;
                spec->value_count += count;
                if (spec->value_count > HUFFMAN_MAX_SYMBOLS)
                    return N148I_ERROR_CORRUPT_DATA;
            }
            if (spec->value_count == 0)
                return N148I_ERROR_CORRUPT_DATA;
            if ((size_t) spec->value_count > encoded_size - offset)
                return N148I_ERROR_TRUNCATED_DATA;
            memcpy(spec->values, encoded + offset,
                   (size_t) spec->value_count);
            offset += (size_t) spec->value_count;
            if (!huffman_spec_is_valid(spec))
                return N148I_ERROR_CORRUPT_DATA;
        }
    } else {
        huffman_default_specs(parsed->specs);
    }

    if ((size_t) parsed->payload_size > encoded_size - offset)
        return N148I_ERROR_TRUNCATED_DATA;
    if ((size_t) parsed->payload_size != encoded_size - offset)
        return N148I_ERROR_CORRUPT_DATA;
    parsed->payload_offset = offset;
    parsed->metadata_offset = N148_FORMAT_1_HEADER_SIZE;
    parsed->metadata_size = (uint32_t)(offset - N148_FORMAT_1_HEADER_SIZE);
    return N148I_OK;
}

static n148i_result_t normalize_options(
    const n148i_encode_options_t *input,
    n148i_encode_options_t *output) {
    n148i_encode_options_init(output);
    if (!input) return N148I_OK;

    if (input->struct_size <
        offsetof(n148i_encode_options_t, quality) + sizeof(input->quality)) {
        return N148I_ERROR_INVALID_ARGUMENT;
    }
    size_t copy_size = input->struct_size;
    if (copy_size > sizeof(*output)) copy_size = sizeof(*output);
    memcpy(output, input, copy_size);
    output->struct_size = sizeof(*output);

    if (output->quality < 1 || output->quality > 100 ||
        !valid_encoder_chroma(output->chroma) ||
        (output->optimize_huffman != 0 && output->optimize_huffman != 1) ||
        output->thread_count < 0 || output->thread_count > N148I_MAX_THREADS ||
        (output->format_version != N148I_FORMAT_VERSION_1 &&
         output->format_version != N148I_FORMAT_VERSION_2 &&
         output->format_version != N148I_FORMAT_VERSION_3 &&
         output->format_version != N148I_FORMAT_VERSION_4 &&
         output->format_version != N148I_FORMAT_VERSION_5 &&
         output->format_version != N148I_FORMAT_VERSION_6 &&
         output->format_version != N148I_FORMAT_VERSION_7) ||
        output->effort < 0 || output->effort > 9 ||
        output->chroma_quality < 0 || output->chroma_quality > 100) {
        return N148I_ERROR_INVALID_ARGUMENT;
    }
    if (output->chroma == N148I_CHROMA_AUTO &&
        output->format_version != N148I_FORMAT_VERSION_5 &&
        output->format_version != N148I_FORMAT_VERSION_6 &&
        output->format_version != N148I_FORMAT_VERSION_7)
        return N148I_ERROR_INVALID_ARGUMENT;
    if (output->format_version != N148I_FORMAT_VERSION_4 &&
        output->format_version != N148I_FORMAT_VERSION_5 &&
        output->format_version != N148I_FORMAT_VERSION_6 &&
        output->format_version != N148I_FORMAT_VERSION_7 &&
        output->chroma_quality != 0)
        return N148I_ERROR_INVALID_ARGUMENT;
    if (output->format_version == N148I_FORMAT_VERSION_2) {
        if (output->feature_flags & ~N148_FORMAT_2_SUPPORTED_FEATURES)
            return N148I_ERROR_UNSUPPORTED_FEATURE;
        if ((output->feature_flags &
             (N148_FEATURE_CONTEXT | N148_FEATURE_INTRA |
              N148_FEATURE_PERCEPTUAL_COLOR |
              N148_FEATURE_ADAPTIVE_QUANT |
              N148_FEATURE_VARIABLE_TRANSFORM |
              N148_FEATURE_RDO |
              N148_FEATURE_LOOP_FILTER)) &&
            !(output->feature_flags & N148_FEATURE_RANS))
            return N148I_ERROR_INVALID_ARGUMENT;
        if ((output->feature_flags & N148_FEATURE_ADAPTIVE_QUANT) &&
            !(output->feature_flags & N148_FEATURE_INTRA))
            return N148I_ERROR_INVALID_ARGUMENT;
        if ((output->feature_flags & N148_FEATURE_VARIABLE_TRANSFORM) &&
            !(output->feature_flags & N148_FEATURE_INTRA))
            return N148I_ERROR_INVALID_ARGUMENT;
        if ((output->feature_flags & N148_FEATURE_RDO) &&
            !(output->feature_flags & N148_FEATURE_INTRA))
            return N148I_ERROR_INVALID_ARGUMENT;
        if ((output->feature_flags & N148_FEATURE_LOOP_FILTER) &&
            !(output->feature_flags & N148_FEATURE_INTRA))
            return N148I_ERROR_INVALID_ARGUMENT;
    } else if (output->format_version == N148I_FORMAT_VERSION_3) {
        if (output->feature_flags & ~N148_FORMAT_3_SUPPORTED_FEATURES)
            return N148I_ERROR_UNSUPPORTED_FEATURE;
        if (!n148_format_3_features_valid(output->feature_flags))
            return N148I_ERROR_INVALID_ARGUMENT;
    } else if (output->format_version == N148I_FORMAT_VERSION_4) {
        if (output->feature_flags & ~N148_FORMAT_4_SUPPORTED_FEATURES)
            return N148I_ERROR_UNSUPPORTED_FEATURE;
        if (!n148_format_4_features_valid(output->feature_flags) ||
            (output->chroma_quality != 0 &&
             !(output->feature_flags &
               N148_FEATURE_CALIBRATED_CHROMA_QUANT)))
            return N148I_ERROR_INVALID_ARGUMENT;
        /* There is no reduction to optimize in 4:4:4. Canonicalize the
           encoder request instead of rejecting the otherwise valid default
           profile or writing a meaningless feature bit into the stream. */
        if (output->chroma == N148I_CHROMA_444)
            output->feature_flags &=
                ~N148_FEATURE_RECONSTRUCTION_AWARE_CHROMA;
    } else if (output->format_version == N148I_FORMAT_VERSION_5) {
        if (output->feature_flags & ~N148_FORMAT_5_SUPPORTED_FEATURES)
            return N148I_ERROR_UNSUPPORTED_FEATURE;
        if (!n148_format_5_features_valid(output->feature_flags) ||
            (output->chroma_quality != 0 &&
             !(output->feature_flags &
               N148_FEATURE_CALIBRATED_CHROMA_QUANT)))
            return N148I_ERROR_INVALID_ARGUMENT;
        if (output->chroma == N148I_CHROMA_444)
            output->feature_flags &=
                ~N148_FEATURE_RECONSTRUCTION_AWARE_CHROMA;
    } else if (output->format_version == N148I_FORMAT_VERSION_6) {
        if (output->feature_flags & ~N148_FORMAT_6_SUPPORTED_FEATURES)
            return N148I_ERROR_UNSUPPORTED_FEATURE;
        if (!n148_format_6_features_valid(output->feature_flags) ||
            (output->chroma_quality != 0 &&
             !(output->feature_flags &
               N148_FEATURE_CALIBRATED_CHROMA_QUANT)))
            return N148I_ERROR_INVALID_ARGUMENT;
        if (output->chroma == N148I_CHROMA_444)
            output->feature_flags &=
                ~N148_FEATURE_RECONSTRUCTION_AWARE_CHROMA;
    } else if (output->format_version == N148I_FORMAT_VERSION_7) {
        /* These public placeholders never had an implementation. Preserve
           their rejection class after assigning bit 30 to a different profile. */
        if (output->feature_flags == N148I_PROFILE_DIRECTIONAL_SCAN ||
            output->feature_flags == N148I_PROFILE_DIRECTIONAL_TRANSFORM)
            return N148I_ERROR_UNSUPPORTED_FEATURE;
        if (output->feature_flags & ~N148_FORMAT_7_SUPPORTED_FEATURES)
            return N148I_ERROR_UNSUPPORTED_FEATURE;
        if (!n148_format_7_features_valid(output->feature_flags) ||
            (output->chroma_quality != 0 &&
             !(output->feature_flags &
               N148_FEATURE_CALIBRATED_CHROMA_QUANT)))
            return N148I_ERROR_INVALID_ARGUMENT;
        if (output->chroma == N148I_CHROMA_444)
            output->feature_flags &=
                ~N148_FEATURE_RECONSTRUCTION_AWARE_CHROMA;
    }
    return N148I_OK;
}

void n148i_encode_options_init(n148i_encode_options_t *options) {
    if (!options) return;
    memset(options, 0, sizeof(*options));
    options->struct_size = sizeof(*options);
    options->quality = 50;
    options->chroma = N148I_CHROMA_420;
    options->optimize_huffman = 1;
    options->thread_count = 0;
    options->format_version = N148I_FORMAT_VERSION_7;
    options->feature_flags = N148I_DEFAULT_FEATURES;
    options->effort = 3;
    options->chroma_quality = 0;
}

static n148i_result_t encode_modern_complete(
    const n148i_image_t *image, const n148i_encode_options_t *settings,
    Plane *y, Plane *cb, Plane *cr,
    uint8_t **encoded, size_t *encoded_size) {
    N148EncodedPayload sections = {0};
    int ok;
    if (settings->format_version == N148I_FORMAT_VERSION_7) {
        int chroma_quality = effective_chroma_quality(settings);
        if (settings->feature_flags & N148I_FORMAT_7_STRUCTURAL_LUMA_QUANT)
            n148_fidelity_rgb_reference(image->pixels,
                                        image->stride ? image->stride :
                                            (size_t)image->width * 3,
                                        (int)image->width, (int)image->height);
        ok = n148_encode_format_7(y, cb, cr, settings->quality, chroma_quality,
                            settings->feature_flags, settings->effort,
                            &sections);
        n148_fidelity_rgb_reference(NULL, 0, 0, 0);
    } else if (settings->format_version == N148I_FORMAT_VERSION_6) {
        int chroma_quality = effective_chroma_quality(settings);
        ok = n148_encode_format_6(y, cb, cr, settings->quality, chroma_quality,
                            settings->feature_flags, settings->effort,
                            &sections);
    } else if (settings->format_version == N148I_FORMAT_VERSION_5) {
        int chroma_quality = effective_chroma_quality(settings);
        ok = n148_encode_format_5(y, cb, cr, settings->quality, chroma_quality,
                            settings->feature_flags, settings->effort,
                            &sections);
    } else if (settings->format_version == N148I_FORMAT_VERSION_4) {
        int chroma_quality = effective_chroma_quality(settings);
        ok = n148_encode_format_4(y, cb, cr, settings->quality, chroma_quality,
                            settings->feature_flags, settings->effort,
                            &sections);
    } else if (settings->format_version == N148I_FORMAT_VERSION_3) {
        ok = n148_encode_format_3(y, cb, cr, settings->quality,
                            settings->feature_flags, settings->effort,
                            &sections);
    } else {
        ok = n148_encode_format_2(y, cb, cr, settings->quality,
                            settings->feature_flags, settings->effort,
                            &sections);
    }
    if (!ok) {
        return N148I_ERROR_ENCODE_FAILED;
    }
    if (sections.metadata_size > UINT16_MAX - N148_EXTENDED_HEADER_SIZE ||
        sections.metadata_size > UINT32_MAX ||
        sections.payload_size == 0 || sections.payload_size > UINT32_MAX ||
        sections.metadata_size > SIZE_MAX - N148_EXTENDED_HEADER_SIZE ||
        sections.payload_size > SIZE_MAX - N148_EXTENDED_HEADER_SIZE -
            sections.metadata_size) {
        n148_encoded_payload_release(&sections);
        return N148I_ERROR_SIZE_OVERFLOW;
    }

    size_t header_size = N148_EXTENDED_HEADER_SIZE + sections.metadata_size;
    size_t complete_size = header_size + sections.payload_size;
    uint8_t *complete = (uint8_t *) malloc(complete_size);
    if (!complete) {
        n148_encoded_payload_release(&sections);
        return N148I_ERROR_OUT_OF_MEMORY;
    }
    memcpy(complete, N148I_MAGIC, N148I_MAGIC_LEN);
    complete[5] = (uint8_t) settings->format_version;
    memory_write_u16(complete + 6, (uint16_t) header_size);
    memory_write_u32(complete + 8, image->width);
    memory_write_u32(complete + 12, image->height);
    memory_write_u32(complete + 16, (uint32_t) sections.payload_size);
    memory_write_u32(complete + 20, settings->feature_flags);
    complete[24] = (uint8_t) settings->quality;
    complete[25] = (uint8_t) settings->chroma;
    complete[26] = (uint8_t) settings->effort;
    complete[27] = (settings->format_version == N148I_FORMAT_VERSION_4 ||
                    settings->format_version == N148I_FORMAT_VERSION_5 ||
                    settings->format_version == N148I_FORMAT_VERSION_6 ||
                    settings->format_version == N148I_FORMAT_VERSION_7) &&
        (settings->feature_flags &
         N148_FEATURE_CALIBRATED_CHROMA_QUANT) ?
        (uint8_t) effective_chroma_quality(settings) : 0;
    memory_write_u32(complete + 28, (uint32_t) sections.metadata_size);
    memcpy(complete + N148_EXTENDED_HEADER_SIZE,
           sections.metadata, sections.metadata_size);
    memcpy(complete + header_size, sections.payload, sections.payload_size);
    n148_encoded_payload_release(&sections);
    *encoded = complete;
    *encoded_size = complete_size;
    return N148I_OK;
}

static n148i_result_t encode_chroma_layout(
    Image *source, const n148i_image_t *public_image,
    const n148i_encode_options_t *settings, n148i_chroma_t chroma,
    uint8_t **encoded, size_t *encoded_size) {
    n148i_encode_options_t concrete = *settings;
    concrete.chroma = chroma;
    if (chroma == N148I_CHROMA_444)
        concrete.feature_flags &=
            ~N148_FEATURE_RECONSTRUCTION_AWARE_CHROMA;
    int reconstruction_aware =
        (concrete.feature_flags &
         N148I_FEATURE_RECONSTRUCTION_AWARE_CHROMA) != 0;
    Plane y = {0}, cb = {0}, cr = {0};
    int ok = n148_split_channels_reconstruction_aware(
        source, &y, &cb, &cr, chroma, reconstruction_aware);
    n148i_result_t result = N148I_ERROR_ENCODE_FAILED;
    if (ok)
        result = encode_modern_complete(
            public_image, &concrete, &y, &cb, &cr, encoded, encoded_size);
    free_plane(&y);
    free_plane(&cb);
    free_plane(&cr);
    return result;
}

/* The image-level objective is the same SSE + lambda * bits form used by the
   block RDO. RGB SSE is divided by three to keep it on a one-plane scale;
   multiplying the complete expression by 300 avoids a division here. */
static long double automatic_chroma_cost(
    const Image *source, const n148i_image_t *decoded, size_t encoded_size,
    const n148i_encode_options_t *settings) {
    if (!source || !source->pixels || !decoded || !decoded->pixels ||
        decoded->width != (uint32_t) source->width ||
        decoded->height != (uint32_t) source->height)
        return LDBL_MAX;
    long double squared_error = 0.0L;
    size_t value_count = (size_t) source->width * source->height * 3u;
    for (size_t index = 0; index < value_count; index++) {
        int difference =
            (int) source->pixels[index] - (int) decoded->pixels[index];
        squared_error += (long double) difference * difference;
    }
    int quant[8][8];
    const int (*base)[8] =
        !(settings->feature_flags & N148I_FEATURE_CALIBRATED_LUMA_QUANT) ?
        Q_LUMA_BASE :
        (settings->format_version == N148I_FORMAT_VERSION_7 &&
         (settings->feature_flags & N148I_FORMAT_7_BALANCED_RECONSTRUCTION)) ?
        N148_BALANCED_LUMA_QUANT_BASE :
        (settings->format_version == N148I_FORMAT_VERSION_7 &&
         (settings->feature_flags & N148I_FORMAT_7_STRUCTURAL_LUMA_QUANT)) ?
        N148_STRUCTURAL_LUMA_QUANT_BASE :
        (settings->format_version == N148I_FORMAT_VERSION_7 &&
         (settings->feature_flags &
          N148I_FORMAT_7_REFINED_SPECTRAL_LUMA_QUANT)) ?
        N148_REFINED_SPECTRAL_LUMA_QUANT_BASE :
        (settings->format_version == N148I_FORMAT_VERSION_7 &&
         (settings->feature_flags & N148I_FORMAT_7_SPECTRAL_LUMA_QUANT)) ?
        N148_SPECTRAL_LUMA_QUANT_BASE : FORMAT_5_LUMA_QUANT_BASE;
    scale_table(base, settings->quality, quant);
    long double step = quant[0][0];
    long double bits = (long double) encoded_size * 8.0L;
    return 100.0L * squared_error + 255.0L * step * step * bits;
}

static n148i_result_t encode_automatic_chroma(
    Image *source, const n148i_image_t *public_image,
    const n148i_encode_options_t *settings,
    uint8_t **encoded, size_t *encoded_size) {
    if (settings->effort == 0)
        return encode_chroma_layout(
            source, public_image, settings, N148I_CHROMA_420,
            encoded, encoded_size);

    static const n148i_chroma_t layouts[] = {
        N148I_CHROMA_420, N148I_CHROMA_422, N148I_CHROMA_444,
    };
    uint8_t *best = NULL;
    size_t best_size = 0;
    long double best_cost = LDBL_MAX;
    for (size_t index = 0; index < sizeof(layouts) / sizeof(layouts[0]);
         index++) {
        uint8_t *candidate = NULL;
        size_t candidate_size = 0;
        n148i_result_t result = encode_chroma_layout(
            source, public_image, settings, layouts[index],
            &candidate, &candidate_size);
        if (result != N148I_OK) {
            free(best);
            return result;
        }
        n148i_image_t decoded = {0};
        result = n148i_decode_memory(candidate, candidate_size, &decoded);
        if (result != N148I_OK) {
            free(candidate);
            free(best);
            return result;
        }
        long double cost = automatic_chroma_cost(
            source, &decoded, candidate_size, settings);
        n148i_free_image(&decoded);
        if (!best || cost < best_cost ||
            (cost == best_cost && candidate_size < best_size)) {
            free(best);
            best = candidate;
            best_size = candidate_size;
            best_cost = cost;
        } else {
            free(candidate);
        }
    }
    if (!best) return N148I_ERROR_ENCODE_FAILED;
    *encoded = best;
    *encoded_size = best_size;
    return N148I_OK;
}

n148i_result_t n148i_encode_memory(const n148i_image_t *image,
                                   const n148i_encode_options_t *options,
                                   uint8_t **encoded,
                                   size_t *encoded_size) {
    if (!image || !image->pixels || !encoded || !encoded_size ||
        image->width == 0 || image->width > INT_MAX ||
        image->height == 0 || image->height > INT_MAX) {
        return N148I_ERROR_INVALID_ARGUMENT;
    }
    *encoded = NULL;
    *encoded_size = 0;

    n148i_encode_options_t settings;
    n148i_result_t result = normalize_options(options, &settings);
    if (result != N148I_OK) return result;

    size_t width = image->width;
    size_t height = image->height;
    if (multiplication_overflows(width, 3))
        return N148I_ERROR_SIZE_OVERFLOW;
    size_t tight_stride = width * 3;
    size_t source_stride = image->stride ? image->stride : tight_stride;
    if (source_stride < tight_stride ||
        (height > 1 &&
         source_stride > (SIZE_MAX - tight_stride) / (height - 1)) ||
        multiplication_overflows(tight_stride, height) ||
        multiplication_overflows(width, height)) {
        return N148I_ERROR_SIZE_OVERFLOW;
    }
    size_t pixel_count = width * height;
#if LONG_MAX < SIZE_MAX
    if (pixel_count > (size_t) LONG_MAX)
        return N148I_ERROR_SIZE_OVERFLOW;
#endif

    uint8_t *compact = NULL;
    Image internal_image;
    internal_image.width = (int) image->width;
    internal_image.height = (int) image->height;
    internal_image.pixels = image->pixels;
    if (source_stride != tight_stride) {
        compact = (uint8_t *) malloc(tight_stride * height);
        if (!compact) return N148I_ERROR_OUT_OF_MEMORY;
        for (size_t row = 0; row < height; row++) {
            memcpy(compact + row * tight_stride,
                   image->pixels + row * source_stride, tight_stride);
        }
        internal_image.pixels = compact;
    }

    if (settings.thread_count > 0)
        n148_set_thread_count(settings.thread_count);

    if (settings.chroma == N148I_CHROMA_AUTO) {
        result = encode_automatic_chroma(
            &internal_image, image, &settings, encoded, encoded_size);
        free(compact);
        return result;
    }

    Plane y = {0}, cb = {0}, cr = {0};
    HuffSpec specs[HUFFMAN_TABLE_COUNT];
    EncodeStats stats;
    uint8_t *payload = NULL;
    int perceptual_color = settings.format_version == N148I_FORMAT_VERSION_2 &&
        (settings.feature_flags & N148I_FEATURE_PERCEPTUAL_COLOR) != 0;
    int reconstruction_aware =
        (settings.format_version == N148I_FORMAT_VERSION_4 ||
         settings.format_version == N148I_FORMAT_VERSION_5 ||
         settings.format_version == N148I_FORMAT_VERSION_6 ||
         settings.format_version == N148I_FORMAT_VERSION_7) &&
        (settings.feature_flags &
         N148I_FEATURE_RECONSTRUCTION_AWARE_CHROMA) != 0;
    int ok = (settings.format_version == N148I_FORMAT_VERSION_4 ||
              settings.format_version == N148I_FORMAT_VERSION_5 ||
              settings.format_version == N148I_FORMAT_VERSION_6 ||
              settings.format_version == N148I_FORMAT_VERSION_7) ?
        n148_split_channels_reconstruction_aware(&internal_image, &y, &cb, &cr,
                               settings.chroma, reconstruction_aware) :
        n148_split_channels_ex(&internal_image, &y, &cb, &cr,
                               settings.chroma, perceptual_color);
    free(compact);
    if (!ok) {
        free_plane(&y);
        free_plane(&cb);
        free_plane(&cr);
        return N148I_ERROR_ENCODE_FAILED;
    }
    if (settings.format_version == N148I_FORMAT_VERSION_2 ||
        settings.format_version == N148I_FORMAT_VERSION_3 ||
        settings.format_version == N148I_FORMAT_VERSION_4 ||
        settings.format_version == N148I_FORMAT_VERSION_5 ||
        settings.format_version == N148I_FORMAT_VERSION_6 ||
        settings.format_version == N148I_FORMAT_VERSION_7) {
        result = encode_modern_complete(image, &settings, &y, &cb, &cr,
                                        encoded, encoded_size);
        free_plane(&y);
        free_plane(&cb);
        free_plane(&cr);
        return result;
    }
    if (ok) {
        ok = encode_image(&y, &cb, &cr, settings.quality,
                          settings.optimize_huffman, specs, &payload, &stats);
    }
    free_plane(&y);
    free_plane(&cb);
    free_plane(&cr);
    if (!ok) {
        free(payload);
        return N148I_ERROR_ENCODE_FAILED;
    }

    if (stats.data_size <= 0 || stats.data_size > UINT32_MAX ||
        stats.table_size < 0) {
        free(payload);
        return N148I_ERROR_SIZE_OVERFLOW;
    }
#if LONG_MAX > UINT32_MAX
    if ((unsigned long) stats.data_size > UINT32_MAX) {
        free(payload);
        return N148I_ERROR_SIZE_OVERFLOW;
    }
#endif
    size_t table_size = (size_t) stats.table_size;
    size_t payload_size = (size_t) stats.data_size;
    if (table_size > SIZE_MAX - N148_FORMAT_1_HEADER_SIZE ||
        payload_size > SIZE_MAX - N148_FORMAT_1_HEADER_SIZE - table_size) {
        free(payload);
        return N148I_ERROR_SIZE_OVERFLOW;
    }
    size_t complete_size =
        N148_FORMAT_1_HEADER_SIZE + table_size + payload_size;
    uint8_t *complete = (uint8_t *) malloc(complete_size);
    if (!complete) {
        free(payload);
        return N148I_ERROR_OUT_OF_MEMORY;
    }

    memcpy(complete, N148I_MAGIC, N148I_MAGIC_LEN);
    complete[5] = N148_FORMAT_VERSION_1;
    memory_write_u32(complete + 6, image->width);
    memory_write_u32(complete + 10, image->height);
    complete[14] = (uint8_t) settings.quality;
    complete[15] = (uint8_t) settings.chroma;
    complete[16] = (uint8_t) settings.optimize_huffman;
    memory_write_u32(complete + 17, (uint32_t) stats.data_size);

    size_t offset = N148_FORMAT_1_HEADER_SIZE;
    if (settings.optimize_huffman) {
        for (int table = 0; table < HUFFMAN_TABLE_COUNT; table++) {
            if (!huffman_spec_is_valid(&specs[table])) {
                free(payload);
                free(complete);
                return N148I_ERROR_ENCODE_FAILED;
            }
            for (int length = 1; length <= 16; length++)
                complete[offset++] = (uint8_t) specs[table].bits[length];
            memcpy(complete + offset, specs[table].values,
                   (size_t) specs[table].value_count);
            offset += (size_t) specs[table].value_count;
        }
    }
    if (offset != N148_FORMAT_1_HEADER_SIZE + table_size) {
        free(payload);
        free(complete);
        return N148I_ERROR_ENCODE_FAILED;
    }
    memcpy(complete + offset, payload, payload_size);
    free(payload);

    *encoded = complete;
    *encoded_size = complete_size;
    return N148I_OK;
}

n148i_result_t n148i_decode_memory(const uint8_t *encoded,
                                   size_t encoded_size,
                                   n148i_image_t *image) {
    if (!image) return N148I_ERROR_INVALID_ARGUMENT;
    ParsedHeader parsed;
    n148i_result_t result = parse_header(encoded, encoded_size, &parsed);
    if (result != N148I_OK) return result;

    size_t width = parsed.width;
    size_t height = parsed.height;
    if (multiplication_overflows(width, 3) ||
        multiplication_overflows(width * 3, height) ||
        multiplication_overflows(width, height)) {
        return N148I_ERROR_SIZE_OVERFLOW;
    }
    size_t pixel_count = width * height;
#if LONG_MAX < SIZE_MAX
    if (pixel_count > (size_t) LONG_MAX)
        return N148I_ERROR_SIZE_OVERFLOW;
#endif

    Plane y = {0}, cb = {0}, cr = {0};
    DecodeStats stats;
    Image decoded = {0};
    int ok;
    if (parsed.version == N148I_FORMAT_VERSION_1) {
        ok = decode_image((uint8_t *) encoded + parsed.payload_offset,
                          (long) parsed.payload_size,
                          (int) parsed.width, (int) parsed.height,
                          parsed.quality, parsed.chroma, parsed.specs,
                          &y, &cb, &cr, &stats);
        if (ok && stats.bytes_consumed != (long) parsed.payload_size)
            ok = 0;
    } else if (parsed.version == N148I_FORMAT_VERSION_2) {
        ok = n148_decode_format_2(encoded + parsed.metadata_offset,
                            parsed.metadata_size,
                            encoded + parsed.payload_offset,
                            parsed.payload_size,
                            (int) parsed.width, (int) parsed.height,
                            parsed.quality, parsed.chroma,
                            parsed.feature_flags, &y, &cb, &cr);
    } else if (parsed.version == N148I_FORMAT_VERSION_3) {
        ok = n148_decode_format_3(encoded + parsed.metadata_offset,
                            parsed.metadata_size,
                            encoded + parsed.payload_offset,
                            parsed.payload_size,
                            (int) parsed.width, (int) parsed.height,
                            parsed.quality, parsed.chroma,
                            parsed.feature_flags, &y, &cb, &cr);
    } else if (parsed.version == N148I_FORMAT_VERSION_4) {
        ok = n148_decode_format_4(encoded + parsed.metadata_offset,
                            parsed.metadata_size,
                            encoded + parsed.payload_offset,
                            parsed.payload_size,
                            (int) parsed.width, (int) parsed.height,
                            parsed.quality, parsed.chroma_quality,
                            parsed.chroma,
                            parsed.feature_flags, &y, &cb, &cr);
    } else if (parsed.version == N148I_FORMAT_VERSION_5) {
        ok = n148_decode_format_5(encoded + parsed.metadata_offset,
                            parsed.metadata_size,
                            encoded + parsed.payload_offset,
                            parsed.payload_size,
                            (int) parsed.width, (int) parsed.height,
                            parsed.quality, parsed.chroma_quality,
                            parsed.chroma,
                            parsed.feature_flags, &y, &cb, &cr);
    } else if (parsed.version == N148I_FORMAT_VERSION_6) {
        ok = n148_decode_format_6(encoded + parsed.metadata_offset,
                            parsed.metadata_size,
                            encoded + parsed.payload_offset,
                            parsed.payload_size,
                            (int) parsed.width, (int) parsed.height,
                            parsed.quality, parsed.chroma_quality,
                            parsed.chroma,
                            parsed.feature_flags, &y, &cb, &cr);
    } else {
        ok = n148_decode_format_7(encoded + parsed.metadata_offset,
                            parsed.metadata_size,
                            encoded + parsed.payload_offset,
                            parsed.payload_size,
                            (int) parsed.width, (int) parsed.height,
                            parsed.quality, parsed.chroma_quality,
                            parsed.chroma,
                            parsed.feature_flags, &y, &cb, &cr);
    }
    int perceptual_color = parsed.version == N148I_FORMAT_VERSION_2 &&
        (parsed.feature_flags & N148I_FEATURE_PERCEPTUAL_COLOR) != 0;
    if (ok) ok = n148_merge_channels_ex(&y, &cb, &cr, 1,
                                         perceptual_color, &decoded);
    free_plane(&y);
    free_plane(&cb);
    free_plane(&cr);
    if (!ok) {
        free_image(&decoded);
        return N148I_ERROR_DECODE_FAILED;
    }
    if (decoded.width != (int) parsed.width ||
        decoded.height != (int) parsed.height || !decoded.pixels) {
        free_image(&decoded);
        return N148I_ERROR_CORRUPT_DATA;
    }

    image->pixels = decoded.pixels;
    image->width = parsed.width;
    image->height = parsed.height;
    image->stride = width * 3;
    return N148I_OK;
}

n148i_result_t n148i_read_header(const uint8_t *encoded,
                                 size_t encoded_size,
                                 n148i_image_info_t *info) {
    if (!info) return N148I_ERROR_INVALID_ARGUMENT;
    ParsedHeader parsed;
    n148i_result_t result = parse_header(encoded, encoded_size, &parsed);
    if (result != N148I_OK) return result;

    info->width = parsed.width;
    info->height = parsed.height;
    info->payload_size = parsed.payload_size;
    info->encoded_header_size = parsed.payload_offset;
    info->format_version = parsed.version;
    info->quality = parsed.quality;
    info->chroma_quality = parsed.chroma_quality;
    info->chroma = (n148i_chroma_t) parsed.chroma;
    info->optimized_huffman = parsed.optimized;
    info->feature_flags = parsed.feature_flags;
    info->effort = parsed.effort;
    info->metadata_size = parsed.metadata_size;
    return N148I_OK;
}

void n148i_free_buffer(void *buffer) {
    free(buffer);
}

void n148i_free_image(n148i_image_t *image) {
    if (!image) return;
    free(image->pixels);
    image->pixels = NULL;
    image->width = 0;
    image->height = 0;
    image->stride = 0;
}

const char *n148i_result_string(n148i_result_t result) {
    switch (result) {
        case N148I_OK: return "success";
        case N148I_ERROR_INVALID_ARGUMENT: return "invalid argument";
        case N148I_ERROR_OUT_OF_MEMORY: return "out of memory";
        case N148I_ERROR_INVALID_FORMAT: return "invalid N.148i format";
        case N148I_ERROR_UNSUPPORTED_VERSION: return "unsupported format version";
        case N148I_ERROR_TRUNCATED_DATA: return "truncated data";
        case N148I_ERROR_CORRUPT_DATA: return "corrupt data";
        case N148I_ERROR_SIZE_OVERFLOW: return "image or buffer is too large";
        case N148I_ERROR_ENCODE_FAILED: return "encoding failed";
        case N148I_ERROR_DECODE_FAILED: return "decoding failed";
        case N148I_ERROR_UNSUPPORTED_SIMD: return "SIMD level is not supported";
        case N148I_ERROR_UNSUPPORTED_FEATURE: return "unsupported format feature";
        default: return "unknown N.148i error";
    }
}

const char *n148i_library_version(void) {
    return N148I_VERSION_STRING;
}

uint32_t n148i_format_version(void) {
    return N148I_FORMAT_VERSION;
}

n148i_simd_level_t n148i_simd_level(void) {
    return (n148i_simd_level_t) n148_cpu_level();
}

const char *n148i_simd_name(n148i_simd_level_t level) {
    switch (level) {
        case N148I_SIMD_AUTO: return "automatic";
        case N148I_SIMD_SCALAR: return "scalar";
        case N148I_SIMD_SSE2: return "SSE2";
        case N148I_SIMD_AVX2: return "AVX2";
        case N148I_SIMD_AVX2_FMA: return "AVX2+FMA";
        default: return "unknown";
    }
}

n148i_result_t n148i_simd_force(n148i_simd_level_t level) {
    if (level == N148I_SIMD_AUTO) {
        n148_cpu_force(-1);
        return N148I_OK;
    }
    if (level < N148I_SIMD_SCALAR || level > N148I_SIMD_AVX2_FMA)
        return N148I_ERROR_INVALID_ARGUMENT;
    if ((int) level > n148_cpu_detected_level())
        return N148I_ERROR_UNSUPPORTED_SIMD;
    n148_cpu_force((int) level);
    return N148I_OK;
}

src/main.c

O main.c é o programa de linha de comando que comprime um PPM e decodifica o resultado, do artigo 16. Na V2, ele ganhou a escolha automática da cor e os parâmetros de formato, perfil e esforço, e passou a mostrar a máscara de recursos do arquivo gerado.

Na V1, o arquivo tinha 225 linhas:

/*
 * N.148i command-line roundtrip tool
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

#include "n148i.h"
#include "ppm.h"

#define DEFAULT_INPUT   "images/example.ppm"
#define DEFAULT_ENCODED "output/image.n148i"
#define DEFAULT_DECODED "output/decoded.ppm"
#define N148I_FIXED_HEADER_SIZE 21
#ifndef QUALITY
#define QUALITY 50
#endif
#ifndef CHROMA_MODE
#define CHROMA_MODE N148I_CHROMA_420
#endif
#ifndef OPTIMIZE
#define OPTIMIZE 1
#endif

static long file_size(const char *path) {
    FILE *file = fopen(path, "rb");
    if (!file) return 0;
    if (fseek(file, 0, SEEK_END) != 0) {
        fclose(file);
        return 0;
    }
    long size = ftell(file);
    fclose(file);
    return size;
}

static int write_file(const char *path, const uint8_t *data, size_t size) {
    FILE *file = fopen(path, "wb");
    if (!file) return 0;
    int written = fwrite(data, 1, size, file) == size;
    int closed = fclose(file) == 0;
    return written && closed;
}

static double compute_psnr(const Image *first, const n148i_image_t *second) {
    if ((uint32_t) first->width != second->width ||
        (uint32_t) first->height != second->height) {
        return 0.0;
    }

    long value_count = (long) first->width * first->height * 3;
    double mean_squared_error = 0.0;
    for (long index = 0; index < value_count; index++) {
        double difference =
            (double) first->pixels[index] - (double) second->pixels[index];
        mean_squared_error += difference * difference;
    }
    mean_squared_error /= value_count;
    if (mean_squared_error == 0.0) return 999.0;
    return 10.0 * log10(255.0 * 255.0 / mean_squared_error);
}

static const char *chroma_name(n148i_chroma_t chroma) {
    switch (chroma) {
        case N148I_CHROMA_444: return "4:4:4";
        case N148I_CHROMA_422: return "4:2:2";
        case N148I_CHROMA_420: return "4:2:0";
        default: return "unknown";
    }
}

static void cli_chroma_dimensions(n148i_chroma_t chroma,
                                  int width, int height,
                                  int *chroma_width, int *chroma_height) {
    *chroma_width = chroma == N148I_CHROMA_444 ? width : (width + 1) / 2;
    *chroma_height = chroma == N148I_CHROMA_420 ? (height + 1) / 2 : height;
}

static long block_count(int width, int height) {
    return (long) ((width + 7) / 8) * ((height + 7) / 8);
}

static void print_usage(const char *program) {
    printf("usage: %s [input.ppm] [quality] [chroma]\n", program);
    printf("  input.ppm  source image (default: %s)\n", DEFAULT_INPUT);
    printf("  quality    1..100        (default: %d)\n", QUALITY);
    printf("  chroma     0=4:4:4 1=4:2:2 2=4:2:0 (default: %d)\n",
           CHROMA_MODE);
}

int main(int argc, char **argv) {
    const char *input_path = DEFAULT_INPUT;
    int quality = QUALITY;
    int chroma_value = CHROMA_MODE;
    Image original = {0};
    n148i_image_t decoded = {0};
    uint8_t *encoded = NULL;
    size_t encoded_size = 0;
    int exit_code = EXIT_FAILURE;

    if (argc > 1) {
        if (argv[1][0] == '-') {
            print_usage(argv[0]);
            return EXIT_SUCCESS;
        }
        input_path = argv[1];
    }
    if (argc > 2) quality = atoi(argv[2]);
    if (argc > 3) chroma_value = atoi(argv[3]);
    if (quality < 1 || quality > 100) {
        printf("quality must be 1..100\n");
        return EXIT_FAILURE;
    }
    if (chroma_value < N148I_CHROMA_444 ||
        chroma_value > N148I_CHROMA_420) {
        printf("chroma must be 0, 1 or 2\n");
        return EXIT_FAILURE;
    }

    if (!load_ppm(input_path, &original)) goto cleanup;

    n148i_chroma_t chroma = (n148i_chroma_t) chroma_value;
    n148i_image_t source = {
        original.pixels,
        (uint32_t) original.width,
        (uint32_t) original.height,
        (size_t) original.width * 3
    };
    n148i_encode_options_t options;
    n148i_encode_options_init(&options);
    options.quality = quality;
    options.chroma = chroma;
    options.optimize_huffman = OPTIMIZE;

    printf("=== N.148i encoder ===\n");
    printf("Input:    %s  (%d x %d)\n", input_path,
           original.width, original.height);
    printf("Quality:  %d\n", quality);
    printf("Chroma:   %s\n", chroma_name(chroma));
    printf("Huffman:  %s\n\n",
           options.optimize_huffman ? "optimized for this image" :
                                      "standard tables");

    int chroma_width, chroma_height;
    cli_chroma_dimensions(chroma, original.width, original.height,
                          &chroma_width, &chroma_height);
    printf("Y plane:      %d x %d\n", original.width, original.height);
    printf("Cb/Cr planes: %d x %d\n\n", chroma_width, chroma_height);

    n148i_result_t result = n148i_encode_memory(
        &source, &options, &encoded, &encoded_size);
    if (result != N148I_OK) {
        printf("Encoding failed: %s.\n", n148i_result_string(result));
        goto cleanup;
    }

    n148i_image_info_t info;
    result = n148i_read_header(encoded, encoded_size, &info);
    if (result != N148I_OK) {
        printf("Encoded header is invalid: %s.\n",
               n148i_result_string(result));
        goto cleanup;
    }
    long blocks = block_count(original.width, original.height) +
        2 * block_count(chroma_width, chroma_height);
    printf("Encoded %ld blocks\n", blocks);
    if (info.optimized_huffman) {
        printf("Huffman tables: %zu bytes stored in the file\n",
               info.encoded_header_size - N148I_FIXED_HEADER_SIZE);
    }
    printf("Entropy data:   %u bytes\n", info.payload_size);

    if (!write_file(DEFAULT_ENCODED, encoded, encoded_size)) {
        printf("Could not write '%s'\n", DEFAULT_ENCODED);
        goto cleanup;
    }
    printf("Wrote %s\n\n", DEFAULT_ENCODED);

    printf("=== N.148i decoder ===\n");
    printf("Header:  v%u, %u x %u, quality %u, chroma %s, %s tables\n",
           info.format_version, info.width, info.height, info.quality,
           chroma_name(info.chroma),
           info.optimized_huffman ? "custom" : "standard");
    result = n148i_decode_memory(encoded, encoded_size, &decoded);
    if (result != N148I_OK) {
        printf("Decoding failed: %s.\n", n148i_result_string(result));
        goto cleanup;
    }
    printf("Decoded %ld blocks, consumed %u of %u bytes\n",
           blocks, info.payload_size, info.payload_size);
    printf("Upsampling: bilinear\n");

    Image decoded_view = {
        (int) decoded.width,
        (int) decoded.height,
        decoded.pixels
    };
    if (!save_ppm(DEFAULT_DECODED, &decoded_view)) {
        printf("Could not write '%s'\n", DEFAULT_DECODED);
        goto cleanup;
    }
    printf("Wrote %s\n\n", DEFAULT_DECODED);

    long original_bytes = file_size(input_path);
    long encoded_bytes = file_size(DEFAULT_ENCODED);
    double psnr = compute_psnr(&original, &decoded);
    printf("=== Results ===\n");
    printf("Original PPM: %8ld bytes (%.1f KB)\n",
           original_bytes, original_bytes / 1024.0);
    printf("N148i file:   %8ld bytes (%.1f KB)\n",
           encoded_bytes, encoded_bytes / 1024.0);
    printf("Compression:  %.1f:1\n", (double) original_bytes / encoded_bytes);
    printf("PSNR:         %.2f dB\n", psnr);
    exit_code = EXIT_SUCCESS;

cleanup:
    n148i_free_buffer(encoded);
    n148i_free_image(&decoded);
    free_image(&original);
    return exit_code;
}

Na V2, ele ficou com 318 linhas:

/*
 * N.148i command-line roundtrip tool
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "n148i.h"
#include "ppm.h"

#define DEFAULT_INPUT   "images/example.ppm"
#define DEFAULT_ENCODED "output/image.n148i"
#define DEFAULT_DECODED "output/decoded.ppm"
#ifndef QUALITY
#define QUALITY 50
#endif
#ifndef CHROMA_MODE
#define CHROMA_MODE N148I_CHROMA_420
#endif
#ifndef OPTIMIZE
#define OPTIMIZE 1
#endif

static long file_size(const char *path) {
    FILE *file = fopen(path, "rb");
    if (!file) return 0;
    if (fseek(file, 0, SEEK_END) != 0) {
        fclose(file);
        return 0;
    }
    long size = ftell(file);
    fclose(file);
    return size;
}

static int write_file(const char *path, const uint8_t *data, size_t size) {
    FILE *file = fopen(path, "wb");
    if (!file) return 0;
    int written = fwrite(data, 1, size, file) == size;
    int closed = fclose(file) == 0;
    return written && closed;
}

static double compute_psnr(const Image *first, const n148i_image_t *second) {
    if ((uint32_t) first->width != second->width ||
        (uint32_t) first->height != second->height) {
        return 0.0;
    }

    long value_count = (long) first->width * first->height * 3;
    double mean_squared_error = 0.0;
    for (long index = 0; index < value_count; index++) {
        double difference =
            (double) first->pixels[index] - (double) second->pixels[index];
        mean_squared_error += difference * difference;
    }
    mean_squared_error /= value_count;
    if (mean_squared_error == 0.0) return 999.0;
    return 10.0 * log10(255.0 * 255.0 / mean_squared_error);
}

static const char *chroma_name(n148i_chroma_t chroma) {
    switch (chroma) {
        case N148I_CHROMA_444: return "4:4:4";
        case N148I_CHROMA_422: return "4:2:2";
        case N148I_CHROMA_420: return "4:2:0";
        case N148I_CHROMA_AUTO: return "auto";
        default: return "unknown";
    }
}

static void cli_chroma_dimensions(n148i_chroma_t chroma,
                                  int width, int height,
                                  int *chroma_width, int *chroma_height) {
    *chroma_width = chroma == N148I_CHROMA_444 ?
        width : width / 2 + (width & 1);
    *chroma_height = chroma == N148I_CHROMA_420 ?
        height / 2 + (height & 1) : height;
}

static long block_count(int width, int height) {
    int blocks_x = width / 8 + (width % 8 != 0);
    int blocks_y = height / 8 + (height % 8 != 0);
    return (long) blocks_x * blocks_y;
}

static void print_usage(const char *program) {
    printf("usage: %s [input.ppm] [quality] [chroma] [format] [profile] [effort]\n", program);
    printf("  input.ppm  source image (default: %s)\n", DEFAULT_INPUT);
    printf("  quality    1..100        (default: %d)\n", QUALITY);
    printf("  chroma     0=4:4:4 1=4:2:2 2=4:2:0 3=auto (default: %d)\n",
           CHROMA_MODE);
    printf("  format     1=legacy 2-6=compatible 7=current (default: %d)\n",
           N148I_FORMAT_VERSION);
    printf("  profile    default, spectral, refined, structural, balanced, or detail (custom profiles require format 7)\n");
    printf("  effort     0..9 (default: 3; use 4 for selective luma search)\n");
}

int main(int argc, char **argv) {
    const char *input_path = DEFAULT_INPUT;
    int quality = QUALITY;
    int chroma_value = CHROMA_MODE;
    int format_version = N148I_FORMAT_VERSION;
    const char *profile = "default";
    int effort = 3;
    Image original = {0};
    n148i_image_t decoded = {0};
    uint8_t *encoded = NULL;
    size_t encoded_size = 0;
    int exit_code = EXIT_FAILURE;

    if (argc > 1) {
        if (argv[1][0] == '-') {
            print_usage(argv[0]);
            return EXIT_SUCCESS;
        }
        input_path = argv[1];
    }
    if (argc > 2) quality = atoi(argv[2]);
    if (argc > 3) chroma_value = atoi(argv[3]);
    if (argc > 4) format_version = atoi(argv[4]);
    if (argc > 5) profile = argv[5];
    if (argc > 6) effort = atoi(argv[6]);
    if (argc > 7 || effort < 0 || effort > 9 ||
        (strcmp(profile, "default") != 0 &&
         strcmp(profile, "spectral") != 0 &&
         strcmp(profile, "refined") != 0 &&
         strcmp(profile, "structural") != 0 &&
         strcmp(profile, "balanced") != 0 &&
         strcmp(profile, "detail") != 0)) {
        print_usage(argv[0]);
        return EXIT_FAILURE;
    }
    if (quality < 1 || quality > 100) {
        printf("quality must be 1..100\n");
        return EXIT_FAILURE;
    }
    if (chroma_value < N148I_CHROMA_444 ||
        chroma_value > N148I_CHROMA_AUTO) {
        printf("chroma must be 0, 1, 2 or 3\n");
        return EXIT_FAILURE;
    }
    if (chroma_value == N148I_CHROMA_AUTO &&
        format_version != N148I_FORMAT_VERSION_5 &&
        format_version != N148I_FORMAT_VERSION_6 &&
        format_version != N148I_FORMAT_VERSION_7) {
        printf("automatic chroma requires format 5, 6 or 7\n");
        return EXIT_FAILURE;
    }
    if (format_version != N148I_FORMAT_VERSION_1 &&
        format_version != N148I_FORMAT_VERSION_2 &&
        format_version != N148I_FORMAT_VERSION_3 &&
        format_version != N148I_FORMAT_VERSION_4 &&
        format_version != N148I_FORMAT_VERSION_5 &&
        format_version != N148I_FORMAT_VERSION_6 &&
        format_version != N148I_FORMAT_VERSION_7) {
        printf("format must be 1, 2, 3, 4, 5, 6 or 7\n");
        return EXIT_FAILURE;
    }
    if (strcmp(profile, "default") != 0 &&
        format_version != N148I_FORMAT_VERSION_7) {
        printf("spectral, refined, structural, balanced, and detail profiles require format 7\n");
        return EXIT_FAILURE;
    }

    if (!load_ppm(input_path, &original)) goto cleanup;

    n148i_chroma_t chroma = (n148i_chroma_t) chroma_value;
    n148i_image_t source = {
        original.pixels,
        (uint32_t) original.width,
        (uint32_t) original.height,
        (size_t) original.width * 3
    };
    n148i_encode_options_t options;
    n148i_encode_options_init(&options);
    options.quality = quality;
    options.effort = effort;
    options.chroma = chroma;
    options.optimize_huffman = OPTIMIZE;
    options.format_version = (uint32_t) format_version;
    if (format_version == N148I_FORMAT_VERSION_2) {
        options.feature_flags = N148I_FORMAT_2_DEFAULT_FEATURES;
    } else if (format_version == N148I_FORMAT_VERSION_3) {
        options.feature_flags = N148I_FORMAT_3_DEFAULT_FEATURES;
    } else if (format_version == N148I_FORMAT_VERSION_4) {
        options.feature_flags = N148I_FORMAT_4_DEFAULT_FEATURES;
    } else if (format_version == N148I_FORMAT_VERSION_5) {
        options.feature_flags = N148I_FORMAT_5_DEFAULT_FEATURES;
    } else if (format_version == N148I_FORMAT_VERSION_6) {
        options.feature_flags = N148I_FORMAT_6_DEFAULT_FEATURES;
    } else if (format_version == N148I_FORMAT_VERSION_7) {
        options.feature_flags = strcmp(profile, "detail") == 0 ?
            N148I_PROFILE_DETAIL_RECONSTRUCTION :
            strcmp(profile, "balanced") == 0 ?
            N148I_PROFILE_BALANCED_RECONSTRUCTION :
            strcmp(profile, "structural") == 0 ?
            N148I_PROFILE_STRUCTURAL_LUMA_QUANT :
            strcmp(profile, "spectral") == 0 ?
            N148I_PROFILE_SPECTRAL_LUMA_QUANT :
            strcmp(profile, "refined") == 0 ?
            N148I_PROFILE_REFINED_SPECTRAL_LUMA_QUANT :
            N148I_DEFAULT_FEATURES;
    }

    printf("=== N.148i encoder ===\n");
    printf("Input:    %s  (%d x %d)\n", input_path,
           original.width, original.height);
    printf("Quality:  %d\n", quality);
    printf("Chroma:   %s\n", chroma_name(chroma));
    printf("Format:   v%d\n", format_version);
    printf("Effort:   %d\n", effort);
    if (format_version == N148I_FORMAT_VERSION_7)
        printf("Profile:  %s\n", profile);
    if (format_version >= N148I_FORMAT_VERSION_2) {
        printf("Coding:   contextual byte rANS with intra prediction\n\n");
    } else {
        printf("Huffman:  %s\n\n",
               options.optimize_huffman ? "optimized for this image" :
                                          "standard tables");
    }

    int chroma_width = 0, chroma_height = 0;
    printf("Y plane:      %d x %d\n", original.width, original.height);
    if (chroma == N148I_CHROMA_AUTO) {
        printf("Cb/Cr planes: automatic search\n\n");
    } else {
        cli_chroma_dimensions(chroma, original.width, original.height,
                              &chroma_width, &chroma_height);
        printf("Cb/Cr planes: %d x %d\n\n", chroma_width, chroma_height);
    }

    n148i_result_t result = n148i_encode_memory(
        &source, &options, &encoded, &encoded_size);
    if (result != N148I_OK) {
        printf("Encoding failed: %s.\n", n148i_result_string(result));
        goto cleanup;
    }
    n148i_image_info_t info;
    result = n148i_read_header(encoded, encoded_size, &info);
    if (result != N148I_OK) {
        printf("Encoded header is invalid: %s.\n",
               n148i_result_string(result));
        goto cleanup;
    }
    cli_chroma_dimensions(info.chroma, original.width, original.height,
                          &chroma_width, &chroma_height);
    long blocks = block_count(original.width, original.height) +
        2 * block_count(chroma_width, chroma_height);
    printf("Encoded %ld blocks\n", blocks);
    if (info.format_version >= N148I_FORMAT_VERSION_2) {
        printf("Feature flags:   0x%08x\n", info.feature_flags);
        printf("Entropy metadata: %u bytes\n", info.metadata_size);
    } else if (info.optimized_huffman) {
        printf("Huffman tables: %u bytes stored in the file\n",
               info.metadata_size);
    }
    printf("Entropy data:   %u bytes\n", info.payload_size);

    if (!write_file(DEFAULT_ENCODED, encoded, encoded_size)) {
        printf("Could not write '%s'\n", DEFAULT_ENCODED);
        goto cleanup;
    }
    printf("Wrote %s\n\n", DEFAULT_ENCODED);

    printf("=== N.148i decoder ===\n");
    printf("Header:  v%u, %u x %u, quality %u, chroma %s",
           info.format_version, info.width, info.height, info.quality,
           chroma_name(info.chroma));
    if (info.format_version >= N148I_FORMAT_VERSION_2) {
        printf(", features 0x%08x\n", info.feature_flags);
    } else {
        printf(", %s Huffman tables\n",
               info.optimized_huffman ? "custom" : "standard");
    }
    result = n148i_decode_memory(encoded, encoded_size, &decoded);
    if (result != N148I_OK) {
        printf("Decoding failed: %s.\n", n148i_result_string(result));
        goto cleanup;
    }
    printf("Decoded %ld blocks, consumed %u of %u bytes\n",
           blocks, info.payload_size, info.payload_size);
    printf("Upsampling: bilinear\n");

    Image decoded_view = {
        (int) decoded.width,
        (int) decoded.height,
        decoded.pixels
    };
    if (!save_ppm(DEFAULT_DECODED, &decoded_view)) {
        printf("Could not write '%s'\n", DEFAULT_DECODED);
        goto cleanup;
    }
    printf("Wrote %s\n\n", DEFAULT_DECODED);

    long original_bytes = file_size(input_path);
    long encoded_bytes = file_size(DEFAULT_ENCODED);
    double psnr = compute_psnr(&original, &decoded);
    printf("=== Results ===\n");
    printf("Original PPM: %8ld bytes (%.1f KB)\n",
           original_bytes, original_bytes / 1024.0);
    printf("N148i file:   %8ld bytes (%.1f KB)\n",
           encoded_bytes, encoded_bytes / 1024.0);
    printf("Compression:  %.1f:1\n", (double) original_bytes / encoded_bytes);
    printf("PSNR:         %.2f dB\n", psnr);
    exit_code = EXIT_SUCCESS;

cleanup:
    n148i_free_buffer(encoded);
    n148i_free_image(&decoded);
    free_image(&original);
    return exit_code;
}

src/validate_cli.c

O validate_cli.c é a bateria de validação do codec, que confere que o decoder consome exatamente os bytes do encoder e que o resultado não muda com o processador nem com o número de threads.

Ele foi o arquivo que mais cresceu, de 417 para 4.674 linhas, porque cada ferramenta nova da Fase 5 ganhou os seus próprios testes.

Na V1, o arquivo tinha 417 linhas:

/*
 * N.148 codec validation driver.
 *
 * Copyright (c) Micilini Roll. Licensed under the MIT License.
 *
 * This executable verifies bitstream determinism across CPU paths and thread
 * counts, partial 8x8 blocks, and exact encoder/decoder byte consumption.
 */
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "n148i.h"
#include "decoder.h"
#include "encoder.h"
#include "header.h"
#include "huffman.h"
#include "ppm.h"
#include "cpu.h"
#include "parallel.h"

#define EXPECTED_EXAMPLE_SIZE 2290L
#define ODD_WIDTH 317
#define ODD_HEIGHT 241

typedef struct {
    unsigned char *stream;
    long stream_size;
    long payload_size;
    long bytes_consumed;
    double psnr;
    int width;
    int height;
    int cpu_level;
    int threads;
    int chroma;
    char cpu_name[16];
    Image decoded;
} CycleResult;

static void release_cycle(CycleResult *result) {
    free(result->stream);
    result->stream = NULL;
    free_image(&result->decoded);
}

static double image_psnr(const Image *original, const Image *decoded) {
    long count = (long) original->width * original->height * 3;
    double squared_error = 0.0;

    for (long index = 0; index < count; index++) {
        double difference =
            (double) original->pixels[index] - decoded->pixels[index];
        squared_error += difference * difference;
    }

    if (squared_error == 0.0) return 999.0;
    return 10.0 * log10(255.0 * 255.0 /
                        (squared_error / (double) count));
}

static int run_cycle(const Image *original, int quality, int chroma,
                     int cpu_level, int threads, CycleResult *result) {
    Plane y = {0}, cb = {0}, cr = {0};
    Plane decoded_y = {0}, decoded_cb = {0}, decoded_cr = {0};
    HuffSpec encode_specs[HUFFMAN_TABLE_COUNT];
    HuffSpec decode_specs[HUFFMAN_TABLE_COUNT];
    EncodeStats encode_stats;
    DecodeStats decode_stats;
    unsigned char *payload = NULL;
    unsigned char *loaded_payload = NULL;
    FILE *file = NULL;
    int success = 0;

    memset(result, 0, sizeof(*result));
    n148_cpu_force(cpu_level);
    n148_set_thread_count(threads);
    result->cpu_level = n148_cpu_level();
    result->threads = n148_thread_count();
    result->chroma = chroma;
    snprintf(result->cpu_name, sizeof(result->cpu_name), "%s", n148_cpu_name());

    if (!split_channels((Image *) original, &y, &cb, &cr, chroma)) {
        fprintf(stderr, "split_channels failed for chroma %d\n", chroma);
        goto cleanup;
    }
    if (!encode_image(&y, &cb, &cr, quality, 1, encode_specs,
                      &payload, &encode_stats)) {
        fprintf(stderr, "encode_image failed for chroma %d\n", chroma);
        goto cleanup;
    }

    N148iHeader header;
    header.version = N148I_VERSION;
    header.width = (uint32_t) original->width;
    header.height = (uint32_t) original->height;
    header.quality = (uint8_t) quality;
    header.chroma = (uint8_t) chroma;
    header.optimized = 1;
    header.data_size = (uint32_t) encode_stats.data_size;

    file = tmpfile();
    if (!file ||
        !write_header(file, &header) ||
        !write_huffman_tables(file, encode_specs) ||
        fwrite(payload, 1, (size_t) encode_stats.data_size, file) !=
            (size_t) encode_stats.data_size ||
        fflush(file) != 0 ||
        fseek(file, 0, SEEK_END) != 0) {
        fprintf(stderr, "could not serialize validation stream\n");
        goto cleanup;
    }

    result->stream_size = ftell(file);
    result->payload_size = encode_stats.data_size;
    long expected_size =
        N148I_HEADER_SIZE + huffman_tables_size(encode_specs) +
        encode_stats.data_size;
    if (result->stream_size != expected_size || result->stream_size <= 0) {
        fprintf(stderr, "serialized size mismatch: %ld vs %ld\n",
                result->stream_size, expected_size);
        goto cleanup;
    }

    result->stream = (unsigned char *) malloc((size_t) result->stream_size);
    if (!result->stream ||
        fseek(file, 0, SEEK_SET) != 0 ||
        fread(result->stream, 1, (size_t) result->stream_size, file) !=
            (size_t) result->stream_size ||
        fseek(file, 0, SEEK_SET) != 0) {
        fprintf(stderr, "could not read serialized validation stream\n");
        goto cleanup;
    }

    N148iHeader loaded;
    if (!read_header(file, &loaded) ||
        loaded.version != header.version ||
        loaded.width != header.width ||
        loaded.height != header.height ||
        loaded.quality != header.quality ||
        loaded.chroma != header.chroma ||
        loaded.optimized != header.optimized ||
        loaded.data_size != header.data_size ||
        !read_huffman_tables(file, decode_specs)) {
        fprintf(stderr, "serialized header or Huffman tables differ\n");
        goto cleanup;
    }

    loaded_payload = (unsigned char *) malloc(loaded.data_size);
    if (!loaded_payload ||
        fread(loaded_payload, 1, loaded.data_size, file) != loaded.data_size ||
        fgetc(file) != EOF) {
        fprintf(stderr, "serialized payload is truncated or has trailing bytes\n");
        goto cleanup;
    }

    if (!decode_image(loaded_payload, loaded.data_size,
                      original->width, original->height, quality, chroma,
                      decode_specs, &decoded_y, &decoded_cb, &decoded_cr,
                      &decode_stats) ||
        !merge_channels(&decoded_y, &decoded_cb, &decoded_cr, 1,
                        &result->decoded)) {
        fprintf(stderr, "decode cycle failed for chroma %d\n", chroma);
        goto cleanup;
    }

    result->bytes_consumed = decode_stats.bytes_consumed;
    result->width = result->decoded.width;
    result->height = result->decoded.height;
    result->psnr = image_psnr(original, &result->decoded);
    if (result->bytes_consumed != result->payload_size) {
        fprintf(stderr, "decoder consumed %ld of %ld bytes for chroma %d\n",
                result->bytes_consumed, result->payload_size, chroma);
        goto cleanup;
    }
    if (result->width != original->width ||
        result->height != original->height) {
        fprintf(stderr, "decoded dimensions changed for chroma %d\n", chroma);
        goto cleanup;
    }

    success = 1;

cleanup:
    if (file) fclose(file);
    free(payload);
    free(loaded_payload);
    free_plane(&y);
    free_plane(&cb);
    free_plane(&cr);
    free_plane(&decoded_y);
    free_plane(&decoded_cb);
    free_plane(&decoded_cr);
    if (!success) release_cycle(result);
    return success;
}

static int cycles_identical(const CycleResult *left,
                            const CycleResult *right) {
    long pixel_count = (long) left->width * left->height * 3;
    return left->stream_size == right->stream_size &&
           memcmp(left->stream, right->stream,
                  (size_t) left->stream_size) == 0 &&
           left->width == right->width &&
           left->height == right->height &&
           memcmp(left->decoded.pixels, right->decoded.pixels,
                  (size_t) pixel_count) == 0 &&
           left->psnr == right->psnr;
}

static void print_cycle(const char *name, const CycleResult *result) {
    printf("cycle,%s,%s,%d,%d,%d,%d,%ld,%ld,%ld,%.12f,"
           "roundtrip_exact,PASS\n",
           name, result->cpu_name, result->threads, result->chroma,
           result->width, result->height, result->stream_size,
           result->payload_size, result->bytes_consumed, result->psnr);
}

static void fill_odd_image(Image *image) {
    image->width = ODD_WIDTH;
    image->height = ODD_HEIGHT;
    image->pixels = (unsigned char *) malloc(
        (size_t) image->width * image->height * 3);
    if (!image->pixels) return;

    for (int y = 0; y < image->height; y++) {
        for (int x = 0; x < image->width; x++) {
            long offset = ((long) y * image->width + x) * 3;
            image->pixels[offset + 0] =
                (unsigned char) ((13 * x + 3 * y + (x * y) % 251) & 255);
            image->pixels[offset + 1] =
                (unsigned char) ((5 * x + 17 * y + (x ^ y)) & 255);
            image->pixels[offset + 2] =
                (unsigned char) ((19 * x + 7 * y + (x * y) % 97) & 255);
        }
    }
}

static int validate_public_api(const Image *original,
                               const CycleResult *reference) {
    n148i_image_t input = {
        original->pixels,
        (uint32_t) original->width,
        (uint32_t) original->height,
        (size_t) original->width * 3
    };
    n148i_encode_options_t options;
    uint8_t *encoded = NULL;
    uint8_t *strided_encoded = NULL;
    uint8_t *strided_pixels = NULL;
    size_t encoded_size = 0;
    size_t strided_size = 0;
    n148i_image_t decoded = {0};
    n148i_image_info_t info = {0};
    int success = 0;

    n148i_encode_options_init(&options);
    options.quality = 50;
    options.chroma = N148I_CHROMA_420;
    options.optimize_huffman = 1;
    options.thread_count = 1;

    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&input, &options, &encoded, &encoded_size) !=
            N148I_OK ||
        encoded_size != (size_t) reference->stream_size ||
        memcmp(encoded, reference->stream, encoded_size) != 0 ||
        n148i_read_header(encoded, encoded_size, &info) != N148I_OK ||
        info.width != (uint32_t) original->width ||
        info.height != (uint32_t) original->height ||
        info.format_version != N148I_FORMAT_VERSION ||
        info.quality != 50 || info.chroma != N148I_CHROMA_420 ||
        !info.optimized_huffman ||
        info.encoded_header_size + info.payload_size != encoded_size ||
        n148i_decode_memory(encoded, encoded_size, &decoded) != N148I_OK ||
        decoded.width != (uint32_t) reference->width ||
        decoded.height != (uint32_t) reference->height ||
        decoded.stride != (size_t) reference->width * 3 ||
        memcmp(decoded.pixels, reference->decoded.pixels,
               decoded.stride * decoded.height) != 0) {
        goto cleanup;
    }

    size_t tight_stride = (size_t) original->width * 3;
    size_t padded_stride = tight_stride + 7;
    strided_pixels = (uint8_t *) malloc(
        padded_stride * (size_t) original->height);
    if (!strided_pixels) goto cleanup;
    memset(strided_pixels, 0xa5, padded_stride * (size_t) original->height);
    for (int row = 0; row < original->height; row++) {
        memcpy(strided_pixels + (size_t) row * padded_stride,
               original->pixels + (size_t) row * tight_stride,
               tight_stride);
    }
    input.pixels = strided_pixels;
    input.stride = padded_stride;
    if (n148i_encode_memory(&input, &options, &strided_encoded,
                            &strided_size) != N148I_OK ||
        strided_size != encoded_size ||
        memcmp(strided_encoded, encoded, encoded_size) != 0 ||
        n148i_read_header(encoded, N148I_HEADER_SIZE - 1, &info) !=
            N148I_ERROR_TRUNCATED_DATA) {
        goto cleanup;
    }
    success = 1;

cleanup:
    printf("comparison,public_api_vs_internal,scalar,1,2,%d,%d,%zu,%u,%u,"
           "%.12f,memory_stride_and_bitstream_identical,%s\n",
           original->width, original->height, encoded_size,
           info.payload_size, info.payload_size, reference->psnr,
           success ? "PASS" : "FAIL");
    free(strided_pixels);
    n148i_free_buffer(strided_encoded);
    n148i_free_image(&decoded);
    n148i_free_buffer(encoded);
    n148i_simd_force(N148I_SIMD_AUTO);
    return success;
}

int main(int argc, char **argv) {
    const char *example_path =
        argc > 1 ? argv[1] : "images/example.ppm";
    const char *odd_path =
        argc > 2 ? argv[2] : "output/validation-317x241.ppm";
    Image example = {0};
    Image odd = {0};
    CycleResult scalar = {0}, avx2 = {0};
    int failures = 0;

    printf("kind,name,cpu,threads,chroma,width,height,file_bytes,"
           "payload_bytes,bytes_consumed,psnr_db,detail,result\n");

    n148_cpu_force(-1);
    int detected_level = n148_cpu_level();
    if (detected_level < N148_CPU_AVX2) {
        fprintf(stderr, "AVX2 is unavailable; path comparison cannot run\n");
        return EXIT_FAILURE;
    }
    if (!load_ppm(example_path, &example)) {
        fprintf(stderr, "could not load %s\n", example_path);
        return EXIT_FAILURE;
    }

    int scalar_ok = run_cycle(&example, 50, CHROMA_420,
                              N148_CPU_BASELINE, 1, &scalar);
    int avx2_ok = run_cycle(&example, 50, CHROMA_420,
                            N148_CPU_AVX2, 1, &avx2);
    if (scalar_ok) print_cycle("example_scalar", &scalar);
    if (avx2_ok) print_cycle("example_avx2", &avx2);

    int path_match =
        scalar_ok && avx2_ok &&
        scalar.stream_size == EXPECTED_EXAMPLE_SIZE &&
        avx2.stream_size == EXPECTED_EXAMPLE_SIZE &&
        cycles_identical(&scalar, &avx2);
    printf("comparison,scalar_vs_avx2,scalar+AVX2,1,2,%d,%d,%ld,%ld,%ld,"
           "%.12f,byte_and_psnr_identical,%s\n",
           example.width, example.height,
           scalar_ok ? scalar.stream_size : 0,
           scalar_ok ? scalar.payload_size : 0,
           scalar_ok ? scalar.bytes_consumed : 0,
           scalar_ok ? scalar.psnr : 0.0,
           path_match ? "PASS" : "FAIL");
    if (!path_match) failures++;

    if (scalar_ok && !validate_public_api(&example, &scalar)) failures++;

    fill_odd_image(&odd);
    if (!odd.pixels || !save_ppm(odd_path, &odd)) {
        fprintf(stderr, "could not create %s\n", odd_path);
        failures++;
    } else {
        for (int chroma = CHROMA_444; chroma <= CHROMA_420; chroma++) {
            CycleResult single = {0}, parallel = {0};
            int single_ok = run_cycle(&odd, 50, chroma, -1, 1, &single);
            int parallel_ok = run_cycle(&odd, 50, chroma, -1, 4, &parallel);
            char single_name[32];
            char parallel_name[32];
            snprintf(single_name, sizeof(single_name),
                     "odd_chroma%d_t1", chroma);
            snprintf(parallel_name, sizeof(parallel_name),
                     "odd_chroma%d_t4", chroma);
            if (single_ok) print_cycle(single_name, &single);
            if (parallel_ok) print_cycle(parallel_name, &parallel);

            int thread_match =
                single_ok && parallel_ok &&
                cycles_identical(&single, &parallel);
            printf("comparison,odd_chroma%d_t1_vs_t4,auto,1+4,%d,%d,%d,%ld,"
                   "%ld,%ld,%.12f,byte_and_psnr_identical,%s\n",
                   chroma, chroma, odd.width, odd.height,
                   single_ok ? single.stream_size : 0,
                   single_ok ? single.payload_size : 0,
                   single_ok ? single.bytes_consumed : 0,
                   single_ok ? single.psnr : 0.0,
                   thread_match ? "PASS" : "FAIL");
            if (!thread_match) failures++;
            release_cycle(&single);
            release_cycle(&parallel);
        }
    }

    release_cycle(&scalar);
    release_cycle(&avx2);
    free_image(&example);
    free_image(&odd);
    n148_cpu_force(-1);
    n148_set_thread_count(1);

    fprintf(stderr, "validation %s (%d failure%s)\n",
            failures == 0 ? "PASS" : "FAIL",
            failures, failures == 1 ? "" : "s");
    return failures == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}

Na V2, ele ficou com 4.674 linhas:

/*
 * N.148 codec validation driver.
 *
 * Copyright (c) Micilini Roll. Licensed under the MIT License.
 *
 * This executable verifies bitstream determinism across CPU paths and thread
 * counts, partial 8x8 blocks, and exact encoder/decoder byte consumption.
 */
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "n148i.h"
#include "decoder.h"
#include "encoder.h"
#include "header.h"
#include "huffman.h"
#include "intra.h"
#include "loop_filter.h"
#include "ppm.h"
#include "cpu.h"
#include "parallel.h"
#include "perceptual.h"
#include "rans.h"
#include "rdo.h"
#include "tables.h"
#include "variable_transform.h"
#include "entropy_payload.h"
#include "predictive_codec.h"
#include "directional_intra.h"
#include "chroma_profile.h"
#include "entropy_profile.h"

#define EXPECTED_EXAMPLE_SIZE 2290L
#define ODD_WIDTH 317
#define ODD_HEIGHT 241

typedef struct {
    unsigned char *stream;
    long stream_size;
    long payload_size;
    long bytes_consumed;
    double psnr;
    int width;
    int height;
    int cpu_level;
    int threads;
    int chroma;
    char cpu_name[16];
    Image decoded;
} CycleResult;

static void release_cycle(CycleResult *result) {
    free(result->stream);
    result->stream = NULL;
    free_image(&result->decoded);
}

static double image_psnr(const Image *original, const Image *decoded) {
    long count = (long) original->width * original->height * 3;
    double squared_error = 0.0;

    for (long index = 0; index < count; index++) {
        double difference =
            (double) original->pixels[index] - decoded->pixels[index];
        squared_error += difference * difference;
    }

    if (squared_error == 0.0) return 999.0;
    return 10.0 * log10(255.0 * 255.0 /
                        (squared_error / (double) count));
}

static int run_cycle(const Image *original, int quality, int chroma,
                     int cpu_level, int threads, CycleResult *result) {
    Plane y = {0}, cb = {0}, cr = {0};
    Plane decoded_y = {0}, decoded_cb = {0}, decoded_cr = {0};
    HuffSpec encode_specs[HUFFMAN_TABLE_COUNT];
    HuffSpec decode_specs[HUFFMAN_TABLE_COUNT];
    EncodeStats encode_stats;
    DecodeStats decode_stats;
    unsigned char *payload = NULL;
    unsigned char *loaded_payload = NULL;
    FILE *file = NULL;
    int success = 0;

    memset(result, 0, sizeof(*result));
    n148_cpu_force(cpu_level);
    n148_set_thread_count(threads);
    result->cpu_level = n148_cpu_level();
    result->threads = n148_thread_count();
    result->chroma = chroma;
    snprintf(result->cpu_name, sizeof(result->cpu_name), "%s", n148_cpu_name());

    if (!split_channels((Image *) original, &y, &cb, &cr, chroma)) {
        fprintf(stderr, "split_channels failed for chroma %d\n", chroma);
        goto cleanup;
    }
    if (!encode_image(&y, &cb, &cr, quality, 1, encode_specs,
                      &payload, &encode_stats)) {
        fprintf(stderr, "encode_image failed for chroma %d\n", chroma);
        goto cleanup;
    }

    N148iHeader header;
    header.version = N148_FORMAT_VERSION_1;
    header.width = (uint32_t) original->width;
    header.height = (uint32_t) original->height;
    header.quality = (uint8_t) quality;
    header.chroma = (uint8_t) chroma;
    header.optimized = 1;
    header.data_size = (uint32_t) encode_stats.data_size;

    file = tmpfile();
    if (!file ||
        !write_header(file, &header) ||
        !write_huffman_tables(file, encode_specs) ||
        fwrite(payload, 1, (size_t) encode_stats.data_size, file) !=
            (size_t) encode_stats.data_size ||
        fflush(file) != 0 ||
        fseek(file, 0, SEEK_END) != 0) {
        fprintf(stderr, "could not serialize validation stream\n");
        goto cleanup;
    }

    result->stream_size = ftell(file);
    result->payload_size = encode_stats.data_size;
    long expected_size =
        N148_FORMAT_1_HEADER_SIZE + huffman_tables_size(encode_specs) +
        encode_stats.data_size;
    if (result->stream_size != expected_size || result->stream_size <= 0) {
        fprintf(stderr, "serialized size mismatch: %ld vs %ld\n",
                result->stream_size, expected_size);
        goto cleanup;
    }

    result->stream = (unsigned char *) malloc((size_t) result->stream_size);
    if (!result->stream ||
        fseek(file, 0, SEEK_SET) != 0 ||
        fread(result->stream, 1, (size_t) result->stream_size, file) !=
            (size_t) result->stream_size ||
        fseek(file, 0, SEEK_SET) != 0) {
        fprintf(stderr, "could not read serialized validation stream\n");
        goto cleanup;
    }

    N148iHeader loaded;
    if (!read_header(file, &loaded) ||
        loaded.version != header.version ||
        loaded.width != header.width ||
        loaded.height != header.height ||
        loaded.quality != header.quality ||
        loaded.chroma != header.chroma ||
        loaded.optimized != header.optimized ||
        loaded.data_size != header.data_size ||
        !read_huffman_tables(file, decode_specs)) {
        fprintf(stderr, "serialized header or Huffman tables differ\n");
        goto cleanup;
    }

    loaded_payload = (unsigned char *) malloc(loaded.data_size);
    if (!loaded_payload ||
        fread(loaded_payload, 1, loaded.data_size, file) != loaded.data_size ||
        fgetc(file) != EOF) {
        fprintf(stderr, "serialized payload is truncated or has trailing bytes\n");
        goto cleanup;
    }

    if (!decode_image(loaded_payload, loaded.data_size,
                      original->width, original->height, quality, chroma,
                      decode_specs, &decoded_y, &decoded_cb, &decoded_cr,
                      &decode_stats) ||
        !merge_channels(&decoded_y, &decoded_cb, &decoded_cr, 1,
                        &result->decoded)) {
        fprintf(stderr, "decode cycle failed for chroma %d\n", chroma);
        goto cleanup;
    }

    result->bytes_consumed = decode_stats.bytes_consumed;
    result->width = result->decoded.width;
    result->height = result->decoded.height;
    result->psnr = image_psnr(original, &result->decoded);
    if (result->bytes_consumed != result->payload_size) {
        fprintf(stderr, "decoder consumed %ld of %ld bytes for chroma %d\n",
                result->bytes_consumed, result->payload_size, chroma);
        goto cleanup;
    }
    if (result->width != original->width ||
        result->height != original->height) {
        fprintf(stderr, "decoded dimensions changed for chroma %d\n", chroma);
        goto cleanup;
    }

    success = 1;

cleanup:
    if (file) fclose(file);
    free(payload);
    free(loaded_payload);
    free_plane(&y);
    free_plane(&cb);
    free_plane(&cr);
    free_plane(&decoded_y);
    free_plane(&decoded_cb);
    free_plane(&decoded_cr);
    if (!success) release_cycle(result);
    return success;
}

static int cycles_identical(const CycleResult *left,
                            const CycleResult *right) {
    long pixel_count = (long) left->width * left->height * 3;
    return left->stream_size == right->stream_size &&
           memcmp(left->stream, right->stream,
                  (size_t) left->stream_size) == 0 &&
           left->width == right->width &&
           left->height == right->height &&
           memcmp(left->decoded.pixels, right->decoded.pixels,
                  (size_t) pixel_count) == 0 &&
           left->psnr == right->psnr;
}

static void print_cycle(const char *name, const CycleResult *result) {
    printf("cycle,%s,%s,%d,%d,%d,%d,%ld,%ld,%ld,%.12f,"
           "roundtrip_exact,PASS\n",
           name, result->cpu_name, result->threads, result->chroma,
           result->width, result->height, result->stream_size,
           result->payload_size, result->bytes_consumed, result->psnr);
}

static void fill_odd_image(Image *image) {
    image->width = ODD_WIDTH;
    image->height = ODD_HEIGHT;
    image->pixels = (unsigned char *) malloc(
        (size_t) image->width * image->height * 3);
    if (!image->pixels) return;

    for (int y = 0; y < image->height; y++) {
        for (int x = 0; x < image->width; x++) {
            long offset = ((long) y * image->width + x) * 3;
            image->pixels[offset + 0] =
                (unsigned char) ((13 * x + 3 * y + (x * y) % 251) & 255);
            image->pixels[offset + 1] =
                (unsigned char) ((5 * x + 17 * y + (x ^ y)) & 255);
            image->pixels[offset + 2] =
                (unsigned char) ((19 * x + 7 * y + (x * y) % 97) & 255);
        }
    }
}

/* Equal-luma red/blue-cyan checks isolate one-pixel chroma detail. A useful
   automatic selector must retain 4:4:4 for this case at high quality. */
static void fill_chroma_detail_image(Image *image) {
    image->width = 64;
    image->height = 64;
    image->pixels = (unsigned char *) malloc(
        (size_t) image->width * image->height * 3u);
    if (!image->pixels) return;

    for (int y = 0; y < image->height; y++) {
        for (int x = 0; x < image->width; x++) {
            size_t offset = ((size_t) y * image->width + x) * 3u;
            if ((x + y) & 1) {
                image->pixels[offset + 0] = 255;
                image->pixels[offset + 1] = 0;
                image->pixels[offset + 2] = 0;
            } else {
                image->pixels[offset + 0] = 0;
                image->pixels[offset + 1] = 82;
                image->pixels[offset + 2] = 255;
            }
        }
    }
}

static int validate_rans_core(void) {
    enum { SYMBOL_COUNT = 8192 };
    uint8_t *symbols = (uint8_t *) malloc(SYMBOL_COUNT);
    uint32_t counts[N148_RANS_ALPHABET_SIZE] = {0};
    N148RansModel model;
    N148RansDecoder decoder;
    uint8_t *stream = NULL;
    size_t stream_size = 0;
    int success = 0;
    if (!symbols) goto cleanup;

    /* Uneven and sparse on purpose: this exercises minimum-one frequency
       preservation as well as repeated renormalization. */
    for (int index = 0; index < SYMBOL_COUNT; index++) {
        uint8_t symbol;
        if (index % 997 == 0) symbol = 255;
        else if (index % 31 == 0) symbol = (uint8_t)(32 + index % 97);
        else if (index % 5 == 0) symbol = 1;
        else symbol = 0;
        symbols[index] = symbol;
        counts[symbol]++;
    }
    if (!n148_rans_build_model(counts, &model) ||
        !n148_rans_encode(symbols, SYMBOL_COUNT, &model,
                          &stream, &stream_size) ||
        !n148_rans_decoder_init(&decoder, &model, stream, stream_size)) {
        goto cleanup;
    }
    for (int index = 0; index < SYMBOL_COUNT; index++) {
        uint8_t decoded = 0;
        if (!n148_rans_decode_symbol(&decoder, &decoded) ||
            decoded != symbols[index]) {
            goto cleanup;
        }
    }
    success = n148_rans_decoder_finished(&decoder);

cleanup:
    printf("comparison,rans_core,scalar,1,0,0,0,%zu,%d,%d,0.0,"
           "normalized_roundtrip,%s\n",
           stream_size, SYMBOL_COUNT, SYMBOL_COUNT,
           success ? "PASS" : "FAIL");
    free(stream);
    free(symbols);
    return success;
}

/* Format 7 snapshots adaptive probabilities in forward symbol order before
   the rANS state is emitted in reverse.  Exercise three independent streams
   (standing in for the three planes) and compare the complete final model
   state on the encoder and decoder sides. */
static int validate_adaptive_rans_core(void) {
    enum { MODEL_COUNT = 3, PLANE_COUNT = 3, SYMBOLS_PER_PLANE = 2048 };
    uint8_t symbols[PLANE_COUNT][SYMBOLS_PER_PLANE];
    uint8_t indexes[PLANE_COUNT][SYMBOLS_PER_PLANE];
    uint32_t counts[MODEL_COUNT][N148_RANS_ALPHABET_SIZE] = {{0}};
    N148RansModel models[MODEL_COUNT];
    const uint8_t adaptive_flags[1] = {0x05u};
    size_t total_stream_size = 0;
    int success = 0;

    for (int plane = 0; plane < PLANE_COUNT; plane++) {
        for (int index = 0; index < SYMBOLS_PER_PLANE; index++) {
            uint8_t model = (uint8_t)((index + 2 * plane) % MODEL_COUNT);
            uint8_t symbol = (uint8_t)(
                ((index / (7 + plane)) + 3 * plane + model) & 7);
            indexes[plane][index] = model;
            symbols[plane][index] = symbol;
            counts[model][symbol]++;
        }
    }
    for (int model = 0; model < MODEL_COUNT; model++)
        if (!n148_rans_build_model(counts[model], &models[model]))
            goto cleanup;

    for (int plane = 0; plane < PLANE_COUNT; plane++) {
        uint8_t *stream = NULL;
        size_t stream_size = 0;
        uint64_t encoder_hash = 0;
        N148RansAdaptiveModel decoder_models[MODEL_COUNT];
        N148RansDecoder decoder;
        int plane_ok = n148_rans_encode_mixed_adaptive(
            symbols[plane], indexes[plane], SYMBOLS_PER_PLANE,
            models, MODEL_COUNT, MODEL_COUNT, adaptive_flags, MODEL_COUNT,
            N148_ENTROPY_ADAPT_RATE_SHIFT, &stream, &stream_size,
            &encoder_hash) &&
            n148_rans_decoder_init_mixed_adaptive(
                &decoder, stream, stream_size, models, decoder_models,
                MODEL_COUNT, MODEL_COUNT, adaptive_flags, MODEL_COUNT,
                N148_ENTROPY_ADAPT_RATE_SHIFT);
        for (int index = 0; index < SYMBOLS_PER_PLANE && plane_ok; index++) {
            uint8_t decoded = 0;
            plane_ok = n148_rans_decode_symbol_with_model(
                &decoder, &models[indexes[plane][index]], &decoded) &&
                decoded == symbols[plane][index];
        }
        uint64_t decoder_hash = plane_ok ?
            n148_rans_adaptive_models_hash(decoder_models, MODEL_COUNT) : 0;
        plane_ok = plane_ok && n148_rans_decoder_finished(&decoder) &&
            encoder_hash != 0 && encoder_hash == decoder_hash;
        total_stream_size += stream_size;
        free(stream);
        if (!plane_ok) goto cleanup;
    }
    success = 1;

cleanup:
    printf("comparison,rans_adaptive_state,scalar,1,0,0,0,%zu,%d,%d,0.0,"
           "three_plane_integer_model_state_match,%s\n",
           total_stream_size, PLANE_COUNT * SYMBOLS_PER_PLANE,
           PLANE_COUNT * SYMBOLS_PER_PLANE, success ? "PASS" : "FAIL");
    return success;
}

static int validate_public_api(const Image *original,
                               const CycleResult *reference) {
    n148i_image_t input = {
        original->pixels,
        (uint32_t) original->width,
        (uint32_t) original->height,
        (size_t) original->width * 3
    };
    n148i_encode_options_t options;
    uint8_t *encoded = NULL;
    uint8_t *strided_encoded = NULL;
    uint8_t *strided_pixels = NULL;
    size_t encoded_size = 0;
    size_t strided_size = 0;
    n148i_image_t decoded = {0};
    n148i_image_info_t info = {0};
    int success = 0;

    n148i_encode_options_init(&options);
    options.quality = 50;
    options.chroma = N148I_CHROMA_420;
    options.optimize_huffman = 1;
    options.thread_count = 1;
    options.format_version = N148I_FORMAT_VERSION_1;
    options.feature_flags = 0;

    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&input, &options, &encoded, &encoded_size) !=
            N148I_OK ||
        encoded_size != (size_t) reference->stream_size ||
        memcmp(encoded, reference->stream, encoded_size) != 0 ||
        n148i_read_header(encoded, encoded_size, &info) != N148I_OK ||
        info.width != (uint32_t) original->width ||
        info.height != (uint32_t) original->height ||
        info.format_version != N148I_FORMAT_VERSION_1 ||
        info.quality != 50 || info.chroma != N148I_CHROMA_420 ||
        !info.optimized_huffman ||
        info.encoded_header_size + info.payload_size != encoded_size ||
        n148i_decode_memory(encoded, encoded_size, &decoded) != N148I_OK ||
        decoded.width != (uint32_t) reference->width ||
        decoded.height != (uint32_t) reference->height ||
        decoded.stride != (size_t) reference->width * 3 ||
        memcmp(decoded.pixels, reference->decoded.pixels,
               decoded.stride * decoded.height) != 0) {
        goto cleanup;
    }

    size_t tight_stride = (size_t) original->width * 3;
    size_t padded_stride = tight_stride + 7;
    strided_pixels = (uint8_t *) malloc(
        padded_stride * (size_t) original->height);
    if (!strided_pixels) goto cleanup;
    memset(strided_pixels, 0xa5, padded_stride * (size_t) original->height);
    for (int row = 0; row < original->height; row++) {
        memcpy(strided_pixels + (size_t) row * padded_stride,
               original->pixels + (size_t) row * tight_stride,
               tight_stride);
    }
    input.pixels = strided_pixels;
    input.stride = padded_stride;
    if (n148i_encode_memory(&input, &options, &strided_encoded,
                            &strided_size) != N148I_OK ||
        strided_size != encoded_size ||
        memcmp(strided_encoded, encoded, encoded_size) != 0 ||
        n148i_read_header(encoded, N148_FORMAT_1_HEADER_SIZE - 1, &info) !=
            N148I_ERROR_TRUNCATED_DATA) {
        goto cleanup;
    }
    success = 1;

cleanup:
    printf("comparison,public_api_vs_internal,scalar,1,2,%d,%d,%zu,%u,%u,"
           "%.12f,memory_stride_and_bitstream_identical,%s\n",
           original->width, original->height, encoded_size,
           info.payload_size, info.payload_size, reference->psnr,
           success ? "PASS" : "FAIL");
    free(strided_pixels);
    n148i_free_buffer(strided_encoded);
    n148i_free_image(&decoded);
    n148i_free_buffer(encoded);
    n148i_simd_force(N148I_SIMD_AUTO);
    return success;
}

static uint32_t validation_u32(const uint8_t *data) {
    return (uint32_t) data[0] | ((uint32_t) data[1] << 8) |
        ((uint32_t) data[2] << 16) | ((uint32_t) data[3] << 24);
}

static void validation_put_u32(uint8_t *data, uint32_t value) {
    data[0] = (uint8_t) value;
    data[1] = (uint8_t) (value >> 8);
    data[2] = (uint8_t) (value >> 16);
    data[3] = (uint8_t) (value >> 24);
}

static int validate_rans_entropy(const Image *original,
                               const CycleResult *format_1_reference) {
    n148i_image_t source = {
        original->pixels,
        (uint32_t) original->width,
        (uint32_t) original->height,
        (size_t) original->width * 3,
    };
    n148i_encode_options_t options;
    uint8_t *scalar = NULL, *vector = NULL, *parallel = NULL, *huffman = NULL;
    size_t scalar_size = 0, vector_size = 0, parallel_size = 0, huffman_size = 0;
    n148i_image_t decoded = {0}, huffman_decoded = {0};
    n148i_image_info_t info = {0};
    Plane y = {0}, cb = {0}, cr = {0};
    N148CoeffPlane expected[3] = {{0}}, recovered[3] = {{0}};
    int success = 0;

    n148i_encode_options_init(&options);
    options.quality = 50;
    options.chroma = N148I_CHROMA_420;
    options.thread_count = 1;
    options.format_version = N148I_FORMAT_VERSION_2;
    options.feature_flags = N148I_FEATURE_RANS;

    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &scalar, &scalar_size) != N148I_OK ||
        n148i_read_header(scalar, scalar_size, &info) != N148I_OK ||
        info.format_version != N148I_FORMAT_VERSION_2 ||
        info.feature_flags != N148I_FEATURE_RANS || info.effort != 3 ||
        info.encoded_header_size !=
            N148_EXTENDED_HEADER_SIZE + info.metadata_size ||
        info.encoded_header_size + info.payload_size != scalar_size ||
        scalar_size >= (size_t) format_1_reference->stream_size ||
        n148i_decode_memory(scalar, scalar_size, &decoded) != N148I_OK ||
        decoded.width != (uint32_t) format_1_reference->width ||
        decoded.height != (uint32_t) format_1_reference->height ||
        memcmp(decoded.pixels, format_1_reference->decoded.pixels,
               decoded.stride * decoded.height) != 0) goto cleanup;

    if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &vector, &vector_size) != N148I_OK ||
        vector_size != scalar_size || memcmp(vector, scalar, scalar_size) != 0)
        goto cleanup;
    options.thread_count = 4;
    if (n148i_simd_force(N148I_SIMD_AUTO) != N148I_OK ||
        n148i_encode_memory(&source, &options, &parallel, &parallel_size) != N148I_OK ||
        parallel_size != scalar_size || memcmp(parallel, scalar, scalar_size) != 0)
        goto cleanup;

    n148_cpu_force(N148_CPU_BASELINE);
    n148_set_thread_count(1);
    if (!split_channels((Image *) original, &y, &cb, &cr, CHROMA_420) ||
        !n148_quantize_planes(&y, &cb, &cr, 50, expected)) goto cleanup;
    uint16_t header_size = (uint16_t)(scalar[6] | ((uint16_t) scalar[7] << 8));
    uint32_t metadata_size = validation_u32(scalar + 28);
    uint32_t payload_size = validation_u32(scalar + 16);
    if (header_size != N148_EXTENDED_HEADER_SIZE + metadata_size ||
        !n148_decode_format_2_coefficients(
            scalar + N148_EXTENDED_HEADER_SIZE, metadata_size,
            scalar + header_size, payload_size,
            original->width, original->height, CHROMA_420,
            N148I_FEATURE_RANS, recovered, NULL, NULL, NULL, NULL))
        goto cleanup;
    for (int plane = 0; plane < 3; plane++) {
        if (expected[plane].count != recovered[plane].count ||
            memcmp(expected[plane].coefficients, recovered[plane].coefficients,
                   (size_t) expected[plane].count * 64 * sizeof(short)) != 0)
            goto cleanup;
    }

    options.feature_flags = 0;
    if (n148i_encode_memory(&source, &options, &huffman, &huffman_size) != N148I_OK ||
        n148i_read_header(huffman, huffman_size, &info) != N148I_OK ||
        info.format_version != N148I_FORMAT_VERSION_2 ||
        info.feature_flags != 0 ||
        n148i_decode_memory(huffman, huffman_size, &huffman_decoded) != N148I_OK ||
        memcmp(huffman_decoded.pixels, format_1_reference->decoded.pixels,
               huffman_decoded.stride * huffman_decoded.height) != 0 ||
        n148i_decode_memory(scalar, scalar_size - 1, &huffman_decoded) !=
            N148I_ERROR_TRUNCATED_DATA) goto cleanup;

    success = 1;

cleanup:
    printf("comparison,rans_vs_format_1_coefficients,scalar+AVX2,1+4,2,%d,%d,"
           "%zu,%u,%u,%.12f,coefficients_pixels_determinism_and_v1_decode,%s\n",
           original->width, original->height, scalar_size,
           info.payload_size, info.payload_size, format_1_reference->psnr,
           success ? "PASS" : "FAIL");
    n148i_free_buffer(scalar);
    n148i_free_buffer(vector);
    n148i_free_buffer(parallel);
    n148i_free_buffer(huffman);
    n148i_free_image(&decoded);
    n148i_free_image(&huffman_decoded);
    free_plane(&y); free_plane(&cb); free_plane(&cr);
    for (int plane = 0; plane < 3; plane++) {
        n148_free_coeff_plane(&expected[plane]);
        n148_free_coeff_plane(&recovered[plane]);
    }
    n148_cpu_force(-1);
    n148_set_thread_count(1);
    return success;
}

static int validate_context_modeling(const Image *original,
                               const CycleResult *format_1_reference) {
    n148i_image_t source = {
        original->pixels,
        (uint32_t) original->width,
        (uint32_t) original->height,
        (size_t) original->width * 3,
    };
    n148i_encode_options_t options;
    uint8_t *rans_only = NULL, *scalar = NULL, *vector = NULL, *parallel = NULL;
    size_t rans_only_size = 0, scalar_size = 0, vector_size = 0, parallel_size = 0;
    n148i_image_t decoded = {0};
    n148i_image_info_t info = {0};
    Plane y = {0}, cb = {0}, cr = {0};
    N148CoeffPlane expected[3] = {{0}}, recovered[3] = {{0}};
    N148ContextTrace encoder_trace = {0}, decoder_trace = {0};
    int success = 0;

    n148i_encode_options_init(&options);
    options.quality = 50;
    options.chroma = N148I_CHROMA_420;
    options.thread_count = 1;
    options.format_version = N148I_FORMAT_VERSION_2;
    options.feature_flags = N148I_FEATURE_RANS;

    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &rans_only, &rans_only_size) !=
            N148I_OK) goto cleanup;
    options.feature_flags |= N148I_FEATURE_CONTEXT;
    if (n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_OK || scalar_size >= rans_only_size ||
        n148i_read_header(scalar, scalar_size, &info) != N148I_OK ||
        info.feature_flags !=
            (N148I_FEATURE_RANS | N148I_FEATURE_CONTEXT) ||
        n148i_decode_memory(scalar, scalar_size, &decoded) != N148I_OK ||
        memcmp(decoded.pixels, format_1_reference->decoded.pixels,
               decoded.stride * decoded.height) != 0) goto cleanup;

    n148_cpu_force(N148_CPU_BASELINE);
    n148_set_thread_count(1);
    if (!split_channels((Image *) original, &y, &cb, &cr, CHROMA_420) ||
        !n148_quantize_planes(&y, &cb, &cr, 50, expected) ||
        !n148_trace_base_contexts(expected, original->width, original->height,
                                CHROMA_420,
                                N148I_FEATURE_RANS | N148I_FEATURE_CONTEXT,
                                &encoder_trace)) goto cleanup;
    uint16_t header_size = (uint16_t)(scalar[6] | ((uint16_t) scalar[7] << 8));
    uint32_t metadata_size = validation_u32(scalar + 28);
    uint32_t payload_size = validation_u32(scalar + 16);
    if (!n148_decode_format_2_coefficients(
            scalar + N148_EXTENDED_HEADER_SIZE, metadata_size,
            scalar + header_size, payload_size,
            original->width, original->height, CHROMA_420,
            N148I_FEATURE_RANS | N148I_FEATURE_CONTEXT,
            recovered, &decoder_trace, NULL, NULL, NULL) ||
        encoder_trace.symbol_count != decoder_trace.symbol_count ||
        encoder_trace.hash != decoder_trace.hash) goto cleanup;
    for (int plane = 0; plane < 3; plane++) {
        if (expected[plane].count != recovered[plane].count ||
            memcmp(expected[plane].coefficients, recovered[plane].coefficients,
                   (size_t) expected[plane].count * 64 * sizeof(short)) != 0)
            goto cleanup;
    }

    if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &vector, &vector_size) !=
            N148I_OK || vector_size != scalar_size ||
        memcmp(vector, scalar, scalar_size) != 0) goto cleanup;
    options.thread_count = 4;
    if (n148i_simd_force(N148I_SIMD_AUTO) != N148I_OK ||
        n148i_encode_memory(&source, &options, &parallel, &parallel_size) !=
            N148I_OK || parallel_size != scalar_size ||
        memcmp(parallel, scalar, scalar_size) != 0) goto cleanup;
    success = 1;

cleanup:
    printf("comparison,context_model_trace,scalar+AVX2,1+4,2,%d,%d,%zu,%u,%u,"
           "%.12f,encoder_decoder_model_hash_and_coefficients,%s\n",
           original->width, original->height, scalar_size,
           info.payload_size, info.payload_size, format_1_reference->psnr,
           success ? "PASS" : "FAIL");
    n148i_free_buffer(rans_only);
    n148i_free_buffer(scalar);
    n148i_free_buffer(vector);
    n148i_free_buffer(parallel);
    n148i_free_image(&decoded);
    free_plane(&y); free_plane(&cb); free_plane(&cr);
    for (int plane = 0; plane < 3; plane++) {
        n148_free_coeff_plane(&expected[plane]);
        n148_free_coeff_plane(&recovered[plane]);
    }
    n148_cpu_force(-1);
    n148_set_thread_count(1);
    return success;
}

static int uniform_plane(const Plane *plane) {
    if (!plane || !plane->data || plane->width <= 0 || plane->height <= 0)
        return 0;
    size_t count = (size_t) plane->width * (size_t) plane->height;
    for (size_t index = 1; index < count; index++)
        if (plane->data[index] != plane->data[0]) return 0;
    return 1;
}

static int validate_intra_uniform_drift(void) {
    enum { WIDTH = 257, HEIGHT = 193 };
    Plane source_y = create_plane(WIDTH, HEIGHT);
    Plane source_cb = create_plane(WIDTH, HEIGHT);
    Plane source_cr = create_plane(WIDTH, HEIGHT);
    Plane decoded_y = {0}, decoded_cb = {0}, decoded_cr = {0};
    N148CoeffPlane coefficients[3] = {{0}};
    uint8_t *modes = NULL;
    size_t mode_count = 0;
    int success = 0;
    if (!source_y.data || !source_cb.data || !source_cr.data) goto cleanup;
    memset(source_y.data, 173, (size_t) WIDTH * HEIGHT);
    memset(source_cb.data, 128, (size_t) WIDTH * HEIGHT);
    memset(source_cr.data, 128, (size_t) WIDTH * HEIGHT);
    if (!n148_intra_quantize_planes(&source_y, &source_cb, &source_cr, 30, 0,
                                    NULL, NULL, 0, 0, coefficients, &modes,
                                    &mode_count) ||
        !n148_intra_reconstruct_planes(coefficients, modes, mode_count,
                                       WIDTH, HEIGHT, 30, CHROMA_444, 0, NULL,
                                       NULL, 0,
                                       &decoded_y, &decoded_cb, &decoded_cr) ||
        !uniform_plane(&decoded_y) || !uniform_plane(&decoded_cb) ||
        !uniform_plane(&decoded_cr)) goto cleanup;
    success = 1;

cleanup:
    free_plane(&source_y); free_plane(&source_cb); free_plane(&source_cr);
    free_plane(&decoded_y); free_plane(&decoded_cb); free_plane(&decoded_cr);
    for (int plane = 0; plane < 3; plane++)
        n148_free_coeff_plane(&coefficients[plane]);
    free(modes);
    return success;
}

static int validate_reconstructed_intra(const Image *original) {
    n148i_image_t source = {
        original->pixels,
        (uint32_t) original->width,
        (uint32_t) original->height,
        (size_t) original->width * 3,
    };
    n148i_encode_options_t options;
    uint8_t *context_only = NULL, *scalar = NULL, *vector = NULL, *parallel = NULL;
    size_t context_only_size = 0, scalar_size = 0, vector_size = 0, parallel_size = 0;
    n148i_image_t scalar_decoded = {0}, vector_decoded = {0};
    n148i_image_t parallel_decoded = {0};
    n148i_image_info_t info = {0};
    Plane source_y = {0}, source_cb = {0}, source_cr = {0};
    Plane expected_y = {0}, expected_cb = {0}, expected_cr = {0};
    Image expected_rgb = {0};
    N148CoeffPlane expected[3] = {{0}}, recovered[3] = {{0}};
    N148ContextTrace encoder_trace = {0}, decoder_trace = {0};
    N148PredictionModes decoded_modes = {0};
    uint8_t *expected_modes = NULL;
    size_t expected_mode_count = 0;
    size_t mode_histogram[N148_INTRA_MODE_COUNT] = {0};
    int success = 0;

    n148i_encode_options_init(&options);
    options.quality = 50;
    options.chroma = N148I_CHROMA_420;
    options.thread_count = 1;
    options.format_version = N148I_FORMAT_VERSION_2;
    options.feature_flags = N148I_FEATURE_RANS | N148I_FEATURE_CONTEXT;
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &context_only, &context_only_size) !=
            N148I_OK) goto cleanup;
    options.feature_flags |= N148I_FEATURE_INTRA;
    if (n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_OK || scalar_size >= context_only_size ||
        n148i_read_header(scalar, scalar_size, &info) != N148I_OK ||
        info.feature_flags != (N148I_FEATURE_RANS | N148I_FEATURE_CONTEXT |
                               N148I_FEATURE_INTRA) ||
        n148i_decode_memory(scalar, scalar_size, &scalar_decoded) != N148I_OK)
        goto cleanup;

    n148_cpu_force(N148_CPU_BASELINE);
    n148_set_thread_count(1);
    if (!split_channels((Image *) original, &source_y, &source_cb, &source_cr,
                        CHROMA_420) ||
        !n148_intra_quantize_planes(&source_y, &source_cb, &source_cr, 50, 0,
                                    NULL, NULL, 0, 0, expected,
                                    &expected_modes,
                                    &expected_mode_count) ||
        !n148_trace_base_contexts(expected, original->width, original->height,
                                CHROMA_420,
                                N148I_FEATURE_RANS | N148I_FEATURE_CONTEXT |
                                    N148I_FEATURE_INTRA,
                                &encoder_trace)) goto cleanup;
    uint16_t header_size = (uint16_t)(scalar[6] | ((uint16_t) scalar[7] << 8));
    uint32_t metadata_size = validation_u32(scalar + 28);
    uint32_t payload_size = validation_u32(scalar + 16);
    if (!n148_decode_format_2_coefficients(
            scalar + N148_EXTENDED_HEADER_SIZE, metadata_size,
            scalar + header_size, payload_size,
            original->width, original->height, CHROMA_420,
            N148I_FEATURE_RANS | N148I_FEATURE_CONTEXT | N148I_FEATURE_INTRA,
            recovered, &decoder_trace, &decoded_modes, NULL, NULL) ||
        encoder_trace.symbol_count != decoder_trace.symbol_count ||
        encoder_trace.hash != decoder_trace.hash ||
        decoded_modes.count != expected_mode_count ||
        memcmp(decoded_modes.values, expected_modes, expected_mode_count) != 0)
        goto cleanup;
    for (int plane = 0; plane < 3; plane++) {
        if (expected[plane].count != recovered[plane].count ||
            memcmp(expected[plane].coefficients, recovered[plane].coefficients,
                   (size_t) expected[plane].count * 64 * sizeof(short)) != 0)
            goto cleanup;
    }
    for (size_t index = 0; index < expected_mode_count; index++) {
        if (expected_modes[index] >= N148_INTRA_MODE_COUNT) goto cleanup;
        mode_histogram[expected_modes[index]]++;
    }
    for (int mode = 0; mode < N148_INTRA_MODE_COUNT; mode++)
        if (mode_histogram[mode] == 0) goto cleanup;
    if (!n148_intra_reconstruct_planes(
            recovered, decoded_modes.values, decoded_modes.count,
            original->width, original->height, 50, CHROMA_420, 0, NULL, NULL,
            0, &expected_y, &expected_cb, &expected_cr) ||
        !merge_channels(&expected_y, &expected_cb, &expected_cr, 1,
                        &expected_rgb) ||
        scalar_decoded.width != (uint32_t) expected_rgb.width ||
        scalar_decoded.height != (uint32_t) expected_rgb.height ||
        memcmp(scalar_decoded.pixels, expected_rgb.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0 ||
        !validate_intra_uniform_drift()) goto cleanup;

    if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &vector, &vector_size) !=
            N148I_OK || vector_size != scalar_size ||
        memcmp(vector, scalar, scalar_size) != 0 ||
        n148i_decode_memory(vector, vector_size, &vector_decoded) != N148I_OK ||
        memcmp(vector_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;
    options.thread_count = 4;
    if (n148i_simd_force(N148I_SIMD_AUTO) != N148I_OK ||
        n148i_encode_memory(&source, &options, &parallel, &parallel_size) !=
            N148I_OK || parallel_size != scalar_size ||
        memcmp(parallel, scalar, scalar_size) != 0 ||
        n148i_decode_memory(parallel, parallel_size, &parallel_decoded) !=
            N148I_OK ||
        memcmp(parallel_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;
    success = 1;

cleanup:
    printf("comparison,reconstructed_intra_prediction,scalar+AVX2,1+4,2,%d,%d,%zu,%u,%u,"
           "0.0,modes_%zu_%zu_%zu_%zu_coefficients_and_uniform_drift,%s\n",
           original->width, original->height, scalar_size,
           info.payload_size, info.payload_size,
           mode_histogram[0], mode_histogram[1], mode_histogram[2],
           mode_histogram[3], success ? "PASS" : "FAIL");
    n148i_free_buffer(context_only); n148i_free_buffer(scalar);
    n148i_free_buffer(vector); n148i_free_buffer(parallel);
    n148i_free_image(&scalar_decoded); n148i_free_image(&vector_decoded);
    n148i_free_image(&parallel_decoded);
    free_plane(&source_y); free_plane(&source_cb); free_plane(&source_cr);
    free_plane(&expected_y); free_plane(&expected_cb); free_plane(&expected_cr);
    free_image(&expected_rgb);
    for (int plane = 0; plane < 3; plane++) {
        n148_free_coeff_plane(&expected[plane]);
        n148_free_coeff_plane(&recovered[plane]);
    }
    free(expected_modes);
    n148_prediction_modes_release(&decoded_modes);
    n148_cpu_force(-1);
    n148_set_thread_count(1);
    return success;
}

static int validate_perceptual_transform(void) {
    enum { LEVELS = 16, SAMPLE_COUNT = LEVELS * LEVELS * LEVELS };
    uint8_t *rgb = (uint8_t *) malloc(SAMPLE_COUNT * 3u);
    uint8_t *intensity = (uint8_t *) malloc(SAMPLE_COUNT);
    uint8_t *red_green = (uint8_t *) malloc(SAMPLE_COUNT);
    uint8_t *blue_yellow = (uint8_t *) malloc(SAMPLE_COUNT);
    int max_error = 0;
    uint8_t max_source[3] = {0}, max_reconstructed[3] = {0};
    double squared_error = 0.0;
    int success = 0;
    if (!rgb || !intensity || !red_green || !blue_yellow) goto cleanup;

    int sample = 0;
    for (int red = 0; red < LEVELS; red++) {
        for (int green = 0; green < LEVELS; green++) {
            for (int blue = 0; blue < LEVELS; blue++) {
                rgb[sample * 3] = (uint8_t)(red * 17);
                rgb[sample * 3 + 1] = (uint8_t)(green * 17);
                rgb[sample * 3 + 2] = (uint8_t)(blue * 17);
                sample++;
            }
        }
    }
    n148_perceptual_init();
    n148_rgb_to_perceptual(rgb, SAMPLE_COUNT, intensity, red_green,
                           blue_yellow);
    for (int index = 0; index < SAMPLE_COUNT; index++) {
        uint8_t reconstructed[3];
        n148_perceptual_to_rgb(
            intensity[index], (uint16_t) red_green[index] << 4,
            (uint16_t) blue_yellow[index] << 4, reconstructed);
        for (int channel = 0; channel < 3; channel++) {
            int error = (int) rgb[index * 3 + channel] -
                reconstructed[channel];
            int magnitude = error < 0 ? -error : error;
            if (magnitude > max_error) {
                max_error = magnitude;
                memcpy(max_source, rgb + index * 3, sizeof(max_source));
                memcpy(max_reconstructed, reconstructed,
                       sizeof(max_reconstructed));
            }
            squared_error += (double) error * error;
        }
    }
    double mse = squared_error / (SAMPLE_COUNT * 3.0);
    double psnr = mse == 0.0 ? 999.0 :
        10.0 * log10(255.0 * 255.0 / mse);
    /* The transform is lossy at its intentional 8-bit plane boundary. These
       limits freeze the measured conversion floor instead of pretending the
       opponent mapping is mathematically lossless. */
    success = max_error <= 16 && psnr >= 45.0;
    printf("comparison,perceptual_color_transform,scalar,1,0,16,16,0,0,0,"
           "%.12f,max_channel_error_%d_at_%u_%u_%u_to_%u_%u_%u_over_%d_"
           "rgb_samples,%s\n",
           psnr, max_error, max_source[0], max_source[1], max_source[2],
           max_reconstructed[0], max_reconstructed[1], max_reconstructed[2],
           SAMPLE_COUNT, success ? "PASS" : "FAIL");

cleanup:
    free(rgb);
    free(intensity);
    free(red_green);
    free(blue_yellow);
    return success;
}

static int validate_perceptual_color(const Image *original) {
    n148i_image_t source = {
        original->pixels,
        (uint32_t) original->width,
        (uint32_t) original->height,
        (size_t) original->width * 3,
    };
    n148i_encode_options_t options;
    uint8_t *scalar = NULL, *vector = NULL, *parallel = NULL;
    size_t scalar_size = 0, vector_size = 0, parallel_size = 0;
    n148i_image_t decoded = {0};
    n148i_image_info_t info = {0};
    size_t reported_size = 0;
    uint32_t features = N148I_FEATURE_RANS | N148I_FEATURE_CONTEXT |
        N148I_FEATURE_INTRA | N148I_FEATURE_PERCEPTUAL_COLOR;
    int success = 0;
    if (!validate_perceptual_transform()) goto cleanup;

    n148i_encode_options_init(&options);
    if (options.format_version == N148I_FORMAT_VERSION_2 &&
        (options.feature_flags & N148I_FEATURE_PERCEPTUAL_COLOR)) goto cleanup;
    options.quality = 50;
    options.thread_count = 1;
    options.format_version = N148I_FORMAT_VERSION_2;
    options.feature_flags = N148I_FEATURE_PERCEPTUAL_COLOR;
    if (n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;

    options.feature_flags = features;
    for (int chroma = N148I_CHROMA_444; chroma <= N148I_CHROMA_420;
         chroma++) {
        options.chroma = (n148i_chroma_t) chroma;
        options.thread_count = 1;
        if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
            n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
                N148I_OK ||
            n148i_read_header(scalar, scalar_size, &info) != N148I_OK ||
            info.feature_flags != features || (int) info.chroma != chroma ||
            n148i_decode_memory(scalar, scalar_size, &decoded) != N148I_OK ||
            decoded.width != (uint32_t) original->width ||
            decoded.height != (uint32_t) original->height) goto cleanup;
        n148i_free_image(&decoded);

        if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
            n148i_encode_memory(&source, &options, &vector, &vector_size) !=
                N148I_OK || vector_size != scalar_size ||
            memcmp(vector, scalar, scalar_size) != 0) goto cleanup;

        options.thread_count = 4;
        if (n148i_simd_force(N148I_SIMD_AUTO) != N148I_OK ||
            n148i_encode_memory(&source, &options, &parallel,
                                &parallel_size) != N148I_OK ||
            parallel_size != scalar_size ||
            memcmp(parallel, scalar, scalar_size) != 0) goto cleanup;
        if (chroma == N148I_CHROMA_420) reported_size = scalar_size;
        n148i_free_buffer(scalar); scalar = NULL;
        n148i_free_buffer(vector); vector = NULL;
        n148i_free_buffer(parallel); parallel = NULL;
    }

    const uint32_t independent_masks[] = {
        N148I_FEATURE_RANS | N148I_FEATURE_PERCEPTUAL_COLOR,
        N148I_FEATURE_RANS | N148I_FEATURE_CONTEXT |
            N148I_FEATURE_PERCEPTUAL_COLOR,
        N148I_FEATURE_RANS | N148I_FEATURE_INTRA |
            N148I_FEATURE_PERCEPTUAL_COLOR,
    };
    options.chroma = N148I_CHROMA_420;
    options.thread_count = 1;
    for (size_t index = 0;
         index < sizeof(independent_masks) / sizeof(independent_masks[0]);
         index++) {
        options.feature_flags = independent_masks[index];
        if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
            n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
                N148I_OK ||
            n148i_decode_memory(scalar, scalar_size, &decoded) != N148I_OK)
            goto cleanup;
        n148i_free_buffer(scalar); scalar = NULL;
        n148i_free_image(&decoded);
    }
    success = 1;

cleanup:
    printf("comparison,perceptual_color,scalar+AVX2,1+4,0+1+2,%d,%d,%zu,"
           "%u,%u,0.0,all_feature_combinations_rgb_roundtrip_and_"
           "determinism,%s\n",
           original->width, original->height, reported_size,
           info.payload_size, info.payload_size, success ? "PASS" : "FAIL");
    n148i_free_buffer(scalar);
    n148i_free_buffer(vector);
    n148i_free_buffer(parallel);
    n148i_free_image(&decoded);
    n148i_simd_force(N148I_SIMD_AUTO);
    return success;
}

static int validate_adaptive_chroma(const Image *original, int chroma,
                                    uint32_t features,
                                    size_t *reported_size,
                                    size_t level_histogram[4]) {
    int perceptual_color =
        (features & N148I_FEATURE_PERCEPTUAL_COLOR) != 0;
    n148i_image_t source = {
        original->pixels,
        (uint32_t) original->width,
        (uint32_t) original->height,
        (size_t) original->width * 3,
    };
    n148i_encode_options_t options;
    uint8_t *scalar = NULL, *vector = NULL, *parallel = NULL;
    uint8_t *corrupt_payload = NULL;
    size_t scalar_size = 0, vector_size = 0, parallel_size = 0;
    n148i_image_t decoded = {0}, vector_decoded = {0}, parallel_decoded = {0};
    n148i_image_info_t info = {0};
    Plane source_y = {0}, source_cb = {0}, source_cr = {0};
    Plane expected_y = {0}, expected_cb = {0}, expected_cr = {0};
    Image expected_rgb = {0};
    N148CoeffPlane expected[3] = {{0}}, recovered[3] = {{0}};
    N148CoeffPlane rejected[3] = {{0}};
    N148PredictionModes decoded_modes = {0};
    N148AdaptiveMap expected_map = {0}, decoded_map = {0};
    uint8_t *expected_modes = NULL;
    size_t expected_mode_count = 0;
    int success = 0;

    n148i_encode_options_init(&options);
    options.quality = 50;
    options.chroma = (n148i_chroma_t) chroma;
    options.thread_count = 1;
    options.format_version = N148I_FORMAT_VERSION_2;
    options.feature_flags = features;
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_OK ||
        n148i_read_header(scalar, scalar_size, &info) != N148I_OK ||
        info.feature_flags != features || (int) info.chroma != chroma ||
        n148i_decode_memory(scalar, scalar_size, &decoded) != N148I_OK)
        goto cleanup;

    n148_cpu_force(N148_CPU_BASELINE);
    n148_set_thread_count(1);
    if (!n148_split_channels_ex(
            (Image *) original, &source_y, &source_cb, &source_cr, chroma,
            perceptual_color) ||
        !n148_adaptive_map_build(&source_y, &expected_map) ||
        !n148_intra_quantize_planes(
            &source_y, &source_cb, &source_cr, 50, perceptual_color,
            &expected_map, NULL, 0, 0,
            expected, &expected_modes, &expected_mode_count)) goto cleanup;

    uint16_t header_size =
        (uint16_t)(scalar[6] | ((uint16_t) scalar[7] << 8));
    uint32_t metadata_size = validation_u32(scalar + 28);
    uint32_t payload_size = validation_u32(scalar + 16);
    const uint8_t *payload = scalar + header_size;
    if (payload_size < 24 || payload[0] != 3 || payload[1] != 3 ||
        payload[2] != 1 || payload[3] != 1 ||
        validation_u32(payload + 20) != expected_map.count ||
        !n148_decode_format_2_coefficients(
            scalar + N148_EXTENDED_HEADER_SIZE, metadata_size,
            payload, payload_size, original->width, original->height, chroma,
            features, recovered, NULL, &decoded_modes, &decoded_map, NULL) ||
        decoded_modes.count != expected_mode_count ||
        memcmp(decoded_modes.values, expected_modes,
               expected_mode_count) != 0 ||
        decoded_map.count != expected_map.count ||
        decoded_map.columns != expected_map.columns ||
        decoded_map.rows != expected_map.rows ||
        memcmp(decoded_map.levels, expected_map.levels,
               expected_map.count) != 0) goto cleanup;

    for (int plane = 0; plane < 3; plane++) {
        if (expected[plane].count != recovered[plane].count ||
            memcmp(expected[plane].coefficients, recovered[plane].coefficients,
                   (size_t) expected[plane].count * 64 * sizeof(short)) != 0)
            goto cleanup;
    }
    if (!n148_intra_reconstruct_planes(
            recovered, decoded_modes.values, decoded_modes.count,
            original->width, original->height, 50, chroma, perceptual_color,
            &decoded_map, NULL, 0,
            &expected_y, &expected_cb, &expected_cr) ||
        !n148_merge_channels_ex(&expected_y, &expected_cb, &expected_cr, 1,
                                perceptual_color, &expected_rgb) ||
        decoded.width != (uint32_t) expected_rgb.width ||
        decoded.height != (uint32_t) expected_rgb.height ||
        memcmp(decoded.pixels, expected_rgb.pixels,
               decoded.stride * decoded.height) != 0) goto cleanup;

    for (size_t index = 0; index < expected_map.count; index++) {
        if (expected_map.levels[index] >= N148_AQ_LEVEL_COUNT) goto cleanup;
        level_histogram[expected_map.levels[index]]++;
    }

    if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &vector, &vector_size) !=
            N148I_OK || vector_size != scalar_size ||
        memcmp(vector, scalar, scalar_size) != 0 ||
        n148i_decode_memory(vector, vector_size, &vector_decoded) != N148I_OK ||
        memcmp(vector_decoded.pixels, decoded.pixels,
               decoded.stride * decoded.height) != 0) goto cleanup;
    options.thread_count = 4;
    if (n148i_simd_force(N148I_SIMD_AUTO) != N148I_OK ||
        n148i_encode_memory(&source, &options, &parallel, &parallel_size) !=
            N148I_OK || parallel_size != scalar_size ||
        memcmp(parallel, scalar, scalar_size) != 0 ||
        n148i_decode_memory(parallel, parallel_size, &parallel_decoded) !=
            N148I_OK ||
        memcmp(parallel_decoded.pixels, decoded.pixels,
               decoded.stride * decoded.height) != 0) goto cleanup;

    corrupt_payload = (uint8_t *) malloc(payload_size);
    if (!corrupt_payload) goto cleanup;
    memcpy(corrupt_payload, payload, payload_size);
    corrupt_payload[20] ^= 1u;
    if (n148_decode_format_2_coefficients(
            scalar + N148_EXTENDED_HEADER_SIZE, metadata_size,
            corrupt_payload, payload_size, original->width, original->height,
            chroma, features, rejected, NULL, NULL, NULL, NULL)) goto cleanup;

    if (reported_size) *reported_size = scalar_size;
    success = 1;

cleanup:
    n148i_free_buffer(scalar); n148i_free_buffer(vector);
    n148i_free_buffer(parallel);
    n148i_free_image(&decoded); n148i_free_image(&vector_decoded);
    n148i_free_image(&parallel_decoded);
    free(corrupt_payload);
    free_plane(&source_y); free_plane(&source_cb); free_plane(&source_cr);
    free_plane(&expected_y); free_plane(&expected_cb); free_plane(&expected_cr);
    free_image(&expected_rgb);
    free(expected_modes);
    n148_prediction_modes_release(&decoded_modes);
    n148_adaptive_map_release(&expected_map);
    n148_adaptive_map_release(&decoded_map);
    for (int plane = 0; plane < 3; plane++) {
        n148_free_coeff_plane(&expected[plane]);
        n148_free_coeff_plane(&recovered[plane]);
        n148_free_coeff_plane(&rejected[plane]);
    }
    n148_cpu_force(-1);
    n148_set_thread_count(1);
    return success;
}

static int validate_adaptive_quantization(const Image *original) {
    const uint32_t features = N148I_FEATURE_RANS | N148I_FEATURE_CONTEXT |
        N148I_FEATURE_INTRA | N148I_FEATURE_ADAPTIVE_QUANT;
    n148i_image_t source = {
        original->pixels,
        (uint32_t) original->width,
        (uint32_t) original->height,
        (size_t) original->width * 3,
    };
    n148i_encode_options_t options;
    uint8_t *encoded = NULL;
    size_t encoded_size = 0;
    size_t reported_size = 0;
    size_t level_histogram[N148_AQ_LEVEL_COUNT] = {0};
    size_t combined_histogram[N148_AQ_LEVEL_COUNT] = {0};
    Image level_fixture = {0};
    int success = 0;

    n148i_encode_options_init(&options);
    options.format_version = N148I_FORMAT_VERSION_2;
    options.feature_flags = N148I_FEATURE_ADAPTIVE_QUANT;
    if (n148i_encode_memory(&source, &options, &encoded, &encoded_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;
    options.feature_flags = N148I_FEATURE_RANS | N148I_FEATURE_ADAPTIVE_QUANT;
    if (n148i_encode_memory(&source, &options, &encoded, &encoded_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;

    for (int chroma = N148I_CHROMA_444; chroma <= N148I_CHROMA_420;
         chroma++) {
        size_t size = 0;
        if (!validate_adaptive_chroma(original, chroma, features, &size,
                                      level_histogram)) goto cleanup;
        if (chroma == N148I_CHROMA_420) reported_size = size;
    }
    level_fixture.width = 64;
    level_fixture.height = 16;
    level_fixture.pixels = (uint8_t *) malloc(64u * 16u * 3u);
    if (!level_fixture.pixels) goto cleanup;
    const int amplitudes[N148_AQ_LEVEL_COUNT] = {0, 1, 3, 10};
    for (int y = 0; y < level_fixture.height; y++) {
        for (int x = 0; x < level_fixture.width; x++) {
            int amplitude = amplitudes[x / N148_AQ_REGION_SIZE];
            int value = 128 + (((x + y) & 1) ? amplitude : -amplitude);
            size_t pixel = ((size_t) y * 64u + (size_t) x) * 3u;
            level_fixture.pixels[pixel] = (uint8_t) value;
            level_fixture.pixels[pixel + 1] = (uint8_t) value;
            level_fixture.pixels[pixel + 2] = (uint8_t) value;
        }
    }
    if (!validate_adaptive_chroma(&level_fixture, N148I_CHROMA_420, features,
                                  NULL, level_histogram)) goto cleanup;
    for (int level = 0; level < N148_AQ_LEVEL_COUNT; level++)
        if (level_histogram[level] == 0) goto cleanup;
    const uint32_t combined_features =
        features | N148I_FEATURE_PERCEPTUAL_COLOR;
    for (int chroma = N148I_CHROMA_444; chroma <= N148I_CHROMA_420;
         chroma++) {
        if (!validate_adaptive_chroma(original, chroma, combined_features,
                                      NULL, combined_histogram)) goto cleanup;
    }
    success = 1;

cleanup:
    printf("comparison,adaptive_quantization,scalar+AVX2,1+4,0+1+2,%d,%d,%zu,"
           "0,0,0.0,levels_%zu_%zu_%zu_%zu_map_coefficients_corruption_and_"
           "perceptual_combination_determinism,%s\n",
           original->width, original->height, reported_size,
           level_histogram[0], level_histogram[1], level_histogram[2],
           level_histogram[3], success ? "PASS" : "FAIL");
    n148i_free_buffer(encoded);
    free_image(&level_fixture);
    n148i_simd_force(N148I_SIMD_AUTO);
    return success;
}

static int validate_transform4_dispatch(void) {
    if (n148_cpu_detected_level() < N148_CPU_AVX2) return 1;
    const int32_t limits[] = {255, 8191, 8192, 32767, 8388607, INT32_MAX};
    uint32_t random = 1;
    int previous_cpu = n148_cpu_level();
    int success = 1;
    for (unsigned range = 0; range < sizeof(limits) / sizeof(limits[0]) && success;
         range++) {
        for (int trial = 0; trial < 128 && success; trial++) {
            int32_t input[16], scalar[16], vector[16], aliased[16];
            for (int i = 0; i < 16; i++) {
                random = random * 1664525u + 1013904223u;
                int32_t value = (int32_t)(random % (uint32_t)limits[range]);
                if (trial < 16) value = i == trial ? limits[range] : 0;
                else if (trial == 16) value = limits[range];
                else if (trial == 17) value = -limits[range];
                else if (trial == 18) value = (i & 1) ? limits[range] : -limits[range];
                else if (random & 0x80000000u) value = -value;
                if (limits[range] == INT32_MAX) {
                    if (trial == 19) value = INT32_MIN;
                    else if (trial == 20)
                        value = (i & 1) ? INT32_MAX : INT32_MIN;
                    else if (trial >= 21 && trial < 37)
                        value = i == trial - 21 ? INT32_MIN : 0;
                }
                input[i] = value;
            }
            for (int inverse = 0; inverse < 2 && success; inverse++) {
                n148_cpu_force(N148_CPU_BASELINE);
                int scalar_ok = inverse ? n148_variable_inverse(input, 4, scalar) :
                    n148_variable_forward(input, 4, scalar);
                n148_cpu_force(N148_CPU_AVX2);
                int vector_ok = inverse ? n148_variable_inverse(input, 4, vector) :
                    n148_variable_forward(input, 4, vector);
                memcpy(aliased, input, sizeof(input));
                int alias_ok = inverse ? n148_variable_inverse(aliased, 4, aliased) :
                    n148_variable_forward(aliased, 4, aliased);
                success = scalar_ok == vector_ok && scalar_ok == alias_ok &&
                    (!scalar_ok || (!memcmp(scalar, vector, sizeof(scalar)) &&
                                    !memcmp(scalar, aliased, sizeof(scalar))));
            }
        }
    }
    n148_cpu_force(previous_cpu);
    return success;
}

static int validate_large_forward_dispatch(void) {
    if (n148_cpu_detected_level() < N148_CPU_AVX2) return 1;
    const int sizes[] = {16, 32};
    const int limits[] = {255, 8191, 32767, 32768, 65535, 8388607};
    int previous_cpu = n148_cpu_level();
    uint32_t random = 0x1487115u;
    int success = 1;
    for (int ns = 0; ns < 2 && success; ns++) {
        int size = sizes[ns], count = size * size;
        for (unsigned range = 0; range < sizeof(limits)/sizeof(limits[0]) && success; range++) {
            for (int trial = 0; trial < 128 && success; trial++) {
                int32_t input[1024], scalar[1024], vector[1024], alias[1024];
                for (int i = 0; i < count; i++) {
                    random = random * 1664525u + 1013904223u;
                    int value = (int)(random % (uint32_t)(limits[range] + 1));
                    if (random & 0x80000000u) value = -value;
                    if (trial < 64) value = i == trial ? limits[range] : 0;
                    else if (trial == 64) value = limits[range];
                    else if (trial == 65) value = -limits[range];
                    else if (trial == 66) value = (i & 1) ? limits[range] : -limits[range];
                    input[i] = value;
                }
                n148_cpu_force(N148_CPU_BASELINE);
                int a = n148_variable_forward(input, size, scalar);
                n148_cpu_force(N148_CPU_AVX2);
                int b = n148_variable_forward(input, size, vector);
                memcpy(alias, input, (size_t)count * sizeof(*input));
                int c = n148_variable_forward(alias, size, alias);
                success = a == b && a == c && (!a ||
                    (!memcmp(scalar,vector,(size_t)count*sizeof(*scalar)) &&
                     !memcmp(scalar,alias,(size_t)count*sizeof(*scalar))));
            }
        }
    }
    n148_cpu_force(previous_cpu);
    return success;
}

static int validate_variable_transform_core(void) {
    if (!validate_transform4_dispatch() || !validate_large_forward_dispatch()) return 0;
    static const uint64_t expected_matrix_hash = 0xb17cb6d69247a7e9ull;
    uint8_t seen8[64] = {0};
    for (int position = 0; position < 64; position++) {
        int natural = ZIGZAG[position];
        if (natural < 0 || natural >= 64 || seen8[natural]) return 0;
        seen8[natural] = 1;
    }
    for (int size_index = 0; size_index < 2; size_index++) {
        int size = size_index == 0 ? 4 : 16;
        uint8_t seen[16 * 16] = {0};
        int32_t input[16 * 16], coefficients[16 * 16];
        int32_t reconstructed[16 * 16];
        for (int position = 0; position < size * size; position++) {
            int natural = n148_variable_zigzag(size, position);
            if (natural < 0 || natural >= size * size || seen[natural])
                return 0;
            seen[natural] = 1;
            input[position] = (int32_t)(((position * 37 +
                (position / size) * 13) % 511) - 255);
        }
        if (!n148_variable_forward(input, size, coefficients) ||
            !n148_variable_inverse(coefficients, size, reconstructed))
            return 0;
        for (int position = 0; position < size * size; position++) {
            int difference = reconstructed[position] - input[position];
            if (difference < -1 || difference > 1) return 0;
        }
    }
    return n148_variable_zigzag(8, 0) == -1 &&
        n148_variable_transform_matrix_hash() == expected_matrix_hash;
}

static uint32_t sparse16_random(uint32_t *state) {
    *state ^= *state << 13;
    *state ^= *state >> 17;
    *state ^= *state << 5;
    return *state;
}

static int validate_sparse16_inverse(void) {
    uint32_t random_state = 1;
    int success = 1;
    int detected = n148_cpu_detected_level();
    for (int cpu = 0; cpu < 2 && success; cpu++) {
        if (cpu && detected < N148_CPU_AVX2) break;
        n148_cpu_force(cpu ? N148_CPU_AVX2 : N148_CPU_BASELINE);
        for (int trial = 0; trial < 500 && success; trial++) {
            int32_t input[16 * 16] = {0};
            int32_t full[16 * 16], sparse[16 * 16];
            uint32_t rows = 0, columns = 0;
            for (int sample = 0; sample < trial % 65; sample++) {
                int y = (int) (sparse16_random(&random_state) % 16u);
                int x = (int) (sparse16_random(&random_state) % 16u);
                input[y * 16 + x] =
                    (int32_t)(sparse16_random(&random_state) % 200001u) -
                    100000;
            }
            for (int y = 0; y < 16; y++) {
                for (int x = 0; x < 16; x++) {
                    if (input[y * 16 + x]) {
                        rows |= 1u << y;
                        columns |= 1u << x;
                    }
                }
            }
            int full_ok = n148_variable_inverse(input, 16, full);
            int sparse_ok = n148_variable_inverse_sparse16(
                input, rows, columns, sparse);
            if (full_ok != sparse_ok ||
                (full_ok && memcmp(full, sparse, sizeof(full)))) success = 0;
        }
    }
    n148_cpu_force(N148_CPU_BASELINE);
    return success;
}

static int validate_forced_transform_strategy(uint8_t strategy) {
    enum { WIDTH = 32, HEIGHT = 32 };
    Plane source[3] = {{0}}, decoded[3] = {{0}};
    N148CoeffPlane coefficients[3] = {{0}};
    N148TransformMap map = {0};
    uint8_t *modes = NULL;
    size_t mode_count = 0;
    int success = 0;
    for (int plane = 0; plane < 3; plane++) {
        source[plane] = create_plane(WIDTH, HEIGHT);
        if (!source[plane].data) goto cleanup;
        for (int y = 0; y < HEIGHT; y++) {
            for (int x = 0; x < WIDTH; x++) {
                int value = plane == 0 ?
                    (x * 7 + y * 11 + ((x ^ y) & 7) * 9) & 255 :
                    128 + (((x + y + plane) & 3) - 1);
                source[plane].data[y * WIDTH + x] = (uint8_t) value;
            }
        }
    }
    if (!n148_transform_map_allocate(WIDTH, HEIGHT, CHROMA_444, &map))
        goto cleanup;
    memset(map.strategies, strategy, map.count);
    if (!n148_transform_map_validate(&map) ||
        !n148_intra_quantize_planes(
            &source[0], &source[1], &source[2], 50, 0, NULL, &map,
            0, 0, coefficients, &modes, &mode_count)) goto cleanup;
    if (strategy == N148_TRANSFORM_DCT16) {
        int blocks_x = map.blocks_x[0];
        if (modes[0] != modes[1] || modes[0] != modes[blocks_x] ||
            modes[0] != modes[blocks_x + 1]) goto cleanup;
        modes[1] = (uint8_t)((modes[1] + 1) % N148_INTRA_MODE_COUNT);
        if (n148_intra_reconstruct_planes(
                coefficients, modes, mode_count, WIDTH, HEIGHT, 50,
                CHROMA_444, 0, NULL, &map, 0,
                &decoded[0], &decoded[1], &decoded[2])) goto cleanup;
        modes[1] = modes[0];
    }
    if (!n148_intra_reconstruct_planes(
            coefficients, modes, mode_count, WIDTH, HEIGHT, 50,
            CHROMA_444, 0, NULL, &map, 0,
            &decoded[0], &decoded[1], &decoded[2])) goto cleanup;
    for (int plane = 0; plane < 3; plane++) {
        if (!decoded[plane].data || decoded[plane].width != WIDTH ||
            decoded[plane].height != HEIGHT) goto cleanup;
    }
    success = 1;

cleanup:
    for (int plane = 0; plane < 3; plane++) {
        free_plane(&source[plane]);
        free_plane(&decoded[plane]);
        n148_free_coeff_plane(&coefficients[plane]);
    }
    free(modes);
    n148_transform_map_release(&map);
    return success;
}

static int validate_transform_edge_rejection(void) {
    N148TransformMap map = {0};
    if (!n148_transform_map_allocate(17, 17, CHROMA_444, &map)) return 0;
    size_t edge = (size_t)(map.rows[0] - 1) * (size_t) map.columns[0] +
        (size_t)(map.columns[0] - 1);
    map.strategies[edge] = N148_TRANSFORM_DCT16;
    int rejected = !n148_transform_map_validate(&map);
    n148_transform_map_release(&map);
    return rejected;
}

static int transform_maps_equal(const N148TransformMap *first,
                                const N148TransformMap *second) {
    return first && second && first->count == second->count &&
        memcmp(first->plane_offsets, second->plane_offsets,
               sizeof(first->plane_offsets)) == 0 &&
        memcmp(first->columns, second->columns, sizeof(first->columns)) == 0 &&
        memcmp(first->rows, second->rows, sizeof(first->rows)) == 0 &&
        memcmp(first->blocks_x, second->blocks_x,
               sizeof(first->blocks_x)) == 0 &&
        memcmp(first->blocks_y, second->blocks_y,
               sizeof(first->blocks_y)) == 0 &&
        memcmp(first->strategies, second->strategies, first->count) == 0;
}

static int validate_variable_transforms(const Image *original) {
    const uint32_t features = N148I_FEATURE_RANS | N148I_FEATURE_CONTEXT |
        N148I_FEATURE_INTRA | N148I_FEATURE_VARIABLE_TRANSFORM;
    n148i_image_t source = {
        original->pixels, (uint32_t) original->width,
        (uint32_t) original->height, (size_t) original->width * 3,
    };
    n148i_encode_options_t options;
    uint8_t *scalar = NULL, *vector = NULL, *parallel = NULL;
    uint8_t *corrupt_payload = NULL, *combined = NULL;
    size_t scalar_size = 0, vector_size = 0, parallel_size = 0;
    size_t combined_size = 0;
    n148i_image_t decoded = {0}, vector_decoded = {0};
    n148i_image_t parallel_decoded = {0}, combined_decoded = {0};
    n148i_image_info_t info = {0};
    Plane source_y = {0}, source_cb = {0}, source_cr = {0};
    Plane expected_y = {0}, expected_cb = {0}, expected_cr = {0};
    Image expected_rgb = {0};
    N148CoeffPlane expected[3] = {{0}}, recovered[3] = {{0}};
    N148CoeffPlane rejected[3] = {{0}};
    N148PredictionModes decoded_modes = {0};
    N148TransformMap expected_map = {0}, decoded_map = {0};
    uint8_t *expected_modes = NULL;
    size_t expected_mode_count = 0;
    size_t histogram[N148_TRANSFORM_STRATEGY_COUNT] = {0};
    int success = 0;

    n148i_encode_options_init(&options);
    options.format_version = N148I_FORMAT_VERSION_2;
    options.quality = 50;
    options.chroma = N148I_CHROMA_420;
    options.thread_count = 1;
    options.feature_flags = N148I_FEATURE_VARIABLE_TRANSFORM;
    if (n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;
    options.feature_flags = N148I_FEATURE_RANS |
        N148I_FEATURE_VARIABLE_TRANSFORM;
    if (n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;
    options.feature_flags = features;
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_OK ||
        n148i_read_header(scalar, scalar_size, &info) != N148I_OK ||
        info.feature_flags != features || info.format_version != 2 ||
        n148i_decode_memory(scalar, scalar_size, &decoded) != N148I_OK)
        goto cleanup;

    n148_cpu_force(N148_CPU_BASELINE);
    n148_set_thread_count(1);
    if (!split_channels((Image *) original, &source_y, &source_cb, &source_cr,
                        CHROMA_420) ||
        !n148_transform_map_build(
            &source_y, &source_cb, &source_cr, &expected_map) ||
        !n148_intra_quantize_planes(
            &source_y, &source_cb, &source_cr, 50, 0, NULL, &expected_map,
            0, 0, expected, &expected_modes, &expected_mode_count))
        goto cleanup;

    uint16_t header_size =
        (uint16_t)(scalar[6] | ((uint16_t) scalar[7] << 8));
    uint32_t metadata_size = validation_u32(scalar + 28);
    uint32_t payload_size = validation_u32(scalar + 16);
    const uint8_t *payload = scalar + header_size;
    if (payload_size < 24 || payload[0] != 4 || payload[1] != 3 ||
        payload[2] != 1 || payload[3] != 2 ||
        validation_u32(payload + 20) != expected_map.count ||
        !n148_decode_format_2_coefficients(
            scalar + N148_EXTENDED_HEADER_SIZE, metadata_size,
            payload, payload_size, original->width, original->height,
            CHROMA_420, features, recovered, NULL, &decoded_modes, NULL,
            &decoded_map) ||
        decoded_modes.count != expected_mode_count ||
        memcmp(decoded_modes.values, expected_modes,
               expected_mode_count) != 0 ||
        !transform_maps_equal(&expected_map, &decoded_map)) goto cleanup;
    for (int plane = 0; plane < 3; plane++) {
        if (expected[plane].count != recovered[plane].count ||
            memcmp(expected[plane].coefficients, recovered[plane].coefficients,
                   (size_t) expected[plane].count * 64 * sizeof(short)) != 0)
            goto cleanup;
    }
    if (!n148_intra_reconstruct_planes(
            recovered, decoded_modes.values, decoded_modes.count,
            original->width, original->height, 50, CHROMA_420, 0, NULL,
            &decoded_map, 0, &expected_y, &expected_cb, &expected_cr) ||
        !merge_channels(&expected_y, &expected_cb, &expected_cr, 1,
                        &expected_rgb) ||
        decoded.width != (uint32_t) expected_rgb.width ||
        decoded.height != (uint32_t) expected_rgb.height ||
        memcmp(decoded.pixels, expected_rgb.pixels,
               decoded.stride * decoded.height) != 0) goto cleanup;
    for (size_t index = 0; index < expected_map.count; index++) {
        if (expected_map.strategies[index] >=
            N148_TRANSFORM_STRATEGY_COUNT) goto cleanup;
        histogram[expected_map.strategies[index]]++;
    }

    if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &vector, &vector_size) !=
            N148I_OK || vector_size != scalar_size ||
        memcmp(vector, scalar, scalar_size) != 0 ||
        n148i_decode_memory(vector, vector_size, &vector_decoded) != N148I_OK ||
        memcmp(vector_decoded.pixels, decoded.pixels,
               decoded.stride * decoded.height) != 0) goto cleanup;
    options.thread_count = 4;
    if (n148i_simd_force(N148I_SIMD_AUTO) != N148I_OK ||
        n148i_encode_memory(&source, &options, &parallel, &parallel_size) !=
            N148I_OK || parallel_size != scalar_size ||
        memcmp(parallel, scalar, scalar_size) != 0 ||
        n148i_decode_memory(parallel, parallel_size, &parallel_decoded) !=
            N148I_OK ||
        memcmp(parallel_decoded.pixels, decoded.pixels,
               decoded.stride * decoded.height) != 0) goto cleanup;

    corrupt_payload = (uint8_t *) malloc(payload_size);
    if (!corrupt_payload) goto cleanup;
    memcpy(corrupt_payload, payload, payload_size);
    corrupt_payload[20] ^= 1u;
    if (n148_decode_format_2_coefficients(
            scalar + N148_EXTENDED_HEADER_SIZE, metadata_size,
            corrupt_payload, payload_size, original->width, original->height,
            CHROMA_420, features, rejected, NULL, NULL, NULL, NULL))
        goto cleanup;

    const uint32_t combinations[] = {
        features | N148I_FEATURE_ADAPTIVE_QUANT,
        features | N148I_FEATURE_PERCEPTUAL_COLOR,
        features | N148I_FEATURE_ADAPTIVE_QUANT |
            N148I_FEATURE_PERCEPTUAL_COLOR,
    };
    options.thread_count = 1;
    for (size_t index = 0;
         index < sizeof(combinations) / sizeof(combinations[0]); index++) {
        options.feature_flags = combinations[index];
        if (n148i_encode_memory(&source, &options, &combined,
                                &combined_size) != N148I_OK ||
            n148i_decode_memory(combined, combined_size,
                                &combined_decoded) != N148I_OK) goto cleanup;
        n148i_free_buffer(combined); combined = NULL;
        n148i_free_image(&combined_decoded);
    }
    if (!validate_variable_transform_core() ||
        !validate_sparse16_inverse() ||
        !validate_forced_transform_strategy(N148_TRANSFORM_DCT4) ||
        !validate_forced_transform_strategy(N148_TRANSFORM_DCT8) ||
        !validate_forced_transform_strategy(N148_TRANSFORM_DCT16) ||
        !validate_transform_edge_rejection()) goto cleanup;
    success = 1;

cleanup:
    printf("comparison,variable_transform,scalar+AVX2,1+4,2,%d,%d,%zu,"
           "0,0,0.0,strategies_%zu_%zu_%zu_q14_hash_%016llx_forced_sizes_"
           "edge_count_and_combination_rejection,%s\n",
           original->width, original->height, scalar_size,
           histogram[0], histogram[1], histogram[2],
           (unsigned long long) n148_variable_transform_matrix_hash(),
           success ? "PASS" : "FAIL");
    n148i_free_buffer(scalar); n148i_free_buffer(vector);
    n148i_free_buffer(parallel); n148i_free_buffer(combined);
    n148i_free_image(&decoded); n148i_free_image(&vector_decoded);
    n148i_free_image(&parallel_decoded); n148i_free_image(&combined_decoded);
    free(corrupt_payload); free(expected_modes);
    free_plane(&source_y); free_plane(&source_cb); free_plane(&source_cr);
    free_plane(&expected_y); free_plane(&expected_cb); free_plane(&expected_cr);
    free_image(&expected_rgb);
    n148_prediction_modes_release(&decoded_modes);
    n148_transform_map_release(&expected_map);
    n148_transform_map_release(&decoded_map);
    for (int plane = 0; plane < 3; plane++) {
        n148_free_coeff_plane(&expected[plane]);
        n148_free_coeff_plane(&recovered[plane]);
        n148_free_coeff_plane(&rejected[plane]);
    }
    n148i_simd_force(N148I_SIMD_AUTO);
    n148_cpu_force(-1);
    n148_set_thread_count(1);
    return success;
}

static int validate_rdo_core(uint32_t *changed) {
    float ideal_levels[64] = {0.0f};
    double unit_energy[64];
    short coefficients[64] = {0};
    for (int position = 0; position < 64; position++)
        unit_energy[position] = 1.0 + (position & 3) * 0.25;
    ideal_levels[0] = 5.0f;
    ideal_levels[1] = 0.55f;
    ideal_levels[7] = -1.6f;
    ideal_levels[31] = 0.7f;
    coefficients[0] = 5;
    coefficients[1] = 1;
    coefficients[7] = -2;
    coefficients[31] = 1;
    short dc = coefficients[0];
    N148RdoResult result;
    double before = n148_rdo_proxy_cost(
        ideal_levels, unit_energy, coefficients, 4.0);
    if (!n148_rdo_refine_coefficients(
            ideal_levels, unit_energy, 4.0, 5, coefficients, &result) ||
        coefficients[0] != dc || result.changed_coefficients == 0 ||
        result.output_nonzeros > result.input_nonzeros ||
        result.output_cost > result.input_cost + 1e-9 ||
        fabs(result.input_cost - before) > 1e-9 ||
        fabs(result.output_cost - n148_rdo_proxy_cost(
            ideal_levels, unit_energy, coefficients, 4.0)) > 1e-9 ||
        n148_rdo_refine_coefficients(
            ideal_levels, unit_energy, -1.0, 5, coefficients, NULL)) return 0;
    if (changed) *changed = result.changed_coefficients;
    return 1;
}

static int validate_rate_distortion_optimization(const Image *original) {
    const uint32_t base_features = N148I_FEATURE_RANS |
        N148I_FEATURE_CONTEXT | N148I_FEATURE_INTRA;
    const uint32_t rdo_features = base_features | N148I_FEATURE_RDO;
    const uint32_t combined_features = rdo_features |
        N148I_FEATURE_PERCEPTUAL_COLOR | N148I_FEATURE_ADAPTIVE_QUANT |
        N148I_FEATURE_VARIABLE_TRANSFORM;
    n148i_image_t source = {
        original->pixels, (uint32_t) original->width,
        (uint32_t) original->height, (size_t) original->width * 3,
    };
    n148i_encode_options_t options;
    uint8_t *baseline = NULL, *effort0 = NULL, *scalar = NULL;
    uint8_t *vector = NULL, *parallel = NULL, *maximum = NULL;
    uint8_t *combined = NULL;
    size_t baseline_size = 0, effort0_size = 0, scalar_size = 0;
    size_t vector_size = 0, parallel_size = 0, maximum_size = 0;
    size_t combined_size = 0;
    n148i_image_t scalar_decoded = {0}, vector_decoded = {0};
    n148i_image_t parallel_decoded = {0}, maximum_decoded = {0};
    n148i_image_t combined_decoded = {0};
    n148i_image_info_t info = {0};
    uint32_t changed = 0;
    int success = 0;

    n148i_encode_options_init(&options);
    if (options.format_version != N148I_FORMAT_VERSION_7 ||
        options.effort != 3)
        goto cleanup;
    options.format_version = N148I_FORMAT_VERSION_2;
    options.quality = 50;
    options.chroma = N148I_CHROMA_420;
    options.thread_count = 1;
    options.effort = 0;
    options.feature_flags = base_features;
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &baseline, &baseline_size) !=
            N148I_OK) goto cleanup;
    options.feature_flags = rdo_features;
    if (n148i_encode_memory(&source, &options, &effort0, &effort0_size) !=
            N148I_OK || effort0_size != baseline_size ||
        effort0_size < N148_EXTENDED_HEADER_SIZE ||
        memcmp(effort0 + N148_EXTENDED_HEADER_SIZE,
               baseline + N148_EXTENDED_HEADER_SIZE,
               effort0_size - N148_EXTENDED_HEADER_SIZE) != 0) goto cleanup;

    options.feature_flags = N148I_FEATURE_RDO;
    if (n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;
    options.feature_flags = N148I_FEATURE_RANS | N148I_FEATURE_RDO;
    if (n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;

    options.feature_flags = rdo_features;
    options.effort = 5;
    if (n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_OK ||
        n148i_read_header(scalar, scalar_size, &info) != N148I_OK ||
        info.feature_flags != rdo_features || info.effort != 5 ||
        n148i_decode_memory(scalar, scalar_size, &scalar_decoded) != N148I_OK)
        goto cleanup;
    if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &vector, &vector_size) !=
            N148I_OK || vector_size != scalar_size ||
        memcmp(vector, scalar, scalar_size) != 0 ||
        n148i_decode_memory(vector, vector_size, &vector_decoded) != N148I_OK ||
        memcmp(vector_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;
    options.thread_count = 4;
    if (n148i_simd_force(N148I_SIMD_AUTO) != N148I_OK ||
        n148i_encode_memory(&source, &options, &parallel, &parallel_size) !=
            N148I_OK || parallel_size != scalar_size ||
        memcmp(parallel, scalar, scalar_size) != 0 ||
        n148i_decode_memory(parallel, parallel_size, &parallel_decoded) !=
            N148I_OK ||
        memcmp(parallel_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;

    options.thread_count = 1;
    options.effort = 9;
    if (n148i_encode_memory(&source, &options, &maximum, &maximum_size) !=
            N148I_OK ||
        n148i_read_header(maximum, maximum_size, &info) != N148I_OK ||
        info.feature_flags != rdo_features || info.effort != 9 ||
        n148i_decode_memory(maximum, maximum_size, &maximum_decoded) !=
            N148I_OK) goto cleanup;

    options.feature_flags = combined_features;
    options.effort = 5;
    if (n148i_encode_memory(&source, &options, &combined, &combined_size) !=
            N148I_OK ||
        n148i_decode_memory(combined, combined_size, &combined_decoded) !=
            N148I_OK || !validate_rdo_core(&changed)) goto cleanup;
    success = 1;

cleanup:
    printf("comparison,rate_distortion_optimization,scalar+AVX2,1+4,2,%d,%d,%zu,"
           "%zu,%zu,0.0,effort0_%zu_effort5_%zu_effort9_%zu_changed_%u_"
           "trellis_modes_dependencies_and_combination_determinism,%s\n",
           original->width, original->height, scalar_size, maximum_size,
           maximum_size, effort0_size, scalar_size, maximum_size, changed,
           success ? "PASS" : "FAIL");
    n148i_free_buffer(baseline); n148i_free_buffer(effort0);
    n148i_free_buffer(scalar); n148i_free_buffer(vector);
    n148i_free_buffer(parallel); n148i_free_buffer(maximum);
    n148i_free_buffer(combined);
    n148i_free_image(&scalar_decoded); n148i_free_image(&vector_decoded);
    n148i_free_image(&parallel_decoded); n148i_free_image(&maximum_decoded);
    n148i_free_image(&combined_decoded);
    n148i_simd_force(N148I_SIMD_AUTO);
    n148_cpu_force(-1);
    n148_set_thread_count(1);
    return success;
}

static int validate_loop_filter_core(N148LoopFilterStats *result) {
    Plane first = create_plane(17, 17);
    Plane second = create_plane(17, 17);
    if (!first.data || !second.data) {
        free_plane(&first);
        free_plane(&second);
        return 0;
    }
    for (int y = 0; y < first.height; y++) {
        for (int x = 0; x < first.width; x++) {
            first.data[(long) y * first.width + x] =
                (uint8_t)(x < 8 ? 100 : 110);
        }
    }
    first.data[4 * first.width + 11] = 140;
    memcpy(second.data, first.data, (size_t) first.width * first.height);
    int before_gap = first.data[5 * first.width + 8] -
        first.data[5 * first.width + 7];
    N148LoopFilterStats first_stats = {0}, second_stats = {0};
    int success = n148_loop_filter_block(
        &first, 8, 0, 8, 30, 0, N148_AQ_INITIAL_LEVEL, &first_stats) &&
        n148_loop_filter_block(
            &second, 8, 0, 8, 30, 0, N148_AQ_INITIAL_LEVEL,
            &second_stats);
    int after_gap = first.data[5 * first.width + 8] -
        first.data[5 * first.width + 7];
    if (!success || first_stats.deblocked_samples == 0 ||
        first_stats.deringed_samples == 0 || after_gap >= before_gap ||
        first.data[4 * first.width + 11] >= 140 ||
        memcmp(first.data, second.data,
               (size_t) first.width * first.height) != 0 ||
        memcmp(&first_stats, &second_stats, sizeof(first_stats)) != 0 ||
        n148_loop_filter_strength(30, 0, 3) <=
            n148_loop_filter_strength(30, 0, 0) ||
        n148_loop_filter_strength(30, 0, 1) <=
            n148_loop_filter_strength(90, 0, 1) ||
        n148_loop_filter_strength(100, 0, 1) != 0 ||
        n148_loop_filter_strength(0, 0, 1) != -1 ||
        n148_loop_filter_block(NULL, 0, 0, 8, 30, 0, 1, NULL)) {
        success = 0;
    }
    if (success && result) *result = first_stats;
    free_plane(&first);
    free_plane(&second);
    return success;
}

static size_t different_rgb_samples(const n148i_image_t *first,
                                    const Image *second) {
    if (!first || !first->pixels || !second || !second->pixels ||
        first->width != (uint32_t) second->width ||
        first->height != (uint32_t) second->height) return 0;
    size_t count = (size_t) second->width * (size_t) second->height * 3u;
    size_t different = 0;
    for (size_t index = 0; index < count; index++)
        different += first->pixels[index] != second->pixels[index];
    return different;
}

static int validate_causal_loop_filter(const Image *original) {
    const uint32_t base_features = N148I_FEATURE_RANS |
        N148I_FEATURE_CONTEXT | N148I_FEATURE_INTRA | N148I_FEATURE_RDO;
    const uint32_t filter_features =
        base_features | N148I_FEATURE_LOOP_FILTER;
    const uint32_t combined_features = N148I_FEATURE_ALL;
    n148i_image_t source = {
        original->pixels, (uint32_t) original->width,
        (uint32_t) original->height, (size_t) original->width * 3,
    };
    n148i_encode_options_t options;
    uint8_t *baseline = NULL, *scalar = NULL, *vector = NULL;
    uint8_t *parallel = NULL, *combined = NULL;
    size_t baseline_size = 0, scalar_size = 0, vector_size = 0;
    size_t parallel_size = 0, combined_size = 0;
    n148i_image_t scalar_decoded = {0}, vector_decoded = {0};
    n148i_image_t parallel_decoded = {0}, combined_decoded = {0};
    N148CoeffPlane recovered[3] = {{0}};
    N148PredictionModes decoded_modes = {0};
    Plane filtered_y = {0}, filtered_cb = {0}, filtered_cr = {0};
    Plane plain_y = {0}, plain_cb = {0}, plain_cr = {0};
    Image filtered_rgb = {0}, plain_rgb = {0};
    n148i_image_info_t info = {0};
    N148LoopFilterStats filter_stats = {0};
    size_t changed_samples = 0;
    uint32_t payload_size = 0;
    int success = 0;

    n148i_encode_options_init(&options);
    if (options.format_version != N148I_FORMAT_VERSION_7 ||
        options.effort != 3)
        goto cleanup;
    options.format_version = N148I_FORMAT_VERSION_2;
    options.quality = 30;
    options.chroma = N148I_CHROMA_420;
    options.thread_count = 1;
    options.effort = 5;
    options.feature_flags = base_features;
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &baseline, &baseline_size) !=
            N148I_OK) goto cleanup;

    options.feature_flags = N148I_FEATURE_LOOP_FILTER;
    if (n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;
    options.feature_flags = N148I_FEATURE_RANS | N148I_FEATURE_LOOP_FILTER;
    if (n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;

    options.feature_flags = filter_features;
    if (n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_OK ||
        n148i_read_header(scalar, scalar_size, &info) != N148I_OK ||
        info.feature_flags != filter_features || info.effort != 5 ||
        n148i_decode_memory(scalar, scalar_size, &scalar_decoded) != N148I_OK)
        goto cleanup;

    uint16_t header_size =
        (uint16_t)(scalar[6] | ((uint16_t) scalar[7] << 8));
    uint32_t metadata_size = validation_u32(scalar + 28);
    payload_size = validation_u32(scalar + 16);
    if (!n148_decode_format_2_coefficients(
            scalar + N148_EXTENDED_HEADER_SIZE, metadata_size,
            scalar + header_size, payload_size,
            original->width, original->height, CHROMA_420,
            filter_features, recovered, NULL, &decoded_modes, NULL, NULL) ||
        !n148_intra_reconstruct_planes(
            recovered, decoded_modes.values, decoded_modes.count,
            original->width, original->height, 30, CHROMA_420, 0,
            NULL, NULL, 1, &filtered_y, &filtered_cb, &filtered_cr) ||
        !merge_channels(&filtered_y, &filtered_cb, &filtered_cr, 1,
                        &filtered_rgb) ||
        memcmp(scalar_decoded.pixels, filtered_rgb.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0 ||
        !n148_intra_reconstruct_planes(
            recovered, decoded_modes.values, decoded_modes.count,
            original->width, original->height, 30, CHROMA_420, 0,
            NULL, NULL, 0, &plain_y, &plain_cb, &plain_cr) ||
        !merge_channels(&plain_y, &plain_cb, &plain_cr, 1, &plain_rgb))
        goto cleanup;
    changed_samples = different_rgb_samples(&scalar_decoded, &plain_rgb);
    if (changed_samples == 0 || !validate_loop_filter_core(&filter_stats))
        goto cleanup;

    if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &vector, &vector_size) !=
            N148I_OK || vector_size != scalar_size ||
        memcmp(vector, scalar, scalar_size) != 0 ||
        n148i_decode_memory(vector, vector_size, &vector_decoded) != N148I_OK ||
        memcmp(vector_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;
    options.thread_count = 4;
    if (n148i_simd_force(N148I_SIMD_AUTO) != N148I_OK ||
        n148i_encode_memory(&source, &options, &parallel, &parallel_size) !=
            N148I_OK || parallel_size != scalar_size ||
        memcmp(parallel, scalar, scalar_size) != 0 ||
        n148i_decode_memory(parallel, parallel_size, &parallel_decoded) !=
            N148I_OK ||
        memcmp(parallel_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;

    for (int chroma = N148I_CHROMA_444; chroma <= N148I_CHROMA_420;
         chroma++) {
        uint8_t *chroma_stream = NULL;
        size_t chroma_size = 0;
        n148i_image_t chroma_decoded = {0};
        options.thread_count = 1;
        options.chroma = (n148i_chroma_t) chroma;
        n148i_result_t encode_result = n148i_encode_memory(
            &source, &options, &chroma_stream, &chroma_size);
        n148i_result_t decode_result = encode_result == N148I_OK ?
            n148i_decode_memory(chroma_stream, chroma_size,
                                &chroma_decoded) : encode_result;
        n148i_free_buffer(chroma_stream);
        n148i_free_image(&chroma_decoded);
        if (encode_result != N148I_OK || decode_result != N148I_OK)
            goto cleanup;
    }

    options.thread_count = 1;
    options.chroma = N148I_CHROMA_420;
    options.quality = 50;
    options.feature_flags = combined_features;
    if (n148i_encode_memory(&source, &options, &combined, &combined_size) !=
            N148I_OK ||
        n148i_decode_memory(combined, combined_size, &combined_decoded) !=
            N148I_OK) goto cleanup;
    success = 1;

cleanup:
    printf("comparison,causal_loop_filter,scalar+AVX2,1+4,2,%d,%d,%zu,%u,%u,"
           "0.0,base_%zu_filter_%zu_changed_%zu_deblock_%llu_dering_%llu_"
           "causal_reference_dependencies_and_combination_determinism,%s\n",
           original->width, original->height, scalar_size, payload_size,
           payload_size, baseline_size, scalar_size, changed_samples,
           (unsigned long long) filter_stats.deblocked_samples,
           (unsigned long long) filter_stats.deringed_samples,
           success ? "PASS" : "FAIL");
    n148i_free_buffer(baseline); n148i_free_buffer(scalar);
    n148i_free_buffer(vector); n148i_free_buffer(parallel);
    n148i_free_buffer(combined);
    n148i_free_image(&scalar_decoded); n148i_free_image(&vector_decoded);
    n148i_free_image(&parallel_decoded); n148i_free_image(&combined_decoded);
    for (int plane = 0; plane < 3; plane++)
        n148_free_coeff_plane(&recovered[plane]);
    n148_prediction_modes_release(&decoded_modes);
    free_plane(&filtered_y); free_plane(&filtered_cb); free_plane(&filtered_cr);
    free_plane(&plain_y); free_plane(&plain_cb); free_plane(&plain_cr);
    free_image(&filtered_rgb); free_image(&plain_rgb);
    n148i_simd_force(N148I_SIMD_AUTO);
    n148_cpu_force(-1);
    n148_set_thread_count(1);
    return success;
}

static int inspect_directional_stream(const uint8_t *stream, size_t stream_size,
                             const Image *source, int chroma,
                             uint32_t features,
                             N148SyntaxInspection *inspection) {
    n148i_image_info_t info = {0};
    return stream && source && inspection &&
        n148i_read_header(stream, stream_size, &info) == N148I_OK &&
        info.format_version == N148I_FORMAT_VERSION_3 &&
        info.feature_flags == features &&
        (int) info.chroma == chroma &&
        info.encoded_header_size <= stream_size &&
        info.metadata_size <= info.encoded_header_size -
            N148_EXTENDED_HEADER_SIZE &&
        info.payload_size == stream_size - info.encoded_header_size &&
        n148_directional_intra_inspect(
            stream + N148_EXTENDED_HEADER_SIZE, info.metadata_size,
            stream + info.encoded_header_size, info.payload_size,
            source->width, source->height, chroma, features, inspection);
}

static int inspect_variable_luma_stream(const uint8_t *stream, size_t stream_size,
                             const Image *source, int chroma,
                             uint32_t features,
                             N148SyntaxInspection *inspection) {
    n148i_image_info_t info = {0};
    int joint_chroma =
        (features & N148I_FEATURE_JOINT_CHROMA_INTRA) != 0;
    int segmented = (features & N148I_FEATURE_SEGMENTATION) != 0;
    int adaptive_filter =
        (features & N148I_FEATURE_ADAPTIVE_LOOP_FILTER) != 0;
    int variable_luma =
        (features & N148I_FEATURE_LUMA_TRANSFORM_16X16) != 0;
    return stream && source && inspection &&
        n148i_read_header(stream, stream_size, &info) == N148I_OK &&
        info.format_version == N148I_FORMAT_VERSION_5 &&
        info.feature_flags == features && (int) info.chroma == chroma &&
        info.encoded_header_size <= stream_size &&
        info.metadata_size <= info.encoded_header_size -
            N148_EXTENDED_HEADER_SIZE &&
        info.payload_size == stream_size - info.encoded_header_size &&
        n148_predictive_inspect(
            stream + N148_EXTENDED_HEADER_SIZE, info.metadata_size,
            stream + info.encoded_header_size, info.payload_size,
            source->width, source->height, chroma,
            features & N148_FORMAT_3_SUPPORTED_FEATURES, joint_chroma,
            segmented, adaptive_filter, variable_luma, 0, inspection);
}

static int validate_directional_intra(const Image *original) {
    const uint32_t profile_features[3] = {
        N148I_PROFILE_DIRECTIONAL_INTRA,
        N148I_PROFILE_CONTEXTUAL_RDO,
        N148I_PROFILE_PERCEPTUAL_TRELLIS,
    };
    n148i_image_t source = {
        original->pixels, (uint32_t) original->width,
        (uint32_t) original->height, (size_t) original->width * 3,
    };
    n148i_encode_options_t options;
    uint8_t *profile_streams[3] = {0};
    size_t profile_sizes[3] = {0};
    n148i_image_t profile_decoded[3] = {{0}};
    N148SyntaxInspection profile_inspection[3] = {0};
    uint8_t *vector = NULL, *parallel = NULL, *corrupt = NULL;
    size_t vector_size = 0, parallel_size = 0;
    n148i_image_t vector_decoded = {0}, parallel_decoded = {0};
    uint64_t mode_mask = 0;
    uint64_t total_splits = 0;
    int success = 0;

    n148i_encode_options_init(&options);
    if (options.format_version != N148I_FORMAT_VERSION_7 ||
        options.feature_flags != N148I_DEFAULT_FEATURES ||
        options.effort != 3) goto cleanup;
    options.format_version = N148I_FORMAT_VERSION_3;
    options.feature_flags = N148I_FORMAT_3_DEFAULT_FEATURES;
    options.quality = 50;
    options.chroma = N148I_CHROMA_420;
    options.thread_count = 1;
    options.effort = 5;
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK) goto cleanup;
    for (int profile = 0; profile < 3; profile++) {
        options.feature_flags = profile_features[profile];
        if (n148i_encode_memory(
                &source, &options, &profile_streams[profile],
                &profile_sizes[profile]) != N148I_OK ||
            n148i_decode_memory(
                profile_streams[profile], profile_sizes[profile],
                &profile_decoded[profile]) != N148I_OK ||
            !inspect_directional_stream(
                profile_streams[profile], profile_sizes[profile], original,
                options.chroma, profile_features[profile],
                &profile_inspection[profile]) ||
            profile_decoded[profile].width != source.width ||
            profile_decoded[profile].height != source.height ||
            profile_inspection[profile].split_blocks == 0 ||
            profile_inspection[profile].plane_split_blocks[1] != 0 ||
            profile_inspection[profile].plane_split_blocks[2] != 0 ||
            profile_inspection[profile].plane_total_blocks[1] == 0 ||
            profile_inspection[profile].plane_total_blocks[2] == 0)
            goto cleanup;
        total_splits += profile_inspection[profile].split_blocks;
        for (int mode = 0; mode < N148_DIRECTIONAL_INTRA_MODE_COUNT; mode++) {
            if (profile_inspection[profile].mode_histogram[mode] != 0)
                mode_mask |= 1ull << mode;
        }
    }
    if (mode_mask != (1ull << N148_DIRECTIONAL_INTRA_MODE_COUNT) - 1 ||
        profile_sizes[0] == profile_sizes[1] ||
        profile_sizes[1] == profile_sizes[2]) goto cleanup;

    options.feature_flags = N148I_PROFILE_PERCEPTUAL_TRELLIS;
    if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &vector, &vector_size) !=
            N148I_OK || vector_size != profile_sizes[2] ||
        memcmp(vector, profile_streams[2], vector_size) != 0 ||
        n148i_decode_memory(vector, vector_size, &vector_decoded) != N148I_OK ||
        memcmp(vector_decoded.pixels, profile_decoded[2].pixels,
               profile_decoded[2].stride * profile_decoded[2].height) != 0)
        goto cleanup;
    options.thread_count = 4;
    if (n148i_simd_force(N148I_SIMD_AUTO) != N148I_OK ||
        n148i_encode_memory(&source, &options, &parallel, &parallel_size) !=
            N148I_OK || parallel_size != profile_sizes[2] ||
        memcmp(parallel, profile_streams[2], parallel_size) != 0 ||
        n148i_decode_memory(parallel, parallel_size, &parallel_decoded) !=
            N148I_OK ||
        memcmp(parallel_decoded.pixels, profile_decoded[2].pixels,
               profile_decoded[2].stride * profile_decoded[2].height) != 0)
        goto cleanup;

    options.thread_count = 1;
    for (int chroma = N148I_CHROMA_444; chroma <= N148I_CHROMA_422;
         chroma++) {
        uint8_t *stream = NULL;
        size_t stream_size = 0;
        n148i_image_t decoded = {0};
        N148SyntaxInspection inspection = {0};
        options.chroma = (n148i_chroma_t) chroma;
        n148i_result_t encoded_result = n148i_encode_memory(
            &source, &options, &stream, &stream_size);
        int chroma_ok = encoded_result == N148I_OK &&
            n148i_decode_memory(stream, stream_size, &decoded) == N148I_OK &&
            inspect_directional_stream(stream, stream_size, original, chroma,
                              options.feature_flags, &inspection) &&
            inspection.plane_total_blocks[1] != 0 &&
            inspection.plane_total_blocks[2] != 0 &&
            inspection.plane_split_blocks[1] == 0 &&
            inspection.plane_split_blocks[2] == 0;
        n148i_free_buffer(stream);
        n148i_free_image(&decoded);
        if (!chroma_ok) goto cleanup;
    }

    options.chroma = N148I_CHROMA_420;
    options.feature_flags = N148I_PROFILE_PERCEPTUAL_TRELLIS &
        ~N148I_FEATURE_CONTEXTUAL_RDO;
    if (n148i_encode_memory(&source, &options, &corrupt, &parallel_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;
    if (n148i_decode_memory(profile_streams[2], profile_sizes[2] - 1,
                            &parallel_decoded) == N148I_OK) goto cleanup;
    corrupt = (uint8_t *) malloc(profile_sizes[2]);
    if (!corrupt) goto cleanup;
    memcpy(corrupt, profile_streams[2], profile_sizes[2]);
    corrupt[21] &= (uint8_t) ~0x04u;
    if (n148i_decode_memory(corrupt, profile_sizes[2], &parallel_decoded) ==
            N148I_OK) goto cleanup;
    success = 1;

cleanup:
    printf("comparison,directional_intra,scalar+AVX2,1+4,0+1+2,%d,%d,%zu,0,0,"
           "0.0,profiles_%zu_%zu_%zu_splits_%llu_modes_0x%llx_"
           "directional_4x4_contextual_rdo_trellis_compatibility_and_"
           "determinism,%s\n",
           original->width, original->height, profile_sizes[2],
           profile_sizes[0], profile_sizes[1], profile_sizes[2],
           (unsigned long long) total_splits,
           (unsigned long long) mode_mask,
           success ? "PASS" : "FAIL");
    for (int profile = 0; profile < 3; profile++) {
        n148i_free_buffer(profile_streams[profile]);
        n148i_free_image(&profile_decoded[profile]);
    }
    n148i_free_buffer(vector); n148i_free_buffer(parallel);
    free(corrupt);
    n148i_free_image(&vector_decoded); n148i_free_image(&parallel_decoded);
    n148i_simd_force(N148I_SIMD_AUTO);
    n148_cpu_force(-1);
    n148_set_thread_count(1);
    return success;
}

static int validate_directional_intra_odd_dimensions(const Image *original) {
    n148i_image_t source = {
        original->pixels, (uint32_t) original->width,
        (uint32_t) original->height, (size_t) original->width * 3,
    };
    n148i_encode_options_t options;
    uint8_t *single = NULL, *parallel = NULL;
    size_t single_size = 0, parallel_size = 0;
    n148i_image_t decoded = {0};
    N148SyntaxInspection inspection = {0};
    int success = 0;
    n148i_encode_options_init(&options);
    options.format_version = N148I_FORMAT_VERSION_3;
    options.quality = 50;
    options.chroma = N148I_CHROMA_420;
    options.thread_count = 1;
    options.feature_flags = N148I_PROFILE_PERCEPTUAL_TRELLIS;
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &single, &single_size) !=
            N148I_OK ||
        n148i_decode_memory(single, single_size, &decoded) != N148I_OK ||
        decoded.width != source.width || decoded.height != source.height ||
        !inspect_directional_stream(single, single_size, original, options.chroma,
                           options.feature_flags, &inspection))
        goto cleanup;
    options.thread_count = 4;
    if (n148i_simd_force(N148I_SIMD_AUTO) != N148I_OK ||
        n148i_encode_memory(&source, &options, &parallel, &parallel_size) !=
            N148I_OK || parallel_size != single_size ||
        memcmp(parallel, single, single_size) != 0) goto cleanup;
    success = 1;

cleanup:
    printf("comparison,directional_intra_odd_dimensions,scalar+auto,1+4,2,%d,%d,%zu,0,0,"
           "0.0,split_%llu_partial_4x4_roundtrip_and_determinism,%s\n",
           original->width, original->height, single_size,
           (unsigned long long) inspection.split_blocks,
           success ? "PASS" : "FAIL");
    n148i_free_buffer(single); n148i_free_buffer(parallel);
    n148i_free_image(&decoded);
    n148i_simd_force(N148I_SIMD_AUTO);
    n148_cpu_force(-1);
    n148_set_thread_count(1);
    return success;
}

static uint64_t rgb_squared_error(const Image *source,
                                  const n148i_image_t *decoded) {
    if (!source || !source->pixels || !decoded || !decoded->pixels ||
        decoded->width != (uint32_t) source->width ||
        decoded->height != (uint32_t) source->height) return UINT64_MAX;
    size_t count = (size_t) source->width * (size_t) source->height * 3u;
    uint64_t error = 0;
    for (size_t index = 0; index < count; index++) {
        int difference = source->pixels[index] - decoded->pixels[index];
        error += (uint64_t)(difference * difference);
    }
    return error;
}

static int same_stream_except_version(const uint8_t *first,
                                      const uint8_t *second, size_t size) {
    return first && second && size > N148I_MAGIC_LEN &&
        memcmp(first, second, N148I_MAGIC_LEN) == 0 &&
        memcmp(first + N148I_MAGIC_LEN + 1,
               second + N148I_MAGIC_LEN + 1,
               size - N148I_MAGIC_LEN - 1) == 0;
}

static uint32_t validation_default_features(int format_version) {
    if (format_version == N148I_FORMAT_VERSION_2)
        return N148I_FORMAT_2_DEFAULT_FEATURES;
    if (format_version == N148I_FORMAT_VERSION_3)
        return N148I_FORMAT_3_DEFAULT_FEATURES;
    if (format_version == N148I_FORMAT_VERSION_4)
        return N148I_FORMAT_4_DEFAULT_FEATURES;
    if (format_version == N148I_FORMAT_VERSION_5)
        return N148I_FORMAT_5_DEFAULT_FEATURES;
    if (format_version == N148I_FORMAT_VERSION_6)
        return N148I_FORMAT_6_DEFAULT_FEATURES;
    if (format_version == N148I_FORMAT_VERSION_7)
        return N148I_FORMAT_7_DEFAULT_FEATURES;
    return 0;
}

/* Exercise the public format/chroma cross-product, not just the historical
   format-1 layout sweep. Each point must parse and decode exactly, and scalar
   single-thread output must match AVX2 four-thread output byte for byte. */
static int validate_chroma_format_matrix(const Image *original,
                                         const char *name) {
    n148i_image_t source = {
        original->pixels, (uint32_t) original->width,
        (uint32_t) original->height, (size_t) original->width * 3,
    };
    int completed = 0;
    int success = 0;

    for (int format = N148I_FORMAT_VERSION_1;
         format <= N148I_FORMAT_VERSION_7; format++) {
        for (int chroma = N148I_CHROMA_444;
             chroma <= N148I_CHROMA_420; chroma++) {
            n148i_encode_options_t options;
            uint8_t *scalar = NULL, *parallel = NULL;
            size_t scalar_size = 0, parallel_size = 0;
            n148i_image_t scalar_decoded = {0}, parallel_decoded = {0};
            n148i_image_info_t info = {0};
            int point_ok = 0;

            n148i_encode_options_init(&options);
            options.quality = 50;
            options.chroma = (n148i_chroma_t) chroma;
            options.format_version = (uint32_t) format;
            options.feature_flags = validation_default_features(format);
            options.thread_count = 1;
            if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
                n148i_encode_memory(&source, &options,
                                    &scalar, &scalar_size) != N148I_OK ||
                n148i_read_header(scalar, scalar_size, &info) != N148I_OK ||
                info.format_version != (uint8_t) format ||
                info.chroma != (n148i_chroma_t) chroma ||
                info.width != source.width || info.height != source.height ||
                info.encoded_header_size + info.payload_size != scalar_size ||
                n148i_decode_memory(scalar, scalar_size,
                                    &scalar_decoded) != N148I_OK ||
                scalar_decoded.width != source.width ||
                scalar_decoded.height != source.height)
                goto point_cleanup;

            uint32_t expected_features = validation_default_features(format);
            if (format >= N148I_FORMAT_VERSION_4 &&
                chroma == N148I_CHROMA_444)
                expected_features &=
                    ~N148I_FEATURE_RECONSTRUCTION_AWARE_CHROMA;
            if (info.feature_flags != expected_features)
                goto point_cleanup;

            options.thread_count = 4;
            if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
                n148i_encode_memory(&source, &options,
                                    &parallel, &parallel_size) != N148I_OK ||
                parallel_size != scalar_size ||
                memcmp(parallel, scalar, scalar_size) != 0 ||
                n148i_decode_memory(parallel, parallel_size,
                                    &parallel_decoded) != N148I_OK ||
                parallel_decoded.stride != scalar_decoded.stride ||
                memcmp(parallel_decoded.pixels, scalar_decoded.pixels,
                       scalar_decoded.stride * scalar_decoded.height) != 0)
                goto point_cleanup;
            point_ok = 1;

point_cleanup:
            n148i_free_buffer(scalar);
            n148i_free_buffer(parallel);
            n148i_free_image(&scalar_decoded);
            n148i_free_image(&parallel_decoded);
            if (!point_ok) goto cleanup;
            completed++;
        }
    }
    success = completed == 21;

cleanup:
    printf("comparison,%s,scalar+AVX2,1+4,0+1+2,%d,%d,0,0,0,0.0,"
           "formats_1_to_7_layout_matrix_%d_of_21_exact_roundtrips_"
           "and_determinism,%s\n",
           name, original->width, original->height, completed,
           success ? "PASS" : "FAIL");
    n148i_simd_force(N148I_SIMD_AUTO);
    n148_cpu_force(-1);
    n148_set_thread_count(1);
    return success;
}

static int validate_reconstruction_aware_chroma(const Image *original,
                                     const char *name) {
    n148i_image_t source = {
        original->pixels, (uint32_t) original->width,
        (uint32_t) original->height, (size_t) original->width * 3,
    };
    n148i_encode_options_t options;
    uint8_t *format_3_stream = NULL, *control = NULL, *scalar = NULL;
    uint8_t *vector = NULL, *parallel = NULL;
    uint8_t *layout_control = NULL, *layout_aware = NULL;
    uint8_t *layout_444 = NULL;
    size_t format_3_size = 0, control_size = 0, scalar_size = 0;
    size_t vector_size = 0, parallel_size = 0;
    size_t layout_control_size = 0, layout_aware_size = 0;
    size_t layout_444_size = 0;
    n148i_image_t control_decoded = {0}, scalar_decoded = {0};
    n148i_image_t vector_decoded = {0}, parallel_decoded = {0};
    n148i_image_t layout_control_decoded = {0};
    n148i_image_t layout_aware_decoded = {0}, layout_444_decoded = {0};
    n148i_image_info_t info = {0}, layout_info = {0};
    uint64_t control_error = UINT64_MAX, aware_error = UINT64_MAX;
    uint64_t control_422_error = UINT64_MAX, aware_422_error = UINT64_MAX;
    int success = 0;

    n148i_encode_options_init(&options);
    if (options.format_version != N148I_FORMAT_VERSION_7 ||
        options.feature_flags != N148I_DEFAULT_FEATURES ||
        strcmp(n148i_library_version(), "V2") != 0 ||
        n148i_format_version() != N148I_FORMAT_VERSION_7) goto cleanup;
    options.quality = 50;
    options.chroma = N148I_CHROMA_420;
    options.thread_count = 1;
    options.effort = 5;

    options.format_version = N148I_FORMAT_VERSION_3;
    options.feature_flags = N148I_FORMAT_3_DEFAULT_FEATURES;
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &format_3_stream,
                            &format_3_size) != N148I_OK)
        goto cleanup;
    options.format_version = N148I_FORMAT_VERSION_4;
    if (n148i_encode_memory(&source, &options, &control, &control_size) !=
            N148I_OK || control_size != format_3_size ||
        !same_stream_except_version(format_3_stream, control, format_3_size) ||
        n148i_decode_memory(control, control_size, &control_decoded) !=
            N148I_OK) goto cleanup;

    options.feature_flags = N148I_PROFILE_RECONSTRUCTION_AWARE_CHROMA;
    if (n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_OK || (scalar_size == control_size &&
            memcmp(scalar, control, scalar_size) == 0) ||
        n148i_read_header(scalar, scalar_size, &info) != N148I_OK ||
        info.format_version != N148I_FORMAT_VERSION_4 ||
        info.feature_flags != N148I_PROFILE_RECONSTRUCTION_AWARE_CHROMA ||
        info.encoded_header_size + info.payload_size != scalar_size ||
        n148i_decode_memory(scalar, scalar_size, &scalar_decoded) != N148I_OK)
        goto cleanup;
    control_error = rgb_squared_error(original, &control_decoded);
    aware_error = rgb_squared_error(original, &scalar_decoded);
    if (control_error == UINT64_MAX || aware_error >= control_error)
        goto cleanup;

    if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &vector, &vector_size) !=
            N148I_OK || vector_size != scalar_size ||
        memcmp(vector, scalar, scalar_size) != 0 ||
        n148i_decode_memory(vector, vector_size, &vector_decoded) != N148I_OK ||
        memcmp(vector_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;
    options.thread_count = 4;
    if (n148i_simd_force(N148I_SIMD_AUTO) != N148I_OK ||
        n148i_encode_memory(&source, &options, &parallel, &parallel_size) !=
            N148I_OK || parallel_size != scalar_size ||
        memcmp(parallel, scalar, scalar_size) != 0 ||
        n148i_decode_memory(parallel, parallel_size, &parallel_decoded) !=
            N148I_OK ||
        memcmp(parallel_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;

    /* 4:2:2 uses the same reconstruction search with an identity vertical
       axis. This is the path that the old format validation rejected. */
    options.thread_count = 1;
    options.chroma = N148I_CHROMA_422;
    options.feature_flags = N148I_FORMAT_3_DEFAULT_FEATURES;
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &layout_control,
                            &layout_control_size) != N148I_OK ||
        n148i_decode_memory(layout_control, layout_control_size,
                            &layout_control_decoded) != N148I_OK)
        goto cleanup;
    options.feature_flags = N148I_PROFILE_RECONSTRUCTION_AWARE_CHROMA;
    if (n148i_encode_memory(&source, &options, &layout_aware,
                            &layout_aware_size) != N148I_OK ||
        n148i_read_header(layout_aware, layout_aware_size,
                          &layout_info) != N148I_OK ||
        layout_info.chroma != N148I_CHROMA_422 ||
        layout_info.feature_flags != N148I_PROFILE_RECONSTRUCTION_AWARE_CHROMA ||
        n148i_decode_memory(layout_aware, layout_aware_size,
                            &layout_aware_decoded) != N148I_OK)
        goto cleanup;
    control_422_error = rgb_squared_error(original, &layout_control_decoded);
    aware_422_error = rgb_squared_error(original, &layout_aware_decoded);
    if (control_422_error == UINT64_MAX ||
        aware_422_error >= control_422_error) goto cleanup;

    /* In 4:4:4 no reduction exists. The encoder accepts the format 4 default
       request but canonicalizes the irrelevant reconstruction-aware bit from the
       stream instead of rejecting the whole layout. */
    options.chroma = N148I_CHROMA_444;
    if (n148i_encode_memory(&source, &options, &layout_444,
                            &layout_444_size) != N148I_OK ||
        n148i_read_header(layout_444, layout_444_size,
                          &layout_info) != N148I_OK ||
        layout_info.chroma != N148I_CHROMA_444 ||
        layout_info.feature_flags != N148I_FORMAT_3_DEFAULT_FEATURES ||
        n148i_decode_memory(layout_444, layout_444_size,
                            &layout_444_decoded) != N148I_OK)
        goto cleanup;
    success = 1;

cleanup:
    printf("comparison,%s,scalar+AVX2,1+4,2,%d,%d,%zu,%u,%u,0.0,"
           "format_3_payload_compatibility_reconstruction_error_%llu_to_%llu_"
           "422_reconstruction_error_%llu_to_%llu_444_canonical_"
           "odd_edges_and_determinism,%s\n",
           name, original->width, original->height, scalar_size,
           info.payload_size, info.payload_size,
           (unsigned long long) control_error,
           (unsigned long long) aware_error,
           (unsigned long long) control_422_error,
           (unsigned long long) aware_422_error,
           success ? "PASS" : "FAIL");
    n148i_free_buffer(format_3_stream); n148i_free_buffer(control);
    n148i_free_buffer(scalar); n148i_free_buffer(vector);
    n148i_free_buffer(parallel); n148i_free_buffer(layout_control);
    n148i_free_buffer(layout_aware); n148i_free_buffer(layout_444);
    n148i_free_image(&control_decoded); n148i_free_image(&scalar_decoded);
    n148i_free_image(&vector_decoded); n148i_free_image(&parallel_decoded);
    n148i_free_image(&layout_control_decoded);
    n148i_free_image(&layout_aware_decoded);
    n148i_free_image(&layout_444_decoded);
    n148i_simd_force(N148I_SIMD_AUTO);
    n148_cpu_force(-1);
    n148_set_thread_count(1);
    return success;
}

static int validate_joint_chroma_intra(const Image *original,
                                     const char *name) {
    n148i_image_t source = {
        original->pixels, (uint32_t) original->width,
        (uint32_t) original->height, (size_t) original->width * 3,
    };
    n148i_encode_options_t options;
    uint8_t *control = NULL, *scalar = NULL, *vector = NULL;
    uint8_t *parallel = NULL, *corrupt = NULL, *invalid = NULL;
    uint8_t *compatibility = NULL;
    size_t control_size = 0, scalar_size = 0, vector_size = 0;
    size_t parallel_size = 0, invalid_size = 0, compatibility_size = 0;
    n148i_image_t scalar_decoded = {0}, vector_decoded = {0};
    n148i_image_t parallel_decoded = {0}, rejected = {0};
    n148i_image_t compatibility_decoded = {0};
    n148i_image_info_t info = {0};
    n148i_image_info_t compatibility_info = {0};
    N148SyntaxInspection inspection = {0};
    uint32_t stored_mode_slots = 0;
    int success = 0;

    n148i_encode_options_init(&options);
    options.format_version = N148I_FORMAT_VERSION_4;
    options.quality = 50;
    options.chroma = N148I_CHROMA_420;
    options.thread_count = 1;
    options.effort = 5;
    options.feature_flags = N148I_PROFILE_RECONSTRUCTION_AWARE_CHROMA;
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &control, &control_size) !=
            N148I_OK) goto cleanup;

    options.feature_flags = N148I_PROFILE_JOINT_CHROMA_INTRA;
    if (n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_OK || (scalar_size == control_size &&
            memcmp(scalar, control, scalar_size) == 0) ||
        n148i_read_header(scalar, scalar_size, &info) != N148I_OK ||
        info.format_version != N148I_FORMAT_VERSION_4 ||
        info.feature_flags != N148I_PROFILE_JOINT_CHROMA_INTRA ||
        info.encoded_header_size + info.payload_size != scalar_size ||
        info.payload_size < 20 || scalar[info.encoded_header_size] != 6 ||
        n148i_decode_memory(scalar, scalar_size, &scalar_decoded) != N148I_OK ||
        !n148_joint_chroma_inspect(
            scalar + N148_EXTENDED_HEADER_SIZE, info.metadata_size,
            scalar + info.encoded_header_size, info.payload_size,
            original->width, original->height, CHROMA_420,
            N148I_FORMAT_3_DEFAULT_FEATURES, &inspection)) goto cleanup;

    stored_mode_slots = validation_u32(
        scalar + info.encoded_header_size + 16);
    int chroma_width, chroma_height;
    chroma_dimensions(CHROMA_420, original->width, original->height,
                      &chroma_width, &chroma_height);
    uint64_t y_blocks = (uint64_t)(original->width / 8 +
        (original->width % 8 != 0)) *
        (uint64_t)(original->height / 8 + (original->height % 8 != 0));
    uint64_t chroma_blocks = (uint64_t)(chroma_width / 8 +
        (chroma_width % 8 != 0)) *
        (uint64_t)(chroma_height / 8 + (chroma_height % 8 != 0));
    uint64_t expected_slots = (y_blocks + chroma_blocks) *
        N148_INTRA_MODE_SLOTS_PER_BLOCK;
    if (expected_slots > UINT32_MAX || stored_mode_slots != expected_slots)
        goto cleanup;
    for (int mode = 0; mode < N148_DIRECTIONAL_INTRA_MODE_COUNT; mode++) {
        if (inspection.plane_mode_histogram[1][mode] !=
            inspection.plane_mode_histogram[2][mode])
            goto cleanup;
    }

    if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &vector, &vector_size) !=
            N148I_OK || vector_size != scalar_size ||
        memcmp(vector, scalar, scalar_size) != 0 ||
        n148i_decode_memory(vector, vector_size, &vector_decoded) != N148I_OK ||
        memcmp(vector_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;
    options.thread_count = 4;
    if (n148i_encode_memory(&source, &options, &parallel, &parallel_size) !=
            N148I_OK || parallel_size != scalar_size ||
        memcmp(parallel, scalar, scalar_size) != 0 ||
        n148i_decode_memory(parallel, parallel_size, &parallel_decoded) !=
            N148I_OK ||
        memcmp(parallel_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;

    corrupt = (uint8_t *) malloc(scalar_size);
    if (!corrupt) goto cleanup;
    memcpy(corrupt, scalar, scalar_size);
    corrupt[21] &= (uint8_t) ~0x20u;
    if (n148i_decode_memory(corrupt, scalar_size, &rejected) == N148I_OK)
        goto cleanup;
    memcpy(corrupt, scalar, scalar_size);
    corrupt[info.encoded_header_size] = 5;
    if (n148i_decode_memory(corrupt, scalar_size, &rejected) == N148I_OK)
        goto cleanup;
    memcpy(corrupt, scalar, scalar_size);
    validation_put_u32(corrupt + info.encoded_header_size + 16,
                       stored_mode_slots + 1);
    if (n148i_decode_memory(corrupt, scalar_size, &rejected) == N148I_OK)
        goto cleanup;

    /* Bit 12 is intentionally 4:2:0-only, but the independently signaled
       joint-mode grammar must remain valid with every public chroma layout. */
    options.thread_count = 1;
    options.feature_flags = N148I_FORMAT_3_DEFAULT_FEATURES |
        N148I_FEATURE_JOINT_CHROMA_INTRA;
    for (int chroma = N148I_CHROMA_444; chroma <= N148I_CHROMA_420; chroma++) {
        options.chroma = (n148i_chroma_t) chroma;
        if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
            n148i_encode_memory(&source, &options, &compatibility,
                                &compatibility_size) != N148I_OK ||
            n148i_read_header(compatibility, compatibility_size,
                              &compatibility_info) != N148I_OK ||
            compatibility_info.chroma != (n148i_chroma_t) chroma ||
            compatibility_info.feature_flags != options.feature_flags ||
            n148i_decode_memory(compatibility, compatibility_size,
                                &compatibility_decoded) != N148I_OK)
            goto cleanup;
        n148i_free_buffer(compatibility);
        compatibility = NULL;
        compatibility_size = 0;
        n148i_free_image(&compatibility_decoded);
    }

    options.thread_count = 1;
    options.chroma = N148I_CHROMA_420;
    options.feature_flags = N148I_PROFILE_RECONSTRUCTION_AWARE_CHROMA |
        N148I_FEATURE_JOINT_CHROMA_INTRA;
    options.feature_flags &= ~N148I_FEATURE_CONTEXTUAL_RDO;
    if (n148i_encode_memory(&source, &options, &invalid, &invalid_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;
    success = 1;

cleanup:
    printf("comparison,%s,scalar+AVX2,1+4,2,%d,%d,%zu,%u,%u,0.0,"
           "payload_revision_6_stored_mode_slots_%u_joint_chroma_"
           "corruption_and_determinism,%s\n",
           name, original->width, original->height, scalar_size,
           info.payload_size, info.payload_size, stored_mode_slots,
           success ? "PASS" : "FAIL");
    n148i_free_buffer(control); n148i_free_buffer(scalar);
    n148i_free_buffer(vector); n148i_free_buffer(parallel);
    n148i_free_buffer(invalid); n148i_free_buffer(compatibility); free(corrupt);
    n148i_free_image(&scalar_decoded); n148i_free_image(&vector_decoded);
    n148i_free_image(&parallel_decoded); n148i_free_image(&rejected);
    n148i_free_image(&compatibility_decoded);
    n148i_simd_force(N148I_SIMD_AUTO);
    n148_cpu_force(-1);
    n148_set_thread_count(1);
    return success;
}

static int validate_calibrated_chroma_quantization(const Image *original,
                                     const char *name) {
    n148i_image_t source = {
        original->pixels, (uint32_t) original->width,
        (uint32_t) original->height, (size_t) original->width * 3,
    };
    n148i_encode_options_t options;
    uint8_t *control = NULL, *scalar = NULL, *vector = NULL;
    uint8_t *parallel = NULL, *explicit_stream = NULL;
    uint8_t *compatibility = NULL, *invalid = NULL, *corrupt = NULL;
    size_t control_size = 0, scalar_size = 0, vector_size = 0;
    size_t parallel_size = 0, explicit_size = 0;
    size_t compatibility_size = 0, invalid_size = 0;
    uint32_t scalar_payload_size = 0;
    n148i_image_t scalar_decoded = {0}, vector_decoded = {0};
    n148i_image_t parallel_decoded = {0}, explicit_decoded = {0};
    n148i_image_t compatibility_decoded = {0}, rejected = {0};
    n148i_image_info_t control_info = {0}, info = {0};
    n148i_image_info_t compatibility_info = {0};
    int success = 0;

    n148i_encode_options_init(&options);
    if (options.format_version != N148I_FORMAT_VERSION_7 ||
        options.feature_flags != N148I_DEFAULT_FEATURES ||
        options.chroma_quality != 0) goto cleanup;
    options.format_version = N148I_FORMAT_VERSION_4;
    options.quality = 50;
    options.chroma = N148I_CHROMA_420;
    options.thread_count = 1;
    options.effort = 5;
    options.feature_flags = N148I_PROFILE_RECONSTRUCTION_AWARE_CHROMA;
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &control, &control_size) !=
            N148I_OK ||
        n148i_read_header(control, control_size, &control_info) != N148I_OK ||
        control_info.chroma_quality != 50 || control[27] != 0)
        goto cleanup;

    options.feature_flags = N148I_PROFILE_CALIBRATED_CHROMA_QUANT;
    if (n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_OK ||
        n148i_read_header(scalar, scalar_size, &info) != N148I_OK ||
        info.format_version != N148I_FORMAT_VERSION_4 ||
        info.feature_flags != N148I_PROFILE_CALIBRATED_CHROMA_QUANT ||
        info.quality != 50 || info.chroma_quality != 55 || scalar[27] != 55 ||
        info.encoded_header_size + info.payload_size != scalar_size ||
        info.payload_size < 20 || scalar[info.encoded_header_size] != 5 ||
        n148i_decode_memory(scalar, scalar_size, &scalar_decoded) != N148I_OK)
        goto cleanup;
    scalar_payload_size = info.payload_size;

    if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &vector, &vector_size) !=
            N148I_OK || vector_size != scalar_size ||
        memcmp(vector, scalar, scalar_size) != 0 ||
        n148i_decode_memory(vector, vector_size, &vector_decoded) != N148I_OK ||
        memcmp(vector_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;
    options.thread_count = 4;
    if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &parallel, &parallel_size) !=
            N148I_OK || parallel_size != scalar_size ||
        memcmp(parallel, scalar, scalar_size) != 0 ||
        n148i_decode_memory(parallel, parallel_size, &parallel_decoded) !=
            N148I_OK ||
        memcmp(parallel_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;

    /* The thread comparison above deliberately keeps AVX2 fixed. The FMA
       inverse path may differ by one final clamp unit; stream identity across
       SIMD levels is checked independently before the thread comparison. */
    options.thread_count = 1;
    options.chroma_quality = 63;
    if (n148i_encode_memory(&source, &options, &explicit_stream,
                            &explicit_size) != N148I_OK ||
        n148i_read_header(explicit_stream, explicit_size, &info) != N148I_OK ||
        info.chroma_quality != 63 || explicit_stream[27] != 63 ||
        n148i_decode_memory(explicit_stream, explicit_size,
                            &explicit_decoded) != N148I_OK)
        goto cleanup;

    corrupt = (uint8_t *) malloc(scalar_size);
    if (!corrupt) goto cleanup;
    memcpy(corrupt, scalar, scalar_size);
    corrupt[27] = 0;
    if (n148i_decode_memory(corrupt, scalar_size, &rejected) == N148I_OK)
        goto cleanup;
    memcpy(corrupt, scalar, scalar_size);
    corrupt[27] = 101;
    if (n148i_decode_memory(corrupt, scalar_size, &rejected) == N148I_OK)
        goto cleanup;
    memcpy(corrupt, scalar, scalar_size);
    corrupt[21] &= (uint8_t) ~0x40u;
    if (n148i_decode_memory(corrupt, scalar_size, &rejected) == N148I_OK)
        goto cleanup;

    options.chroma_quality = 55;
    options.feature_flags = N148I_PROFILE_RECONSTRUCTION_AWARE_CHROMA;
    if (n148i_encode_memory(&source, &options, &invalid, &invalid_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;
    options.feature_flags = N148I_PROFILE_CALIBRATED_CHROMA_QUANT;
    options.chroma_quality = 101;
    if (n148i_encode_memory(&source, &options, &invalid, &invalid_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;
    options.format_version = N148I_FORMAT_VERSION_3;
    options.feature_flags = N148I_FORMAT_3_DEFAULT_FEATURES;
    options.chroma_quality = 55;
    if (n148i_encode_memory(&source, &options, &invalid, &invalid_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;

    /* The calibrated table is independent of subsampling syntax. The
       reconstruction-aware path's
       reconstruction-aware reducer remains intentionally 4:2:0-only. */
    options.format_version = N148I_FORMAT_VERSION_4;
    options.feature_flags = N148I_FORMAT_3_DEFAULT_FEATURES |
        N148I_FEATURE_CALIBRATED_CHROMA_QUANT;
    options.chroma_quality = 55;
    for (int chroma = N148I_CHROMA_444; chroma <= N148I_CHROMA_420; chroma++) {
        options.chroma = (n148i_chroma_t) chroma;
        if (n148i_encode_memory(&source, &options, &compatibility,
                                &compatibility_size) != N148I_OK ||
            n148i_read_header(compatibility, compatibility_size,
                              &compatibility_info) != N148I_OK ||
            compatibility_info.chroma != (n148i_chroma_t) chroma ||
            compatibility_info.chroma_quality != 55 ||
            n148i_decode_memory(compatibility, compatibility_size,
                                &compatibility_decoded) != N148I_OK)
            goto cleanup;
        n148i_free_buffer(compatibility);
        compatibility = NULL;
        compatibility_size = 0;
        n148i_free_image(&compatibility_decoded);
    }
    success = 1;

cleanup:
    printf("comparison,%s,scalar+AVX2,1+4,2,%d,%d,%zu,%u,%u,0.0,"
           "calibrated_chroma_quality_55_header_byte27_"
           "corruption_all_layouts_and_determinism,%s\n",
           name, original->width, original->height, scalar_size,
           scalar_payload_size, scalar_payload_size,
           success ? "PASS" : "FAIL");
    n148i_free_buffer(control); n148i_free_buffer(scalar);
    n148i_free_buffer(vector); n148i_free_buffer(parallel);
    n148i_free_buffer(explicit_stream); n148i_free_buffer(compatibility);
    n148i_free_buffer(invalid); free(corrupt);
    n148i_free_image(&scalar_decoded); n148i_free_image(&vector_decoded);
    n148i_free_image(&parallel_decoded); n148i_free_image(&explicit_decoded);
    n148i_free_image(&compatibility_decoded); n148i_free_image(&rejected);
    n148i_simd_force(N148I_SIMD_AUTO);
    n148_cpu_force(-1);
    n148_set_thread_count(1);
    return success;
}

static int validate_frame_segmentation(const Image *original,
                                    const char *name) {
    n148i_image_t source = {
        original->pixels, (uint32_t) original->width,
        (uint32_t) original->height, (size_t) original->width * 3,
    };
    n148i_encode_options_t options;
    uint8_t *control = NULL, *scalar = NULL, *vector = NULL;
    uint8_t *parallel = NULL, *compatibility = NULL;
    uint8_t *invalid = NULL, *corrupt = NULL;
    size_t control_size = 0, scalar_size = 0, vector_size = 0;
    size_t parallel_size = 0, compatibility_size = 0, invalid_size = 0;
    n148i_image_t scalar_decoded = {0}, vector_decoded = {0};
    n148i_image_t parallel_decoded = {0}, compatibility_decoded = {0};
    n148i_image_t rejected = {0};
    n148i_image_info_t info = {0}, compatibility_info = {0};
    N148SyntaxInspection inspection = {0};
    uint32_t stored_segments = 0;
    uint64_t histogram_total = 0;
    int success = 0;

    n148i_encode_options_init(&options);
    options.format_version = N148I_FORMAT_VERSION_4;
    options.quality = 50;
    options.chroma = N148I_CHROMA_420;
    options.thread_count = 1;
    options.effort = 5;
    options.feature_flags = N148I_PROFILE_CALIBRATED_CHROMA_QUANT;
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &control, &control_size) !=
            N148I_OK) goto cleanup;

    options.feature_flags = N148I_PROFILE_CHROMA_SEGMENTATION;
    if (n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_OK || (scalar_size == control_size &&
            memcmp(scalar, control, scalar_size) == 0) ||
        n148i_read_header(scalar, scalar_size, &info) != N148I_OK ||
        info.format_version != N148I_FORMAT_VERSION_4 ||
        info.feature_flags != N148I_PROFILE_CHROMA_SEGMENTATION ||
        info.chroma_quality != 55 ||
        info.encoded_header_size + info.payload_size != scalar_size ||
        info.payload_size < 28 || scalar[info.encoded_header_size] != 7 ||
        scalar[info.encoded_header_size + 3] != 12 ||
        n148i_decode_memory(scalar, scalar_size, &scalar_decoded) != N148I_OK ||
        !n148_segmented_inspect(
            scalar + N148_EXTENDED_HEADER_SIZE, info.metadata_size,
            scalar + info.encoded_header_size, info.payload_size,
            original->width, original->height, CHROMA_420,
            N148I_FORMAT_3_DEFAULT_FEATURES, 0, &inspection)) goto cleanup;

    stored_segments = validation_u32(
        scalar + info.encoded_header_size + 24);
    uint64_t expected_segments =
        (uint64_t)(original->width / N148_SEGMENT_REGION_SIZE +
            (original->width % N148_SEGMENT_REGION_SIZE != 0)) *
        (uint64_t)(original->height / N148_SEGMENT_REGION_SIZE +
            (original->height % N148_SEGMENT_REGION_SIZE != 0));
    for (int segment = 0; segment < N148_SEGMENT_COUNT; segment++)
        histogram_total += inspection.segment_histogram[segment];
    if (expected_segments > UINT32_MAX ||
        stored_segments != (uint32_t) expected_segments ||
        inspection.segment_count != expected_segments ||
        histogram_total != expected_segments) goto cleanup;
    for (int segment = 0; segment < N148_SEGMENT_COUNT; segment++) {
        if (inspection.segment_quant_scale[segment] <
                N148_SEGMENT_MIN_SCALE ||
            inspection.segment_quant_scale[segment] >
                N148_SEGMENT_MAX_SCALE ||
            scalar[info.encoded_header_size + 28 + segment] !=
                inspection.segment_quant_scale[segment]) goto cleanup;
    }

    if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &vector, &vector_size) !=
            N148I_OK || vector_size != scalar_size ||
        memcmp(vector, scalar, scalar_size) != 0 ||
        n148i_decode_memory(vector, vector_size, &vector_decoded) != N148I_OK ||
        memcmp(vector_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;
    options.thread_count = 4;
    if (n148i_encode_memory(&source, &options, &parallel, &parallel_size) !=
            N148I_OK || parallel_size != scalar_size ||
        memcmp(parallel, scalar, scalar_size) != 0 ||
        n148i_decode_memory(parallel, parallel_size, &parallel_decoded) !=
            N148I_OK ||
        memcmp(parallel_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;

    corrupt = (uint8_t *) malloc(scalar_size);
    if (!corrupt) goto cleanup;
    memcpy(corrupt, scalar, scalar_size);
    corrupt[21] &= (uint8_t) ~0x80u;
    if (n148i_decode_memory(corrupt, scalar_size, &rejected) == N148I_OK)
        goto cleanup;
    memcpy(corrupt, scalar, scalar_size);
    corrupt[info.encoded_header_size] = 5;
    if (n148i_decode_memory(corrupt, scalar_size, &rejected) == N148I_OK)
        goto cleanup;
    memcpy(corrupt, scalar, scalar_size);
    corrupt[info.encoded_header_size + 3] &= (uint8_t) ~8u;
    if (n148i_decode_memory(corrupt, scalar_size, &rejected) == N148I_OK)
        goto cleanup;
    memcpy(corrupt, scalar, scalar_size);
    validation_put_u32(corrupt + info.encoded_header_size + 24,
                       stored_segments + 1);
    if (n148i_decode_memory(corrupt, scalar_size, &rejected) == N148I_OK)
        goto cleanup;
    memcpy(corrupt, scalar, scalar_size);
    corrupt[info.encoded_header_size + 28] = N148_SEGMENT_MIN_SCALE - 1;
    if (n148i_decode_memory(corrupt, scalar_size, &rejected) == N148I_OK)
        goto cleanup;

    options.thread_count = 1;
    options.feature_flags = N148I_PROFILE_CHROMA_SEGMENTATION &
        ~N148I_FEATURE_CALIBRATED_CHROMA_QUANT;
    if (n148i_encode_memory(&source, &options, &invalid, &invalid_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;
    options.feature_flags = N148I_PROFILE_CHROMA_SEGMENTATION &
        ~N148I_FEATURE_CONTEXTUAL_RDO;
    if (n148i_encode_memory(&source, &options, &invalid, &invalid_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;

    /* Segmentation itself is independent of chroma layout. Excluding
       reconstruction-aware chroma
       permits this syntax check in 4:4:4 and 4:2:2 as well as 4:2:0. */
    options.feature_flags = N148I_FORMAT_3_DEFAULT_FEATURES |
        N148I_FEATURE_CALIBRATED_CHROMA_QUANT |
        N148I_FEATURE_SEGMENTATION;
    for (int chroma = N148I_CHROMA_444; chroma <= N148I_CHROMA_420; chroma++) {
        options.chroma = (n148i_chroma_t) chroma;
        if (n148i_encode_memory(&source, &options, &compatibility,
                                &compatibility_size) != N148I_OK ||
            n148i_read_header(compatibility, compatibility_size,
                              &compatibility_info) != N148I_OK ||
            compatibility_info.chroma != (n148i_chroma_t) chroma ||
            compatibility_info.feature_flags != options.feature_flags ||
            n148i_decode_memory(compatibility, compatibility_size,
                                &compatibility_decoded) != N148I_OK)
            goto cleanup;
        n148i_free_buffer(compatibility);
        compatibility = NULL;
        compatibility_size = 0;
        n148i_free_image(&compatibility_decoded);
    }
    success = 1;

cleanup:
    printf("comparison,%s,scalar+AVX2,1+4,2,%d,%d,%zu,%u,%u,0.0,"
           "payload_revision_7_segments_%u_frame_cluster_map_"
           "corruption_all_layouts_and_determinism,%s\n",
           name, original->width, original->height, scalar_size,
           info.payload_size, info.payload_size, stored_segments,
           success ? "PASS" : "FAIL");
    n148i_free_buffer(control); n148i_free_buffer(scalar);
    n148i_free_buffer(vector); n148i_free_buffer(parallel);
    n148i_free_buffer(compatibility); n148i_free_buffer(invalid); free(corrupt);
    n148i_free_image(&scalar_decoded); n148i_free_image(&vector_decoded);
    n148i_free_image(&parallel_decoded);
    n148i_free_image(&compatibility_decoded); n148i_free_image(&rejected);
    n148i_simd_force(N148I_SIMD_AUTO);
    n148_cpu_force(-1);
    n148_set_thread_count(1);
    return success;
}

static int validate_segment_adaptive_filter(const Image *original,
                                       const char *name) {
    n148i_image_t source = {
        original->pixels, (uint32_t) original->width,
        (uint32_t) original->height, (size_t) original->width * 3,
    };
    n148i_encode_options_t options;
    uint8_t *control = NULL, *scalar = NULL, *vector = NULL;
    uint8_t *parallel = NULL, *compatibility = NULL;
    uint8_t *invalid = NULL, *corrupt = NULL;
    size_t control_size = 0, scalar_size = 0, vector_size = 0;
    size_t parallel_size = 0, compatibility_size = 0, invalid_size = 0;
    n148i_image_t scalar_decoded = {0}, vector_decoded = {0};
    n148i_image_t parallel_decoded = {0}, compatibility_decoded = {0};
    n148i_image_t rejected = {0};
    n148i_image_info_t info = {0};
    N148SyntaxInspection inspection = {0};
    int success = 0;

    n148i_encode_options_init(&options);
    options.format_version = N148I_FORMAT_VERSION_4;
    options.quality = 50;
    options.chroma = N148I_CHROMA_420;
    options.thread_count = 1;
    options.effort = 5;
    options.feature_flags = N148I_PROFILE_CHROMA_SEGMENTATION;
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &control, &control_size) !=
            N148I_OK) goto cleanup;

    options.feature_flags = N148I_PROFILE_ADAPTIVE_CHROMA_FILTER;
    if (n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_OK || (scalar_size == control_size &&
            memcmp(scalar, control, scalar_size) == 0) ||
        n148i_read_header(scalar, scalar_size, &info) != N148I_OK ||
        info.feature_flags != N148I_PROFILE_ADAPTIVE_CHROMA_FILTER ||
        info.encoded_header_size + info.payload_size != scalar_size ||
        !info.payload_size || scalar[info.encoded_header_size] != 9 ||
        n148i_decode_memory(scalar, scalar_size, &scalar_decoded) != N148I_OK ||
        !n148_adaptive_filter_inspect(
            scalar + N148_EXTENDED_HEADER_SIZE, info.metadata_size,
            scalar + info.encoded_header_size, info.payload_size,
            original->width, original->height, CHROMA_420,
            N148I_FORMAT_3_DEFAULT_FEATURES, 0, &inspection) ||
        inspection.segment_count == 0) goto cleanup;

    if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &vector, &vector_size) !=
            N148I_OK || vector_size != scalar_size ||
        memcmp(vector, scalar, scalar_size) != 0 ||
        n148i_decode_memory(vector, vector_size, &vector_decoded) != N148I_OK ||
        memcmp(vector_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;
    options.thread_count = 4;
    if (n148i_encode_memory(&source, &options, &parallel, &parallel_size) !=
            N148I_OK || parallel_size != scalar_size ||
        memcmp(parallel, scalar, scalar_size) != 0 ||
        n148i_decode_memory(parallel, parallel_size, &parallel_decoded) !=
            N148I_OK ||
        memcmp(parallel_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;

    corrupt = (uint8_t *) malloc(scalar_size);
    if (!corrupt) goto cleanup;
    memcpy(corrupt, scalar, scalar_size);
    corrupt[22] &= (uint8_t) ~1u;
    if (n148i_decode_memory(corrupt, scalar_size, &rejected) == N148I_OK)
        goto cleanup;
    memcpy(corrupt, scalar, scalar_size);
    corrupt[info.encoded_header_size] = 7;
    if (n148i_decode_memory(corrupt, scalar_size, &rejected) == N148I_OK)
        goto cleanup;

    options.thread_count = 1;
    options.feature_flags = N148I_PROFILE_ADAPTIVE_CHROMA_FILTER &
        ~N148I_FEATURE_SEGMENTATION;
    if (n148i_encode_memory(&source, &options, &invalid, &invalid_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;
    options.feature_flags = N148I_PROFILE_ADAPTIVE_CHROMA_FILTER &
        ~N148I_FEATURE_LOOP_FILTER;
    if (n148i_encode_memory(&source, &options, &invalid, &invalid_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;

    /* Reconstruction-aware chroma is the only 4:2:0-specific bit. The adaptive filter
       follows the full-resolution segment map for every chroma layout. */
    options.feature_flags = N148I_FORMAT_3_DEFAULT_FEATURES |
        N148I_FEATURE_CALIBRATED_CHROMA_QUANT |
        N148I_FEATURE_SEGMENTATION |
        N148I_FEATURE_ADAPTIVE_LOOP_FILTER;
    for (int chroma = N148I_CHROMA_444; chroma <= N148I_CHROMA_420; chroma++) {
        options.chroma = (n148i_chroma_t) chroma;
        if (n148i_encode_memory(&source, &options, &compatibility,
                                &compatibility_size) != N148I_OK ||
            n148i_decode_memory(compatibility, compatibility_size,
                                &compatibility_decoded) != N148I_OK)
            goto cleanup;
        n148i_free_buffer(compatibility);
        compatibility = NULL;
        compatibility_size = 0;
        n148i_free_image(&compatibility_decoded);
    }
    success = 1;

cleanup:
    printf("comparison,%s,scalar+AVX2,1+4,2,%d,%d,%zu,%u,%u,0.0,"
           "payload_revision_9_segment_filter_levels_2_1_1_0_"
           "dependencies_corruption_all_layouts_and_determinism,%s\n",
           name, original->width, original->height, scalar_size,
           info.payload_size, info.payload_size, success ? "PASS" : "FAIL");
    n148i_free_buffer(control); n148i_free_buffer(scalar);
    n148i_free_buffer(vector); n148i_free_buffer(parallel);
    n148i_free_buffer(compatibility); n148i_free_buffer(invalid); free(corrupt);
    n148i_free_image(&scalar_decoded); n148i_free_image(&vector_decoded);
    n148i_free_image(&parallel_decoded);
    n148i_free_image(&compatibility_decoded); n148i_free_image(&rejected);
    n148i_simd_force(N148I_SIMD_AUTO);
    n148_cpu_force(-1);
    n148_set_thread_count(1);
    return success;
}

static int validate_calibrated_luma_quantization(const Image *original, const char *name) {
    n148i_image_t source = {
        original->pixels, (uint32_t) original->width,
        (uint32_t) original->height, (size_t) original->width * 3u,
    };
    n148i_encode_options_t options;
    uint8_t *format_4_stream = NULL, *format_5_control = NULL, *scalar = NULL;
    uint8_t *vector = NULL, *parallel = NULL, *invalid = NULL;
    size_t format_4_size = 0, format_5_control_size = 0, scalar_size = 0;
    size_t vector_size = 0, parallel_size = 0, invalid_size = 0;
    n148i_image_t format_4_decoded = {0}, control_decoded = {0};
    n148i_image_t scalar_decoded = {0}, vector_decoded = {0};
    n148i_image_t parallel_decoded = {0}, rejected = {0};
    n148i_image_info_t info = {0};
    int success = 0;

    n148i_encode_options_init(&options);
    if (options.format_version != N148I_FORMAT_VERSION_7 ||
        options.feature_flags != N148I_DEFAULT_FEATURES ||
        options.effort != 3) goto cleanup;
    options.quality = 50;
    options.chroma = N148I_CHROMA_420;
    options.thread_count = 1;
    options.format_version = N148I_FORMAT_VERSION_4;
    options.feature_flags = N148I_FORMAT_4_DEFAULT_FEATURES;
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &format_4_stream,
                            &format_4_size) != N148I_OK ||
        n148i_decode_memory(format_4_stream, format_4_size,
                            &format_4_decoded) != N148I_OK)
        goto cleanup;

    /* Turning calibrated luma quantization off must reuse the exact accepted
       format 4 payload and
       reconstruction. Only the outer format byte is allowed to differ. */
    options.format_version = N148I_FORMAT_VERSION_5;
    if (n148i_encode_memory(&source, &options, &format_5_control,
                            &format_5_control_size) != N148I_OK ||
        format_5_control_size != format_4_size ||
        !same_stream_except_version(format_4_stream, format_5_control,
                                    format_4_size) ||
        n148i_decode_memory(format_5_control, format_5_control_size,
                            &control_decoded) != N148I_OK ||
        memcmp(format_4_decoded.pixels, control_decoded.pixels,
               format_4_decoded.stride * format_4_decoded.height) != 0)
        goto cleanup;

    options.feature_flags = N148I_PROFILE_CALIBRATED_LUMA_QUANT;
    if (n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_OK ||
        n148i_read_header(scalar, scalar_size, &info) != N148I_OK ||
        info.format_version != N148I_FORMAT_VERSION_5 ||
        info.feature_flags != N148I_PROFILE_CALIBRATED_LUMA_QUANT ||
        info.chroma_quality != 55 ||
        n148i_decode_memory(scalar, scalar_size, &scalar_decoded) != N148I_OK)
        goto cleanup;

    if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &vector, &vector_size) !=
            N148I_OK || vector_size != scalar_size ||
        memcmp(vector, scalar, scalar_size) != 0 ||
        n148i_decode_memory(vector, vector_size, &vector_decoded) != N148I_OK ||
        memcmp(vector_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;
    options.thread_count = 4;
    if (n148i_encode_memory(&source, &options, &parallel, &parallel_size) !=
            N148I_OK || parallel_size != scalar_size ||
        memcmp(parallel, scalar, scalar_size) != 0 ||
        n148i_decode_memory(parallel, parallel_size,
                            &parallel_decoded) != N148I_OK ||
        memcmp(parallel_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;

    options.thread_count = 1;
    options.feature_flags = N148I_PROFILE_CALIBRATED_LUMA_QUANT &
        ~N148I_FEATURE_CONTEXTUAL_RDO;
    if (n148i_encode_memory(&source, &options, &invalid, &invalid_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;
    invalid = (uint8_t *) malloc(scalar_size);
    if (!invalid) goto cleanup;
    memcpy(invalid, scalar, scalar_size);
    invalid[23] |= 0x80u;
    if (n148i_decode_memory(invalid, scalar_size, &rejected) !=
            N148I_ERROR_UNSUPPORTED_FEATURE) goto cleanup;
    success = 1;

cleanup:
    printf("comparison,%s,scalar+AVX2,1+4,2,%d,%d,%zu,%u,%u,0.0,"
           "format_4_payload_compatibility_calibrated_luma_feature_"
           "dependencies_and_determinism,%s\n",
           name, original->width, original->height, scalar_size,
           info.payload_size, info.payload_size, success ? "PASS" : "FAIL");
    n148i_free_buffer(format_4_stream); n148i_free_buffer(format_5_control);
    n148i_free_buffer(scalar); n148i_free_buffer(vector);
    n148i_free_buffer(parallel); n148i_free_buffer(invalid);
    n148i_free_image(&format_4_decoded); n148i_free_image(&control_decoded);
    n148i_free_image(&scalar_decoded); n148i_free_image(&vector_decoded);
    n148i_free_image(&parallel_decoded); n148i_free_image(&rejected);
    n148i_simd_force(N148I_SIMD_AUTO);
    n148_cpu_force(-1);
    n148_set_thread_count(1);
    return success;
}

static int validate_variable_luma_transform(const Image *original,
                                                const char *name) {
    n148i_image_t source = {
        original->pixels, (uint32_t) original->width,
        (uint32_t) original->height, (size_t) original->width * 3u,
    };
    n148i_encode_options_t options;
    uint8_t *calibrated_luma = NULL, *scalar = NULL, *vector = NULL;
    uint8_t *parallel = NULL, *all_features = NULL;
    uint8_t *legacy_quant = NULL, *invalid = NULL, *corrupt = NULL;
    size_t calibrated_luma_size = 0, scalar_size = 0, vector_size = 0;
    size_t parallel_size = 0, all_features_size = 0;
    size_t legacy_quant_size = 0, invalid_size = 0;
    n148i_image_t calibrated_luma_decoded = {0}, scalar_decoded = {0};
    n148i_image_t vector_decoded = {0}, parallel_decoded = {0};
    n148i_image_t all_features_decoded = {0}, legacy_quant_decoded = {0};
    n148i_image_t rejected = {0};
    n148i_image_info_t info = {0};
    N148SyntaxInspection inspection = {0};
    uint32_t stored_transform_count = 0;
    int success = 0;

    n148i_encode_options_init(&options);
    options.format_version = N148I_FORMAT_VERSION_5;
    options.quality = 30;
    options.chroma = N148I_CHROMA_420;
    options.thread_count = 1;
    options.feature_flags = N148I_PROFILE_CALIBRATED_LUMA_QUANT;
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &calibrated_luma,
                            &calibrated_luma_size) !=
            N148I_OK ||
        n148i_decode_memory(calibrated_luma, calibrated_luma_size,
                            &calibrated_luma_decoded) != N148I_OK)
        goto cleanup;

    options.feature_flags = N148I_PROFILE_VARIABLE_LUMA_TRANSFORM;
    if (n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_OK ||
        n148i_read_header(scalar, scalar_size, &info) != N148I_OK ||
        info.feature_flags != N148I_PROFILE_VARIABLE_LUMA_TRANSFORM ||
        info.encoded_header_size + info.payload_size != scalar_size ||
        info.payload_size < 28 ||
        scalar[info.encoded_header_size] != 11 ||
        scalar[info.encoded_header_size + 3] != 6 ||
        !inspect_variable_luma_stream(scalar, scalar_size, original, options.chroma,
                           options.feature_flags, &inspection) ||
        inspection.luma_transform_regions == 0 ||
        inspection.luma_transform_16x16 == 0 ||
        inspection.luma_transform_16x16 >
            inspection.luma_transform_regions ||
        n148i_decode_memory(scalar, scalar_size, &scalar_decoded) != N148I_OK ||
        scalar_decoded.width != source.width ||
        scalar_decoded.height != source.height)
        goto cleanup;
    stored_transform_count = validation_u32(
        scalar + info.encoded_header_size + 24);
    if (stored_transform_count != inspection.luma_transform_regions)
        goto cleanup;

    if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &vector, &vector_size) !=
            N148I_OK || vector_size != scalar_size ||
        memcmp(vector, scalar, scalar_size) != 0 ||
        n148i_decode_memory(vector, vector_size, &vector_decoded) != N148I_OK ||
        memcmp(vector_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;
    options.thread_count = 4;
    if (n148i_encode_memory(&source, &options, &parallel, &parallel_size) !=
            N148I_OK || parallel_size != scalar_size ||
        memcmp(parallel, scalar, scalar_size) != 0 ||
        n148i_decode_memory(parallel, parallel_size, &parallel_decoded) !=
            N148I_OK ||
        memcmp(parallel_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;

    /* The transform is independently switchable from calibrated luma
       table and remains composable with every retained opt-in experiment. */
    options.thread_count = 1;
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK) goto cleanup;
    options.feature_flags = N148I_PROFILE_VARIABLE_LUMA_TRANSFORM &
        ~N148I_FEATURE_CALIBRATED_LUMA_QUANT;
    if (n148i_encode_memory(&source, &options, &legacy_quant,
                            &legacy_quant_size) != N148I_OK ||
        n148i_decode_memory(legacy_quant, legacy_quant_size,
                            &legacy_quant_decoded) != N148I_OK)
        goto cleanup;
    options.feature_flags = N148I_FORMAT_5_FEATURE_MASK;
    if (n148i_encode_memory(&source, &options, &all_features,
                            &all_features_size) != N148I_OK ||
        n148i_decode_memory(all_features, all_features_size,
                            &all_features_decoded) != N148I_OK)
        goto cleanup;

    options.feature_flags = N148I_PROFILE_VARIABLE_LUMA_TRANSFORM &
        ~N148I_FEATURE_CONTEXTUAL_RDO;
    if (n148i_encode_memory(&source, &options, &invalid, &invalid_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;
    options.feature_flags = N148I_PROFILE_VARIABLE_LUMA_TRANSFORM &
        ~N148I_FEATURE_INTRA_4X4;
    if (n148i_encode_memory(&source, &options, &invalid, &invalid_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;

    corrupt = (uint8_t *) malloc(scalar_size);
    if (!corrupt) goto cleanup;
    memcpy(corrupt, scalar, scalar_size);
    corrupt[info.encoded_header_size] = 5;
    if (n148i_decode_memory(corrupt, scalar_size, &rejected) == N148I_OK)
        goto cleanup;
    memcpy(corrupt, scalar, scalar_size);
    corrupt[info.encoded_header_size + 3] &= (uint8_t) ~2u;
    if (n148i_decode_memory(corrupt, scalar_size, &rejected) == N148I_OK)
        goto cleanup;
    memcpy(corrupt, scalar, scalar_size);
    validation_put_u32(corrupt + info.encoded_header_size + 24,
                       stored_transform_count + 1u);
    if (n148i_decode_memory(corrupt, scalar_size, &rejected) == N148I_OK)
        goto cleanup;
    memcpy(corrupt, scalar, scalar_size);
    corrupt[21] &= (uint8_t) ~4u;
    if (n148i_decode_memory(corrupt, scalar_size, &rejected) == N148I_OK)
        goto cleanup;
    success = 1;

cleanup:
    printf("comparison,%s,scalar+AVX2,1+4,2,%d,%d,%zu,%u,%u,0.0,"
           "payload_revision_11_dct16_%llu_of_%llu_calibrated_luma_control_dependencies_"
           "counts_independent_switching_full_feature_composition_"
           "corruption_and_determinism,%s\n",
           name, original->width, original->height, scalar_size,
           info.payload_size, info.payload_size,
           (unsigned long long) inspection.luma_transform_16x16,
           (unsigned long long) inspection.luma_transform_regions,
           success ? "PASS" : "FAIL");
    n148i_free_buffer(calibrated_luma); n148i_free_buffer(scalar);
    n148i_free_buffer(vector); n148i_free_buffer(parallel);
    n148i_free_buffer(all_features); n148i_free_buffer(legacy_quant);
    n148i_free_buffer(invalid); free(corrupt);
    n148i_free_image(&calibrated_luma_decoded);
    n148i_free_image(&scalar_decoded);
    n148i_free_image(&vector_decoded); n148i_free_image(&parallel_decoded);
    n148i_free_image(&all_features_decoded);
    n148i_free_image(&legacy_quant_decoded);
    n148i_free_image(&rejected);
    n148i_simd_force(N148I_SIMD_AUTO);
    n148_cpu_force(-1);
    n148_set_thread_count(1);
    return success;
}

static int validate_perceptual_luma_trellis(const Image *original,
                                                const char *name) {
    n148i_image_t source = {
        original->pixels, (uint32_t) original->width,
        (uint32_t) original->height, (size_t) original->width * 3u,
    };
    n148i_encode_options_t options;
    uint8_t *control = NULL, *scalar = NULL, *vector = NULL;
    uint8_t *parallel = NULL, *layout = NULL, *invalid = NULL;
    size_t control_size = 0, scalar_size = 0, vector_size = 0;
    size_t parallel_size = 0, layout_size = 0, invalid_size = 0;
    n148i_image_t scalar_decoded = {0}, vector_decoded = {0};
    n148i_image_t parallel_decoded = {0};
    n148i_image_info_t info = {0};
    N148SyntaxInspection inspection = {0};
    int success = 0;

    n148i_encode_options_init(&options);
    options.format_version = N148I_FORMAT_VERSION_5;
    options.quality = 30;
    options.chroma = N148I_CHROMA_420;
    options.thread_count = 1;
    options.feature_flags = N148I_PROFILE_VARIABLE_LUMA_TRANSFORM;
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &control, &control_size) !=
            N148I_OK) goto cleanup;

    options.feature_flags = N148I_PROFILE_PERCEPTUAL_LUMA_TRELLIS;
    if (n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_OK ||
        (scalar_size == control_size &&
         memcmp(scalar, control, scalar_size) == 0) ||
        n148i_read_header(scalar, scalar_size, &info) != N148I_OK ||
        info.feature_flags != N148I_PROFILE_PERCEPTUAL_LUMA_TRELLIS ||
        !inspect_variable_luma_stream(scalar, scalar_size, original, options.chroma,
                           options.feature_flags, &inspection) ||
        n148i_decode_memory(scalar, scalar_size, &scalar_decoded) != N148I_OK)
        goto cleanup;

    if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &vector, &vector_size) !=
            N148I_OK || vector_size != scalar_size ||
        memcmp(vector, scalar, scalar_size) != 0 ||
        n148i_decode_memory(vector, vector_size, &vector_decoded) != N148I_OK ||
        memcmp(vector_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;
    options.thread_count = 4;
    if (n148i_simd_force(N148I_SIMD_AUTO) != N148I_OK ||
        n148i_encode_memory(&source, &options, &parallel, &parallel_size) !=
            N148I_OK || parallel_size != scalar_size ||
        memcmp(parallel, scalar, scalar_size) != 0 ||
        n148i_decode_memory(parallel, parallel_size,
                            &parallel_decoded) != N148I_OK ||
        memcmp(parallel_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;

    options.thread_count = 1;
    for (int chroma = N148I_CHROMA_444; chroma <= N148I_CHROMA_422;
         chroma++) {
        n148i_image_t decoded = {0};
        n148i_free_buffer(layout);
        layout = NULL;
        layout_size = 0;
        options.chroma = (n148i_chroma_t) chroma;
        int layout_ok = n148i_encode_memory(
                &source, &options, &layout, &layout_size) == N148I_OK &&
            n148i_decode_memory(layout, layout_size, &decoded) == N148I_OK;
        n148i_free_image(&decoded);
        if (!layout_ok) goto cleanup;
    }

    options.chroma = N148I_CHROMA_420;
    options.feature_flags = N148I_PROFILE_PERCEPTUAL_LUMA_TRELLIS &
        ~N148I_FEATURE_CONTEXTUAL_RDO;
    if (n148i_encode_memory(&source, &options, &invalid, &invalid_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;
    success = 1;

cleanup:
    printf("comparison,%s,scalar+AVX2,1+4,0+1+2,%d,%d,%zu,%u,%u,0.0,"
           "perceptual_luma_trellis_opt_in_all_layouts_"
           "dependencies_and_determinism,%s\n",
           name, original->width, original->height, scalar_size,
           info.payload_size, info.payload_size, success ? "PASS" : "FAIL");
    n148i_free_buffer(control); n148i_free_buffer(scalar);
    n148i_free_buffer(vector); n148i_free_buffer(parallel);
    n148i_free_buffer(layout); n148i_free_buffer(invalid);
    n148i_free_image(&scalar_decoded); n148i_free_image(&vector_decoded);
    n148i_free_image(&parallel_decoded);
    n148i_simd_force(N148I_SIMD_AUTO);
    n148_cpu_force(-1);
    n148_set_thread_count(1);
    return success;
}

static int validate_quant_adaptive_luma_filter(const Image *original,
                                                   const char *name) {
    n148i_image_t source = {
        original->pixels, (uint32_t) original->width,
        (uint32_t) original->height, (size_t) original->width * 3u,
    };
    n148i_encode_options_t options;
    uint8_t *control = NULL, *scalar = NULL, *vector = NULL;
    uint8_t *parallel = NULL, *layout = NULL, *same_control = NULL;
    uint8_t *same_candidate = NULL, *invalid = NULL;
    size_t control_size = 0, scalar_size = 0, vector_size = 0;
    size_t parallel_size = 0, layout_size = 0, same_control_size = 0;
    size_t same_candidate_size = 0, invalid_size = 0;
    n148i_image_t control_decoded = {0}, scalar_decoded = {0};
    n148i_image_t vector_decoded = {0}, parallel_decoded = {0};
    n148i_image_t same_control_decoded = {0}, same_candidate_decoded = {0};
    n148i_image_info_t info = {0};
    N148SyntaxInspection inspection = {0};
    int success = 0;

    n148i_encode_options_init(&options);
    options.format_version = N148I_FORMAT_VERSION_5;
    options.quality = 30;
    options.chroma = N148I_CHROMA_420;
    options.thread_count = 1;
    options.feature_flags = N148I_PROFILE_VARIABLE_LUMA_TRANSFORM;
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &control, &control_size) !=
            N148I_OK ||
        n148i_decode_memory(control, control_size, &control_decoded) !=
            N148I_OK) goto cleanup;

    options.feature_flags = N148I_PROFILE_QUANT_ADAPTIVE_LUMA_FILTER;
    if (n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_OK ||
        n148i_read_header(scalar, scalar_size, &info) != N148I_OK ||
        info.feature_flags != N148I_PROFILE_QUANT_ADAPTIVE_LUMA_FILTER ||
        !inspect_variable_luma_stream(scalar, scalar_size, original, options.chroma,
                           options.feature_flags, &inspection) ||
        n148i_decode_memory(scalar, scalar_size, &scalar_decoded) != N148I_OK ||
        memcmp(control_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) == 0 ||
        n148_loop_filter_quant_luma_strength(30) != 5 ||
        n148_loop_filter_quant_luma_strength(45) != 3 ||
        n148_loop_filter_quant_luma_strength(60) != 2 ||
        n148_loop_filter_quant_luma_strength(75) != 2 ||
        n148_loop_filter_quant_luma_strength(90) != 1 ||
        n148_loop_filter_quant_luma_strength(96) != 0 ||
        n148_loop_filter_quant_luma_strength(0) != -1) goto cleanup;

    if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &vector, &vector_size) !=
            N148I_OK || vector_size != scalar_size ||
        memcmp(vector, scalar, scalar_size) != 0 ||
        n148i_decode_memory(vector, vector_size, &vector_decoded) != N148I_OK ||
        memcmp(vector_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;
    options.thread_count = 4;
    if (n148i_simd_force(N148I_SIMD_AUTO) != N148I_OK ||
        n148i_encode_memory(&source, &options, &parallel, &parallel_size) !=
            N148I_OK || parallel_size != scalar_size ||
        memcmp(parallel, scalar, scalar_size) != 0 ||
        n148i_decode_memory(parallel, parallel_size,
                            &parallel_decoded) != N148I_OK ||
        memcmp(parallel_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;

    options.thread_count = 1;
    for (int chroma = N148I_CHROMA_444; chroma <= N148I_CHROMA_420;
         chroma++) {
        n148i_image_t decoded = {0};
        n148i_free_buffer(layout);
        layout = NULL;
        layout_size = 0;
        options.chroma = (n148i_chroma_t) chroma;
        int layout_ok = n148i_encode_memory(
                &source, &options, &layout, &layout_size) == N148I_OK &&
            n148i_decode_memory(layout, layout_size, &decoded) == N148I_OK;
        n148i_free_image(&decoded);
        if (!layout_ok) goto cleanup;
    }

    options.chroma = N148I_CHROMA_420;
    options.quality = 60;
    options.feature_flags = N148I_PROFILE_VARIABLE_LUMA_TRANSFORM;
    if (n148i_encode_memory(
            &source, &options, &same_control, &same_control_size) != N148I_OK ||
        n148i_decode_memory(same_control, same_control_size,
                            &same_control_decoded) != N148I_OK)
        goto cleanup;
    options.feature_flags = N148I_PROFILE_QUANT_ADAPTIVE_LUMA_FILTER;
    if (n148i_encode_memory(
            &source, &options, &same_candidate,
            &same_candidate_size) != N148I_OK ||
        same_candidate_size != same_control_size ||
        n148i_decode_memory(same_candidate, same_candidate_size,
                            &same_candidate_decoded) != N148I_OK ||
        memcmp(same_control_decoded.pixels, same_candidate_decoded.pixels,
               same_control_decoded.stride *
                   same_control_decoded.height) != 0)
        goto cleanup;

    options.quality = 30;
    options.feature_flags = N148I_PROFILE_QUANT_ADAPTIVE_LUMA_FILTER &
        ~N148I_FEATURE_LOOP_FILTER;
    if (n148i_encode_memory(&source, &options, &invalid, &invalid_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;
    n148i_free_buffer(invalid);
    invalid = NULL;
    invalid_size = 0;
    options.feature_flags = N148I_PROFILE_QUANT_ADAPTIVE_LUMA_FILTER &
        ~N148I_FEATURE_CALIBRATED_LUMA_QUANT;
    if (n148i_encode_memory(&source, &options, &invalid, &invalid_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;
    success = 1;

cleanup:
    printf("comparison,%s,scalar+AVX2,1+4,0+1+2,%d,%d,%zu,%u,%u,0.0,"
           "strengths_5_3_2_2_1_q60_exact_reconstruction_all_layouts_"
           "dependencies_and_determinism,%s\n",
           name, original->width, original->height, scalar_size,
           info.payload_size, info.payload_size, success ? "PASS" : "FAIL");
    n148i_free_buffer(control); n148i_free_buffer(scalar);
    n148i_free_buffer(vector); n148i_free_buffer(parallel);
    n148i_free_buffer(layout); n148i_free_buffer(same_control);
    n148i_free_buffer(same_candidate); n148i_free_buffer(invalid);
    n148i_free_image(&control_decoded); n148i_free_image(&scalar_decoded);
    n148i_free_image(&vector_decoded); n148i_free_image(&parallel_decoded);
    n148i_free_image(&same_control_decoded);
    n148i_free_image(&same_candidate_decoded);
    n148i_simd_force(N148I_SIMD_AUTO);
    n148_cpu_force(-1);
    n148_set_thread_count(1);
    return success;
}

static int validate_automatic_chroma(const Image *original,
                                         const char *name) {
    n148i_image_t source = {
        original->pixels, (uint32_t) original->width,
        (uint32_t) original->height, (size_t) original->width * 3u,
    };
    Image detail = {0};
    n148i_image_t detail_source = {0};
    n148i_encode_options_t options;
    uint8_t *fast = NULL, *fixed = NULL, *scalar = NULL, *explicit = NULL;
    uint8_t *vector = NULL, *parallel = NULL, *detail_stream = NULL;
    uint8_t *invalid = NULL;
    size_t fast_size = 0, fixed_size = 0, scalar_size = 0;
    size_t explicit_size = 0, vector_size = 0, parallel_size = 0;
    size_t detail_size = 0, invalid_size = 0;
    n148i_image_t decoded = {0}, detail_decoded = {0};
    n148i_image_info_t fast_info = {0}, info = {0}, detail_info = {0};
    int success = 0;

    n148i_encode_options_init(&options);
    options.quality = 50;
    options.chroma = N148I_CHROMA_AUTO;
    options.effort = 0;
    options.thread_count = 1;
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &fast, &fast_size) != N148I_OK ||
        n148i_read_header(fast, fast_size, &fast_info) != N148I_OK ||
        fast_info.chroma != N148I_CHROMA_420) goto cleanup;

    options.chroma = N148I_CHROMA_420;
    if (n148i_encode_memory(&source, &options, &fixed, &fixed_size) !=
            N148I_OK || fixed_size != fast_size ||
        memcmp(fixed, fast, fast_size) != 0) goto cleanup;

    options.chroma = N148I_CHROMA_AUTO;
    options.format_version = N148I_FORMAT_VERSION_4;
    options.feature_flags = N148I_FORMAT_4_DEFAULT_FEATURES;
    if (n148i_encode_memory(&source, &options, &invalid, &invalid_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;

    options.format_version = N148I_FORMAT_VERSION_5;
    options.feature_flags = N148I_PROFILE_CALIBRATED_LUMA_QUANT;
    options.quality = 75;
    options.effort = 5;
    if (n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_OK ||
        n148i_read_header(scalar, scalar_size, &info) != N148I_OK ||
        info.chroma < N148I_CHROMA_444 ||
        info.chroma > N148I_CHROMA_420 ||
        n148i_decode_memory(scalar, scalar_size, &decoded) != N148I_OK)
        goto cleanup;

    /* AUTO must be exactly one of the three independently usable streams;
       no encoder-only sentinel may leak into the file header. */
    options.chroma = info.chroma;
    if (n148i_encode_memory(&source, &options, &explicit, &explicit_size) !=
            N148I_OK || explicit_size != scalar_size ||
        memcmp(explicit, scalar, scalar_size) != 0) goto cleanup;

    options.chroma = N148I_CHROMA_AUTO;
    if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &vector, &vector_size) !=
            N148I_OK || vector_size != scalar_size ||
        memcmp(vector, scalar, scalar_size) != 0) goto cleanup;
    options.thread_count = 4;
    if (n148i_encode_memory(&source, &options, &parallel, &parallel_size) !=
            N148I_OK || parallel_size != scalar_size ||
        memcmp(parallel, scalar, scalar_size) != 0) goto cleanup;

    fill_chroma_detail_image(&detail);
    if (!detail.pixels) goto cleanup;
    detail_source.pixels = detail.pixels;
    detail_source.width = (uint32_t) detail.width;
    detail_source.height = (uint32_t) detail.height;
    detail_source.stride = (size_t) detail.width * 3u;
    options.thread_count = 1;
    options.quality = 95;
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&detail_source, &options,
                            &detail_stream, &detail_size) != N148I_OK ||
        n148i_read_header(detail_stream, detail_size, &detail_info) !=
            N148I_OK || detail_info.chroma != N148I_CHROMA_444 ||
        n148i_decode_memory(detail_stream, detail_size,
                            &detail_decoded) != N148I_OK) goto cleanup;
    success = 1;

cleanup:
    printf("comparison,%s,scalar+AVX2,1+4,3,%d,%d,%zu,%u,%u,0.0,"
           "effort0_exact_420_auto_is_concrete_best_candidate_"
           "high_frequency_fixture_selects_444_and_determinism,%s\n",
           name, original->width, original->height, scalar_size,
           info.payload_size, info.payload_size, success ? "PASS" : "FAIL");
    n148i_free_buffer(fast); n148i_free_buffer(fixed);
    n148i_free_buffer(scalar); n148i_free_buffer(explicit);
    n148i_free_buffer(vector); n148i_free_buffer(parallel);
    n148i_free_buffer(detail_stream); n148i_free_buffer(invalid);
    n148i_free_image(&decoded); n148i_free_image(&detail_decoded);
    free_image(&detail);
    n148i_simd_force(N148I_SIMD_AUTO);
    n148_cpu_force(-1);
    n148_set_thread_count(1);
    return success;
}

static int validate_fidelity_tools(const Image *original, const char *name) {
    n148i_image_t source = {
        original->pixels, (uint32_t) original->width,
        (uint32_t) original->height, (size_t) original->width * 3u,
    };
    n148i_encode_options_t options;
    uint8_t *format_5_stream = NULL, *compatibility = NULL, *scalar = NULL;
    uint8_t *vector = NULL, *combined = NULL, *invalid = NULL;
    size_t format_5_size = 0, compatibility_size = 0, scalar_size = 0;
    size_t vector_size = 0, combined_size = 0, invalid_size = 0;
    n148i_image_t compatibility_decoded = {0}, scalar_decoded = {0};
    n148i_image_t vector_decoded = {0}, combined_decoded = {0};
    n148i_image_info_t info = {0};
    N148SyntaxInspection inspection = {0};
    int32_t impulse[32 * 32] = {0};
    int32_t transformed[32 * 32], reconstructed[32 * 32];
    const char *failure = "initialization";
    int success = 0;

    n148i_encode_options_init(&options);
    if (options.format_version != N148I_FORMAT_VERSION_7 ||
        options.feature_flags != N148I_DEFAULT_FEATURES ||
        options.effort != 3 ||
        n148_variable_transform_matrix32_hash() !=
            0xb27f5da0e4d360b1ull) goto cleanup;
    impulse[0] = 127;
    impulse[31] = -63;
    impulse[32 * 31] = 31;
    if (!n148_variable_forward(impulse, 32, transformed) ||
        !n148_variable_inverse(transformed, 32, reconstructed)) goto cleanup;
    for (int index = 0; index < 32 * 32; index++)
        if (abs(reconstructed[index] - impulse[index]) > 1) goto cleanup;

    options.quality = 30;
    options.chroma = N148I_CHROMA_420;
    options.thread_count = 1;
    options.format_version = N148I_FORMAT_VERSION_5;
    options.feature_flags = N148I_FORMAT_5_DEFAULT_FEATURES;
    failure = "format 5 reference encode";
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &format_5_stream,
                            &format_5_size) != N148I_OK)
        goto cleanup;

    options.format_version = N148I_FORMAT_VERSION_6;
    failure = "format 6 compatibility encode/decode";
    if (n148i_encode_memory(&source, &options, &compatibility,
                            &compatibility_size) != N148I_OK ||
        compatibility_size != format_5_size ||
        !same_stream_except_version(format_5_stream, compatibility,
                                    format_5_size) ||
        n148i_decode_memory(compatibility, compatibility_size,
                            &compatibility_decoded) != N148I_OK)
        goto cleanup;

    options.feature_flags = N148I_PROFILE_LUMA_TRANSFORM_32X32;
    failure = "format 6 dct32 encode/decode/inspect";
    if (n148i_encode_memory(&source, &options, &scalar, &scalar_size) !=
            N148I_OK) goto cleanup;
    failure = "format 6 dct32 header";
    if (n148i_read_header(scalar, scalar_size, &info) != N148I_OK ||
        info.format_version != N148I_FORMAT_VERSION_6 ||
        info.feature_flags != N148I_PROFILE_LUMA_TRANSFORM_32X32) goto cleanup;
    failure = "format 6 dct32 decode";
    if (n148i_decode_memory(scalar, scalar_size, &scalar_decoded) !=
            N148I_OK) goto cleanup;
    failure = "format 6 dct32 inspect";
    if (!n148_predictive_inspect(
            scalar + N148_EXTENDED_HEADER_SIZE, info.metadata_size,
            scalar + info.encoded_header_size, info.payload_size,
            original->width, original->height, N148I_CHROMA_420,
            info.feature_flags & N148_FORMAT_3_SUPPORTED_FEATURES, 0, 0, 0, 1,
            1, &inspection)) goto cleanup;

    options.thread_count = 4;
    failure = "format 6 dct32 simd/thread determinism";
    if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &vector, &vector_size) !=
            N148I_OK || vector_size != scalar_size ||
        memcmp(vector, scalar, scalar_size) != 0 ||
        n148i_decode_memory(vector, vector_size, &vector_decoded) !=
            N148I_OK ||
        memcmp(vector_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;

    options.thread_count = 1;
    options.feature_flags = N148I_PROFILE_COMBINED_INTRA_PREDICTION;
    failure = "format 6 combined prediction roundtrip";
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &combined, &combined_size) !=
            N148I_OK ||
        n148i_decode_memory(combined, combined_size, &combined_decoded) !=
            N148I_OK) goto cleanup;

    options.feature_flags = N148I_PROFILE_LUMA_TRANSFORM_32X32 &
        ~N148I_FEATURE_LUMA_TRANSFORM_16X16;
    failure = "format 6 dct32 dependency on dct16";
    if (n148i_encode_memory(&source, &options, &invalid, &invalid_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;
    options.feature_flags = N148I_PROFILE_LUMA_TRANSFORM_32X32 &
        ~N148I_FEATURE_CALIBRATED_LUMA_QUANT;
    failure = "format 6 dct32 dependency on calibrated luma";
    if (n148i_encode_memory(&source, &options, &invalid, &invalid_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;
    options.format_version = N148I_FORMAT_VERSION_5;
    options.feature_flags = N148I_PROFILE_LUMA_TRANSFORM_32X32;
    failure = "format 5 rejects format 6 features";
    if (n148i_encode_memory(&source, &options, &invalid, &invalid_size) !=
            N148I_ERROR_UNSUPPORTED_FEATURE) goto cleanup;
    success = 1;
    failure = "none";

cleanup:
    printf("comparison,%s,scalar+AVX2,1+4,2,%d,%d,%zu,%u,%u,0.0,"
           "format_6_compatibility_dct32_%llu_combined_prediction_"
           "dependencies_matrix_hash_and_determinism,%s\n",
           name, original->width, original->height, scalar_size,
           info.payload_size, info.payload_size,
           (unsigned long long) inspection.luma_transform_32x32,
           success ? "PASS" : "FAIL");
    if (!success) fprintf(stderr, "format 6 fidelity failure: %s\n", failure);
    n148i_free_buffer(format_5_stream); n148i_free_buffer(compatibility);
    n148i_free_buffer(scalar); n148i_free_buffer(vector);
    n148i_free_buffer(combined); n148i_free_buffer(invalid);
    n148i_free_image(&compatibility_decoded);
    n148i_free_image(&scalar_decoded); n148i_free_image(&vector_decoded);
    n148i_free_image(&combined_decoded);
    n148i_simd_force(N148I_SIMD_AUTO);
    n148_cpu_force(-1);
    n148_set_thread_count(1);
    return success;
}

static int validate_adaptive_rich_context(const Image *original,
                                         const char *name) {
    n148i_image_t source = {
        original->pixels, (uint32_t) original->width,
        (uint32_t) original->height, (size_t) original->width * 3u,
    };
    n148i_encode_options_t options;
    uint8_t *format_6_stream = NULL, *compatibility = NULL, *adaptive = NULL;
    uint8_t *scalar = NULL, *parallel = NULL, *invalid = NULL;
    uint8_t *multiple = NULL, *multiple_parallel = NULL;
    uint8_t *corrupt = NULL;
    size_t format_6_size = 0, compatibility_size = 0, adaptive_size = 0;
    size_t scalar_size = 0, parallel_size = 0, invalid_size = 0;
    size_t multiple_size = 0, multiple_parallel_size = 0;
    n148i_image_t format_6_decoded = {0}, compatibility_decoded = {0};
    n148i_image_t adaptive_decoded = {0}, scalar_decoded = {0};
    n148i_image_t parallel_decoded = {0}, rejected = {0};
    n148i_image_t multiple_decoded = {0};
    n148i_image_info_t info = {0};
    N148SyntaxInspection inspection = {0};
    const char *failure = "initialization";
    int success = 0;

    n148i_encode_options_init(&options);
    if (options.format_version != N148I_FORMAT_VERSION_7 ||
        options.feature_flags != N148I_DEFAULT_FEATURES ||
        options.effort != 3) goto cleanup;
    options.quality = 50;
    options.chroma = N148I_CHROMA_420;
    options.thread_count = 1;
    options.format_version = N148I_FORMAT_VERSION_6;
    options.feature_flags = N148I_FORMAT_6_DEFAULT_FEATURES;
    failure = "format 6 reference encode/decode";
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &format_6_stream,
                            &format_6_size) != N148I_OK ||
        n148i_decode_memory(format_6_stream, format_6_size,
                            &format_6_decoded) != N148I_OK)
        goto cleanup;

    /* With every format 7 tool disabled, format 7 must be an exact syntax
       wrapper around the accepted format 6 stream. */
    options.format_version = N148I_FORMAT_VERSION_7;
    failure = "format 7 compatibility stream";
    if (n148i_encode_memory(&source, &options, &compatibility,
                            &compatibility_size) != N148I_OK ||
        compatibility_size != format_6_size ||
        !same_stream_except_version(format_6_stream, compatibility,
                                    format_6_size) ||
        n148i_decode_memory(compatibility, compatibility_size,
                            &compatibility_decoded) != N148I_OK ||
        memcmp(format_6_decoded.pixels, compatibility_decoded.pixels,
               format_6_decoded.stride * format_6_decoded.height) != 0)
        goto cleanup;

    options.feature_flags = N148I_PROFILE_ADAPTIVE_ENTROPY;
    failure = "adaptive-only roundtrip";
    if (n148i_encode_memory(&source, &options, &adaptive,
                            &adaptive_size) != N148I_OK ||
        n148i_decode_memory(adaptive, adaptive_size,
                            &adaptive_decoded) != N148I_OK ||
        memcmp(format_6_decoded.pixels, adaptive_decoded.pixels,
               format_6_decoded.stride * format_6_decoded.height) != 0)
        goto cleanup;

    options.feature_flags = N148I_PROFILE_RICH_COEFFICIENT_CONTEXTS;
    /* Effort 3 may choose different intra modes in the rich format 7 profile.
       Validate its syntax and reconstruction independently of format 6. */
    failure = "rich adaptive encode/header/decode";
    if (n148i_encode_memory(&source, &options, &scalar,
                            &scalar_size) != N148I_OK ||
        scalar_size == 0 ||
        n148i_read_header(scalar, scalar_size, &info) != N148I_OK ||
        info.format_version != N148I_FORMAT_VERSION_7 ||
        info.feature_flags != N148I_PROFILE_RICH_COEFFICIENT_CONTEXTS ||
        n148i_decode_memory(scalar, scalar_size, &scalar_decoded) !=
            N148I_OK ||
        scalar_decoded.width != source.width ||
        scalar_decoded.height != source.height ||
        !n148_inspect_format_7(
            scalar + N148_EXTENDED_HEADER_SIZE, info.metadata_size,
            scalar + info.encoded_header_size, info.payload_size,
            original->width, original->height, N148I_CHROMA_420,
            info.feature_flags, &inspection))
        goto cleanup;

    options.thread_count = 4;
    failure = "format 7 SIMD/thread determinism";
    if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &parallel,
                            &parallel_size) != N148I_OK ||
        parallel_size != scalar_size ||
        memcmp(parallel, scalar, scalar_size) != 0 ||
        n148i_decode_memory(parallel, parallel_size,
                            &parallel_decoded) != N148I_OK ||
        memcmp(parallel_decoded.pixels, scalar_decoded.pixels,
               scalar_decoded.stride * scalar_decoded.height) != 0)
        goto cleanup;

    options.thread_count = 1;
    options.feature_flags = N148I_PROFILE_RICH_COEFFICIENT_CONTEXTS &
        ~N148I_FEATURE_ADAPTIVE_ENTROPY;
    failure = "rich-context dependency";
    if (n148i_encode_memory(&source, &options, &invalid, &invalid_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;
    options.feature_flags = N148I_PROFILE_MULTIPLE_INTRA_REFERENCES;
    failure = "multiple-reference encode/header/decode/inspection";
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &multiple, &multiple_size) !=
            N148I_OK ||
        n148i_read_header(multiple, multiple_size, &info) != N148I_OK ||
        info.feature_flags != N148I_PROFILE_MULTIPLE_INTRA_REFERENCES ||
        n148i_decode_memory(multiple, multiple_size, &multiple_decoded) !=
            N148I_OK ||
        !n148_inspect_format_7(
            multiple + N148_EXTENDED_HEADER_SIZE, info.metadata_size,
            multiple + info.encoded_header_size, info.payload_size,
            original->width, original->height, N148I_CHROMA_420,
            info.feature_flags, &inspection) ||
        inspection.luma_reference_histogram[0] +
            inspection.luma_reference_histogram[1] +
            inspection.luma_reference_histogram[2] == 0)
        goto cleanup;

    options.thread_count = 4;
    failure = "multiple-reference SIMD/thread determinism";
    if (n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &multiple_parallel,
                            &multiple_parallel_size) != N148I_OK ||
        multiple_parallel_size != multiple_size ||
        memcmp(multiple_parallel, multiple, multiple_size) != 0)
        goto cleanup;

    options.thread_count = 1;
    options.feature_flags = N148I_PROFILE_MULTIPLE_INTRA_REFERENCES &
        ~N148I_FEATURE_RICH_COEFFICIENT_CONTEXTS;
    failure = "multiple-reference rich-context dependency";
    if (n148i_encode_memory(&source, &options, &invalid, &invalid_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;
    options.feature_flags = N148I_PROFILE_MULTIPLE_INTRA_REFERENCES &
        ~N148I_FEATURE_CONTEXTUAL_RDO;
    failure = "multiple-reference RDO dependency";
    if (n148i_encode_memory(&source, &options, &invalid, &invalid_size) !=
            N148I_ERROR_INVALID_ARGUMENT) goto cleanup;
    options.feature_flags = N148I_PROFILE_DIRECTIONAL_SCAN;
    failure = "reserved directional-scan rejection";
    if (n148i_encode_memory(&source, &options, &invalid, &invalid_size) !=
            N148I_ERROR_UNSUPPORTED_FEATURE) goto cleanup;
    options.format_version = N148I_FORMAT_VERSION_6;
    options.feature_flags = N148I_PROFILE_RICH_COEFFICIENT_CONTEXTS;
    failure = "format 6 rejects format 7 features";
    if (n148i_encode_memory(&source, &options, &invalid, &invalid_size) !=
            N148I_ERROR_UNSUPPORTED_FEATURE) goto cleanup;

    failure = "truncated/corrupt format 7 rejection";
    if (n148i_decode_memory(scalar, scalar_size - 1, &rejected) !=
            N148I_ERROR_TRUNCATED_DATA) goto cleanup;
    corrupt = (uint8_t *) malloc(scalar_size);
    if (!corrupt) goto cleanup;
    memcpy(corrupt, scalar, scalar_size);
    corrupt[N148_EXTENDED_HEADER_SIZE] = 0xffu;
    if (n148i_decode_memory(corrupt, scalar_size, &rejected) == N148I_OK)
        goto cleanup;
    success = 1;
    failure = "none";

cleanup:
    printf("comparison,%s,scalar+AVX2,1+4,2,%d,%d,%zu,%u,%u,0.0,"
           "format_7_format_6_compatibility_adaptive_rich_context_state_"
           "fallback_multiple_references_dependencies_and_determinism,%s\n",
           name, original->width, original->height, scalar_size,
           info.payload_size, info.payload_size,
           success ? "PASS" : "FAIL");
    if (!success)
        fprintf(stderr, "format 7 adaptive-context failure: %s\n", failure);
    n148i_free_buffer(format_6_stream); n148i_free_buffer(compatibility);
    n148i_free_buffer(adaptive); n148i_free_buffer(scalar);
    n148i_free_buffer(parallel); n148i_free_buffer(invalid);
    n148i_free_buffer(multiple); n148i_free_buffer(multiple_parallel);
    free(corrupt);
    n148i_free_image(&format_6_decoded);
    n148i_free_image(&compatibility_decoded);
    n148i_free_image(&adaptive_decoded);
    n148i_free_image(&scalar_decoded);
    n148i_free_image(&parallel_decoded);
    n148i_free_image(&multiple_decoded);
    n148i_free_image(&rejected);
    n148i_simd_force(N148I_SIMD_AUTO);
    n148_cpu_force(-1);
    n148_set_thread_count(1);
    return success;
}

static int validate_format_7_full_trellis(const Image *original) {
    n148i_image_t source = {
        original->pixels, (uint32_t)original->width,
        (uint32_t)original->height, (size_t)original->width * 3u,
    };
    n148i_encode_options_t options;
    n148i_encode_options_init(&options);
    options.quality = 60;
    options.thread_count = 1;
    options.feature_flags = N148I_FORMAT_7_FULL_TRELLIS_FEATURES;
    uint8_t *scalar = NULL, *vector = NULL;
    size_t scalar_size = 0, vector_size = 0;
    n148i_image_t decoded = {0};
    n148i_image_info_t info = {0};
    int success =
        n148i_simd_force(N148I_SIMD_SCALAR) == N148I_OK &&
        n148i_encode_memory(&source, &options, &scalar,
                            &scalar_size) == N148I_OK &&
        n148i_read_header(scalar, scalar_size, &info) == N148I_OK &&
        info.feature_flags == N148I_FORMAT_7_FULL_TRELLIS_FEATURES &&
        n148i_simd_force(N148I_SIMD_AVX2) == N148I_OK &&
        n148i_encode_memory(&source, &options, &vector,
                            &vector_size) == N148I_OK &&
        scalar_size == vector_size &&
        memcmp(scalar, vector, scalar_size) == 0 &&
        n148i_decode_memory(vector, vector_size, &decoded) == N148I_OK &&
        decoded.width == source.width && decoded.height == source.height;
    printf("comparison,format_7_full_trellis,scalar+AVX2,1,2,%d,%d,%zu,"
           "%u,%u,0.0,explicit_full_trellis_roundtrip_and_determinism,%s\n",
           original->width, original->height, scalar_size,
           info.payload_size, info.payload_size,
           success ? "PASS" : "FAIL");
    n148i_free_buffer(scalar);
    n148i_free_buffer(vector);
    n148i_free_image(&decoded);
    n148i_simd_force(N148I_SIMD_AUTO);
    return success;
}

static int validate_format_7_spectral_luma(const Image *original) {
    n148i_image_t source = {
        original->pixels, (uint32_t) original->width,
        (uint32_t) original->height, (size_t) original->width * 3u,
    };
    n148i_encode_options_t options;
    n148i_encode_options_init(&options);
    options.quality = 60;
    options.thread_count = 1;
    uint8_t *baseline = NULL, *scalar = NULL, *vector = NULL;
    uint8_t *invalid = NULL;
    size_t baseline_size = 0, scalar_size = 0, vector_size = 0;
    size_t invalid_size = 0;
    n148i_image_t baseline_rgb = {0}, spectral_rgb = {0};
    n148i_image_info_t info = {0};
    int success = 0;
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &baseline,
                            &baseline_size) != N148I_OK ||
        n148i_decode_memory(baseline, baseline_size, &baseline_rgb) !=
            N148I_OK) goto cleanup;
    options.feature_flags = N148I_PROFILE_SPECTRAL_LUMA_QUANT;
    if (n148i_encode_memory(&source, &options, &scalar,
                            &scalar_size) != N148I_OK ||
        n148i_read_header(scalar, scalar_size, &info) != N148I_OK ||
        info.format_version != N148I_FORMAT_VERSION_7 ||
        info.feature_flags != N148I_PROFILE_SPECTRAL_LUMA_QUANT ||
        n148i_decode_memory(scalar, scalar_size, &spectral_rgb) != N148I_OK ||
        spectral_rgb.width != source.width ||
        spectral_rgb.height != source.height ||
        memcmp(baseline_rgb.pixels, spectral_rgb.pixels,
               spectral_rgb.stride * spectral_rgb.height) == 0 ||
        n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &vector,
                            &vector_size) != N148I_OK ||
        vector_size != scalar_size ||
        memcmp(vector, scalar, scalar_size) != 0)
        goto cleanup;
    options.feature_flags &= ~N148I_FEATURE_CALIBRATED_LUMA_QUANT;
    if (n148i_encode_memory(&source, &options, &invalid,
                            &invalid_size) != N148I_ERROR_INVALID_ARGUMENT)
        goto cleanup;
    options.format_version = N148I_FORMAT_VERSION_6;
    options.feature_flags = N148I_FORMAT_6_DEFAULT_FEATURES |
        N148I_FORMAT_7_SPECTRAL_LUMA_QUANT;
    if (n148i_encode_memory(&source, &options, &invalid,
                            &invalid_size) != N148I_ERROR_UNSUPPORTED_FEATURE)
        goto cleanup;
    success = 1;
cleanup:
    printf("comparison,format_7_spectral_luma,scalar+AVX2,1,2,%d,%d,%zu,"
           "%u,%u,0.0,flagged_table_roundtrip_old_profile_isolated_"
           "dependencies_and_determinism,%s\n",
           original->width, original->height, scalar_size,
           info.payload_size, info.payload_size,
           success ? "PASS" : "FAIL");
    n148i_free_buffer(baseline);
    n148i_free_buffer(scalar);
    n148i_free_buffer(vector);
    n148i_free_buffer(invalid);
    n148i_free_image(&baseline_rgb);
    n148i_free_image(&spectral_rgb);
    n148i_simd_force(N148I_SIMD_AUTO);
    return success;
}

static int validate_format_7_refined_spectral_luma(const Image *original) {
    n148i_image_t source = {
        original->pixels, (uint32_t) original->width,
        (uint32_t) original->height, (size_t) original->width * 3u,
    };
    n148i_encode_options_t options;
    n148i_encode_options_init(&options);
    options.quality = 60;
    options.thread_count = 1;
    options.feature_flags = N148I_PROFILE_SPECTRAL_LUMA_QUANT;
    uint8_t *spectral = NULL, *scalar = NULL, *vector = NULL;
    uint8_t *invalid = NULL;
    size_t spectral_size = 0, scalar_size = 0, vector_size = 0;
    size_t invalid_size = 0;
    n148i_image_t spectral_rgb = {0}, refined_rgb = {0};
    n148i_image_info_t info = {0};
    int success = 0;
    if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
        n148i_encode_memory(&source, &options, &spectral,
                            &spectral_size) != N148I_OK ||
        n148i_decode_memory(spectral, spectral_size, &spectral_rgb) !=
            N148I_OK) goto cleanup;
    options.feature_flags = N148I_PROFILE_REFINED_SPECTRAL_LUMA_QUANT;
    if (n148i_encode_memory(&source, &options, &scalar,
                            &scalar_size) != N148I_OK ||
        n148i_read_header(scalar, scalar_size, &info) != N148I_OK ||
        info.format_version != N148I_FORMAT_VERSION_7 ||
        info.feature_flags != N148I_PROFILE_REFINED_SPECTRAL_LUMA_QUANT ||
        n148i_decode_memory(scalar, scalar_size, &refined_rgb) != N148I_OK ||
        refined_rgb.width != source.width ||
        refined_rgb.height != source.height ||
        memcmp(spectral_rgb.pixels, refined_rgb.pixels,
               refined_rgb.stride * refined_rgb.height) == 0 ||
        n148i_simd_force(N148I_SIMD_AVX2) != N148I_OK ||
        n148i_encode_memory(&source, &options, &vector,
                            &vector_size) != N148I_OK ||
        vector_size != scalar_size ||
        memcmp(vector, scalar, scalar_size) != 0)
        goto cleanup;
    options.feature_flags &= ~N148I_FORMAT_7_SPECTRAL_LUMA_QUANT;
    if (n148i_encode_memory(&source, &options, &invalid,
                            &invalid_size) != N148I_ERROR_INVALID_ARGUMENT)
        goto cleanup;
    options.feature_flags = N148I_PROFILE_REFINED_SPECTRAL_LUMA_QUANT &
        ~N148I_FEATURE_CALIBRATED_LUMA_QUANT;
    if (n148i_encode_memory(&source, &options, &invalid,
                            &invalid_size) != N148I_ERROR_INVALID_ARGUMENT)
        goto cleanup;
    options.format_version = N148I_FORMAT_VERSION_6;
    options.feature_flags = N148I_FORMAT_6_DEFAULT_FEATURES |
        N148I_FORMAT_7_REFINED_SPECTRAL_LUMA_QUANT;
    if (n148i_encode_memory(&source, &options, &invalid,
                            &invalid_size) != N148I_ERROR_UNSUPPORTED_FEATURE)
        goto cleanup;
    success = 1;
cleanup:
    printf("comparison,format_7_refined_spectral_luma,scalar+AVX2,1,2,%d,%d,%zu,"
           "%u,%u,0.0,refined_table_roundtrip_old_spectral_isolated_"
           "dependencies_and_determinism,%s\n",
           original->width, original->height, scalar_size,
           info.payload_size, info.payload_size,
           success ? "PASS" : "FAIL");
    n148i_free_buffer(spectral);
    n148i_free_buffer(scalar);
    n148i_free_buffer(vector);
    n148i_free_buffer(invalid);
    n148i_free_image(&spectral_rgb);
    n148i_free_image(&refined_rgb);
    n148i_simd_force(N148I_SIMD_AUTO);
    return success;
}

static int validate_format_7_structural_luma(void) {
    const int widths[] = {1, 2, 3, 7, 8, 9, 15, 16, 17, 31, 32, 33};
    const int heights[] = {1, 3, 2, 8, 7, 9, 16, 15, 19, 32, 31, 35};
    const int qualities[] = {1, 30, 60, 100};
    const int efforts[] = {0, 3, 5, 9};
    const uint32_t required[] = {
        N148I_FORMAT_7_REFINED_SPECTRAL_LUMA_QUANT,
        N148I_FEATURE_SEGMENTATION, N148I_FEATURE_CONTEXTUAL_RDO,
        N148I_FEATURE_CALIBRATED_CHROMA_QUANT,
        N148I_FEATURE_LUMA_TRANSFORM_16X16,
    };
    int completed = 0;
    for (int trial = 0; trial < 24; trial++) {
        int width = widths[trial % 12], height = heights[trial % 12];
        size_t row = (size_t)width * 3, stride = row + 13;
        size_t pixel_bytes = row * (size_t)height;
        size_t padded_bytes = stride * (size_t)(height - 1) + row;
        uint8_t *tight = malloc(pixel_bytes), *padded = malloc(padded_bytes);
        uint8_t *encoded[2] = {NULL, NULL};
        size_t sizes[2] = {0, 0};
        n148i_image_t decoded[2] = {{0}, {0}};
        n148i_image_info_t info = {0};
        int success = 0;
        if (!tight || !padded) goto cleanup;
        uint32_t random = 731871u + (uint32_t)trial;
        for (size_t i = 0; i < pixel_bytes; i++) {
            random = random * 1664525u + 1013904223u;
            tight[i] = trial % 3 ? (uint8_t)(random >> 24) :
                (uint8_t)((i % 7 < 3) ? 0 : 255);
        }
        memset(padded, 0xa5, padded_bytes);
        for (int y = 0; y < height; y++)
            memcpy(padded + (size_t)y * stride, tight + (size_t)y * row, row);
        n148i_image_t source[2] = {
            {tight, (uint32_t)width, (uint32_t)height, trial % 2 ? row : 0},
            {padded, (uint32_t)width, (uint32_t)height, stride},
        };
        n148i_encode_options_t options;
        n148i_encode_options_init(&options);
        options.feature_flags = N148I_PROFILE_STRUCTURAL_LUMA_QUANT;
        options.quality = qualities[trial % 4];
        options.chroma = (n148i_chroma_t)(trial / 6);
        options.effort = efforts[(trial / 3) % 4];
        options.thread_count = 1;
        if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
            n148i_encode_memory(&source[0], &options, &encoded[0], &sizes[0]) != N148I_OK ||
            n148i_read_header(encoded[0], sizes[0], &info) != N148I_OK ||
            !(info.feature_flags & N148I_FORMAT_7_STRUCTURAL_LUMA_QUANT) ||
            info.chroma_quality != options.quality ||
            n148i_decode_memory(encoded[0], sizes[0], &decoded[0]) != N148I_OK)
            goto cleanup;
        options.chroma_quality = options.quality;
        if (n148i_simd_force(N148I_SIMD_AUTO) != N148I_OK ||
            n148i_encode_memory(&source[1], &options, &encoded[1], &sizes[1]) != N148I_OK ||
            sizes[0] != sizes[1] || memcmp(encoded[0], encoded[1], sizes[0]) ||
            n148i_decode_memory(encoded[1], sizes[1], &decoded[1]) != N148I_OK ||
            decoded[0].width != (uint32_t)width || decoded[0].height != (uint32_t)height ||
            decoded[1].width != (uint32_t)width || decoded[1].height != (uint32_t)height ||
            memcmp(decoded[0].pixels, decoded[1].pixels, pixel_bytes))
            goto cleanup;
        if (trial == 0) {
            uint32_t original_flags = info.feature_flags;
            for (size_t j = 0; j < sizeof(required) / sizeof(required[0]); j++) {
                uint32_t invalid_flags = original_flags & ~required[j];
                for (int byte = 0; byte < 4; byte++)
                    encoded[0][20 + byte] = (uint8_t)(invalid_flags >> (8 * byte));
                n148i_image_info_t invalid_info = {0};
                n148i_image_t invalid_image = {0};
                int header_status = n148i_read_header(encoded[0], sizes[0], &invalid_info);
                int decode_status = n148i_decode_memory(encoded[0], sizes[0], &invalid_image);
                n148i_free_image(&invalid_image);
                if (header_status == N148I_OK || decode_status == N148I_OK)
                    goto cleanup;
            }
            for (int byte = 0; byte < 4; byte++)
                encoded[0][20 + byte] = (uint8_t)(original_flags >> (8 * byte));
        }
        success = 1;
cleanup:
        for (int i = 0; i < 2; i++) {
            n148i_free_buffer(encoded[i]);
            n148i_free_image(&decoded[i]);
        }
        free(tight);
        free(padded);
        n148i_simd_force(N148I_SIMD_AUTO);
        if (!success) break;
        completed++;
    }
    printf("comparison,format_7_structural_luma,scalar+auto,1,2,33,35,0,0,0,0.0,"
           "24_odd_stride_chroma_effort_pairs_extreme_quality_dependencies,%s\n",
           completed == 24 ? "PASS" : "FAIL");
    return completed == 24;
}

static int validate_format_7_reconstruction(uint32_t profile, int detail) {
    const int widths[] = {1, 2, 3, 7, 8, 9, 15, 16, 17, 31, 32, 33};
    const int heights[] = {1, 3, 2, 8, 7, 9, 16, 15, 19, 32, 31, 35};
    const int qualities[] = {1, 30, 60, 100};
    const int efforts[] = {0, 3, 5, 9};
    const uint32_t required[] = {
        N148I_FORMAT_7_STRUCTURAL_LUMA_QUANT,
        N148I_FORMAT_7_REFINED_SPECTRAL_LUMA_QUANT,
        N148I_FEATURE_SEGMENTATION, N148I_FEATURE_CONTEXTUAL_RDO,
        N148I_FEATURE_CALIBRATED_CHROMA_QUANT,
        N148I_FEATURE_LUMA_TRANSFORM_16X16,
        N148I_FORMAT_7_BALANCED_RECONSTRUCTION,
    };
    int completed = 0;
    for (int trial = 0; trial < 24; trial++) {
        int width = widths[trial % 12], height = heights[trial % 12];
        size_t row = (size_t)width * 3, stride = row + 13;
        size_t pixel_bytes = row * (size_t)height;
        size_t padded_bytes = stride * (size_t)(height - 1) + row;
        uint8_t *tight = malloc(pixel_bytes), *padded = malloc(padded_bytes);
        uint8_t *encoded[2] = {NULL, NULL};
        size_t sizes[2] = {0, 0};
        n148i_image_t decoded[2] = {{0}, {0}};
        n148i_image_info_t info = {0};
        int success = 0;
        if (!tight || !padded) goto cleanup;
        uint32_t random = 731871u + (uint32_t)trial;
        for (size_t i = 0; i < pixel_bytes; i++) {
            random = random * 1664525u + 1013904223u;
            tight[i] = trial % 3 ? (uint8_t)(random >> 24) :
                (uint8_t)((i % 7 < 3) ? 0 : 255);
        }
        memset(padded, 0xa5, padded_bytes);
        for (int y = 0; y < height; y++)
            memcpy(padded + (size_t)y * stride, tight + (size_t)y * row, row);
        n148i_image_t source[2] = {
            {tight, (uint32_t)width, (uint32_t)height, trial % 2 ? row : 0},
            {padded, (uint32_t)width, (uint32_t)height, stride},
        };
        n148i_encode_options_t options;
        n148i_encode_options_init(&options);
        options.feature_flags = profile;
        options.quality = qualities[trial % 4];
        options.chroma = (n148i_chroma_t)(trial / 6);
        options.effort = efforts[(trial / 3 + (detail ? 2 : 0)) % 4];
        options.thread_count = 1;
        if (n148i_simd_force(N148I_SIMD_SCALAR) != N148I_OK ||
            n148i_encode_memory(&source[0], &options, &encoded[0], &sizes[0]) != N148I_OK ||
            n148i_read_header(encoded[0], sizes[0], &info) != N148I_OK ||
            !(info.feature_flags & (detail ? N148I_FORMAT_7_DETAIL_RECONSTRUCTION :
                                     N148I_FORMAT_7_BALANCED_RECONSTRUCTION)) ||
            info.chroma_quality != options.quality ||
            n148i_decode_memory(encoded[0], sizes[0], &decoded[0]) != N148I_OK)
            goto cleanup;
        options.chroma_quality = options.quality;
        if (n148i_simd_force(N148I_SIMD_AUTO) != N148I_OK ||
            n148i_encode_memory(&source[1], &options, &encoded[1], &sizes[1]) != N148I_OK ||
            sizes[0] != sizes[1] || memcmp(encoded[0], encoded[1], sizes[0]) ||
            n148i_decode_memory(encoded[1], sizes[1], &decoded[1]) != N148I_OK ||
            decoded[0].width != (uint32_t)width || decoded[0].height != (uint32_t)height ||
            decoded[1].width != (uint32_t)width || decoded[1].height != (uint32_t)height ||
            memcmp(decoded[0].pixels, decoded[1].pixels, pixel_bytes))
            goto cleanup;
        if (trial == 0) {
            uint32_t original_flags = info.feature_flags;
            for (size_t j = 0; j < sizeof(required) / sizeof(required[0]) - (detail ? 0u : 1u); j++) {
                uint32_t invalid_flags = original_flags & ~required[j];
                for (int byte = 0; byte < 4; byte++)
                    encoded[0][20 + byte] = (uint8_t)(invalid_flags >> (8 * byte));
                n148i_image_info_t invalid_info = {0};
                n148i_image_t invalid_image = {0};
                int header_status = n148i_read_header(encoded[0], sizes[0], &invalid_info);
                int decode_status = n148i_decode_memory(encoded[0], sizes[0], &invalid_image);
                n148i_free_image(&invalid_image);
                if (header_status == N148I_OK || decode_status == N148I_OK)
                    goto cleanup;
            }
            for (int byte = 0; byte < 4; byte++)
                encoded[0][20 + byte] = (uint8_t)(original_flags >> (8 * byte));
        }
        success = 1;
cleanup:
        for (int i = 0; i < 2; i++) {
            n148i_free_buffer(encoded[i]);
            n148i_free_image(&decoded[i]);
        }
        free(tight);
        free(padded);
        n148i_simd_force(N148I_SIMD_AUTO);
        if (!success) break;
        completed++;
    }
    printf("comparison,format_7_%s,scalar+auto,1,2,33,35,0,0,0,0.0,"
           "24_odd_stride_chroma_effort_pairs_extreme_quality_dependencies,%s\n",
           detail ? "detail" : "balanced", completed == 24 ? "PASS" : "FAIL");
    return completed == 24;
}


static int validate_format_7_selective_luma_search(const Image *original) {
    n148i_image_t source = {
        original->pixels, (uint32_t) original->width,
        (uint32_t) original->height, (size_t) original->width * 3u,
    };
    n148i_encode_options_t options;
    n148i_encode_options_init(&options);
    options.quality = 60;
    options.thread_count = 1;
    options.feature_flags = N148I_PROFILE_SPECTRAL_LUMA_QUANT;
    uint8_t *baseline = NULL, *scalar = NULL, *vector = NULL;
    size_t baseline_size = 0, scalar_size = 0, vector_size = 0;
    n148i_image_t baseline_rgb = {0}, decoded = {0};
    n148i_image_info_t info = {0};
    int baseline_ok =
        n148i_simd_force(N148I_SIMD_SCALAR) == N148I_OK &&
        n148i_encode_memory(&source, &options, &baseline,
                            &baseline_size) == N148I_OK &&
        n148i_decode_memory(baseline, baseline_size, &baseline_rgb) ==
            N148I_OK;
    options.effort = 4;
    int success = baseline_ok &&
        n148i_encode_memory(&source, &options, &scalar,
                            &scalar_size) == N148I_OK &&
        n148i_read_header(scalar, scalar_size, &info) == N148I_OK &&
        info.format_version == N148I_FORMAT_VERSION_7 &&
        info.feature_flags == N148I_PROFILE_SPECTRAL_LUMA_QUANT &&
        info.effort == 4 &&
        n148i_simd_force(N148I_SIMD_AVX2) == N148I_OK &&
        n148i_encode_memory(&source, &options, &vector,
                            &vector_size) == N148I_OK &&
        scalar_size == vector_size &&
        memcmp(scalar, vector, scalar_size) == 0 &&
        n148i_decode_memory(vector, vector_size, &decoded) == N148I_OK &&
        decoded.width == source.width && decoded.height == source.height &&
        baseline_rgb.width == source.width &&
        baseline_rgb.height == source.height &&
        baseline_rgb.stride == decoded.stride &&
        memcmp(baseline_rgb.pixels, decoded.pixels,
               decoded.stride * decoded.height) != 0;
    printf("comparison,format_7_selective_luma_search,scalar+AVX2,1,2,%d,%d,%zu,"
           "%u,%u,0.0,effort4_changes_odd_fixture_roundtrip_"
           "header_and_determinism,%s\n",
           original->width, original->height, scalar_size,
           info.payload_size, info.payload_size,
           success ? "PASS" : "FAIL");
    n148i_free_buffer(baseline);
    n148i_free_buffer(scalar);
    n148i_free_buffer(vector);
    n148i_free_image(&baseline_rgb);
    n148i_free_image(&decoded);
    n148i_simd_force(N148I_SIMD_AUTO);
    return success;
}

int main(int argc, char **argv) {
    const char *example_path =
        argc > 1 ? argv[1] : "images/example.ppm";
    const char *odd_path =
        argc > 2 ? argv[2] : "output/validation-317x241.ppm";
    Image example = {0};
    Image odd = {0};
    CycleResult scalar = {0}, avx2 = {0};
    int failures = 0;

    printf("kind,name,cpu,threads,chroma,width,height,file_bytes,"
           "payload_bytes,bytes_consumed,psnr_db,detail,result\n");

    if (!validate_rans_core()) failures++;
    if (!validate_adaptive_rans_core()) failures++;

    n148_cpu_force(-1);
    int detected_level = n148_cpu_level();
    if (detected_level < N148_CPU_AVX2) {
        fprintf(stderr, "AVX2 is unavailable; path comparison cannot run\n");
        return EXIT_FAILURE;
    }
    if (!load_ppm(example_path, &example)) {
        fprintf(stderr, "could not load %s\n", example_path);
        return EXIT_FAILURE;
    }

    int scalar_ok = run_cycle(&example, 50, CHROMA_420,
                              N148_CPU_BASELINE, 1, &scalar);
    int avx2_ok = run_cycle(&example, 50, CHROMA_420,
                            N148_CPU_AVX2, 1, &avx2);
    if (scalar_ok) print_cycle("example_scalar", &scalar);
    if (avx2_ok) print_cycle("example_avx2", &avx2);

    int path_match =
        scalar_ok && avx2_ok &&
        scalar.stream_size == EXPECTED_EXAMPLE_SIZE &&
        avx2.stream_size == EXPECTED_EXAMPLE_SIZE &&
        cycles_identical(&scalar, &avx2);
    printf("comparison,scalar_vs_avx2,scalar+AVX2,1,2,%d,%d,%ld,%ld,%ld,"
           "%.12f,byte_and_psnr_identical,%s\n",
           example.width, example.height,
           scalar_ok ? scalar.stream_size : 0,
           scalar_ok ? scalar.payload_size : 0,
           scalar_ok ? scalar.bytes_consumed : 0,
           scalar_ok ? scalar.psnr : 0.0,
           path_match ? "PASS" : "FAIL");
    if (!path_match) failures++;

    if (scalar_ok && !validate_public_api(&example, &scalar)) failures++;
    if (scalar_ok && !validate_rans_entropy(&example, &scalar)) failures++;
    if (scalar_ok && !validate_context_modeling(&example, &scalar)) failures++;
    if (scalar_ok && !validate_reconstructed_intra(&example)) failures++;
    if (scalar_ok && !validate_perceptual_color(&example)) failures++;
    if (scalar_ok && !validate_adaptive_quantization(&example)) failures++;
    if (scalar_ok && !validate_variable_transforms(&example)) failures++;
    if (scalar_ok && !validate_rate_distortion_optimization(&example)) failures++;
    if (scalar_ok && !validate_causal_loop_filter(&example)) failures++;
    if (scalar_ok && !validate_directional_intra(&example)) failures++;
    if (scalar_ok && !validate_chroma_format_matrix(
            &example, "chroma_format_matrix")) failures++;
    if (scalar_ok && !validate_reconstruction_aware_chroma(
            &example, "reconstruction_aware_chroma")) failures++;
    if (scalar_ok && !validate_joint_chroma_intra(
            &example, "joint_chroma_intra")) failures++;
    if (scalar_ok && !validate_calibrated_chroma_quantization(
            &example, "calibrated_chroma_quant")) failures++;
    if (scalar_ok && !validate_frame_segmentation(
            &example, "frame_segmentation")) failures++;
    if (scalar_ok && !validate_segment_adaptive_filter(
            &example, "adaptive_loop_filter")) failures++;
    if (scalar_ok && !validate_calibrated_luma_quantization(
            &example, "calibrated_luma_quant")) failures++;
    if (scalar_ok && !validate_variable_luma_transform(
            &example, "variable_luma_transform")) failures++;
    if (scalar_ok && !validate_perceptual_luma_trellis(
            &example, "perceptual_luma_trellis")) failures++;
    if (scalar_ok && !validate_quant_adaptive_luma_filter(
            &example, "quant_adaptive_luma_filter")) failures++;
    if (scalar_ok && !validate_automatic_chroma(
            &example, "automatic_chroma")) failures++;
    if (scalar_ok && !validate_fidelity_tools(
            &example, "fidelity_tools")) failures++;
    if (scalar_ok && !validate_adaptive_rich_context(
            &example, "adaptive_rich_context")) failures++;
    if (scalar_ok && !validate_format_7_full_trellis(&example)) failures++;
    if (scalar_ok && !validate_format_7_spectral_luma(&example)) failures++;
    if (scalar_ok && !validate_format_7_refined_spectral_luma(&example)) failures++;
    if (scalar_ok && !validate_format_7_structural_luma()) failures++;
    if (scalar_ok && !validate_format_7_reconstruction(
            N148I_PROFILE_BALANCED_RECONSTRUCTION, 0)) failures++;
    if (scalar_ok && !validate_format_7_reconstruction(
            N148I_PROFILE_DETAIL_RECONSTRUCTION, 1)) failures++;
    fill_odd_image(&odd);
    if (!odd.pixels || !save_ppm(odd_path, &odd)) {
        fprintf(stderr, "could not create %s\n", odd_path);
        failures++;
    } else {
        if (!validate_format_7_selective_luma_search(&odd)) failures++;
        if (!validate_directional_intra_odd_dimensions(&odd)) failures++;
        if (!validate_chroma_format_matrix(
                &odd, "chroma_format_matrix_odd")) failures++;
        if (!validate_reconstruction_aware_chroma(
                &odd, "reconstruction_aware_chroma_odd")) failures++;
        if (!validate_joint_chroma_intra(
                &odd, "joint_chroma_intra_odd")) failures++;
        if (!validate_calibrated_chroma_quantization(
                &odd, "calibrated_chroma_quant_odd")) failures++;
        if (!validate_frame_segmentation(
                &odd, "frame_segmentation_odd")) failures++;
        if (!validate_segment_adaptive_filter(
                &odd, "adaptive_loop_filter_odd")) failures++;
        if (!validate_calibrated_luma_quantization(
                &odd, "calibrated_luma_quant_odd")) failures++;
        if (!validate_variable_luma_transform(
                &odd, "variable_luma_transform_odd")) failures++;
        if (!validate_automatic_chroma(
                &odd, "automatic_chroma_odd")) failures++;
        for (int chroma = CHROMA_444; chroma <= CHROMA_420; chroma++) {
            CycleResult single = {0}, parallel = {0};
            int single_ok = run_cycle(&odd, 50, chroma, -1, 1, &single);
            int parallel_ok = run_cycle(&odd, 50, chroma, -1, 4, &parallel);
            char single_name[32];
            char parallel_name[32];
            snprintf(single_name, sizeof(single_name),
                     "odd_chroma%d_t1", chroma);
            snprintf(parallel_name, sizeof(parallel_name),
                     "odd_chroma%d_t4", chroma);
            if (single_ok) print_cycle(single_name, &single);
            if (parallel_ok) print_cycle(parallel_name, &parallel);

            int thread_match =
                single_ok && parallel_ok &&
                cycles_identical(&single, &parallel);
            printf("comparison,odd_chroma%d_t1_vs_t4,auto,1+4,%d,%d,%d,%ld,"
                   "%ld,%ld,%.12f,byte_and_psnr_identical,%s\n",
                   chroma, chroma, odd.width, odd.height,
                   single_ok ? single.stream_size : 0,
                   single_ok ? single.payload_size : 0,
                   single_ok ? single.bytes_consumed : 0,
                   single_ok ? single.psnr : 0.0,
                   thread_match ? "PASS" : "FAIL");
            if (!thread_match) failures++;
            release_cycle(&single);
            release_cycle(&parallel);
        }
    }

    release_cycle(&scalar);
    release_cycle(&avx2);
    free_image(&example);
    free_image(&odd);
    n148_cpu_force(-1);
    n148_set_thread_count(1);

    fprintf(stderr, "validation %s (%d failure%s)\n",
            failures == 0 ? "PASS" : "FAIL",
            failures, failures == 1 ? "" : "s");
    return failures == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}

src/benchmark_final_cli.c

O benchmark_final_cli.c é o programa que mede os codecs na memória, usado no julgamento do artigo 25 e no julgamento da V2, no artigo 40.

Na V2, ele ganhou o WebP e passou a chamar o N.148i pela API pública, em vez das funções internas do encoder.

Na V1, o arquivo tinha 812 linhas:

/*
 * In-memory final benchmark driver for N.148i, libjpeg-turbo and JPEG XL.
 *
 * Copyright (c) Micilini Roll. Licensed under the MIT License.
 *
 * This file is measurement-only instrumentation.  It deliberately calls the
 * three codec libraries directly, keeps disk I/O outside timed regions, uses
 * persistent worker pools, alternates codec order, and emits every timing
 * sample so the statistical analysis is independently reproducible.
 */
#define _GNU_SOURCE

#include <errno.h>
#include <getopt.h>
#include <stddef.h>
#include <stdio.h>
#include <jpeglib.h>
#include <jxl/decode.h>
#include <jxl/encode.h>
#include <jxl/thread_parallel_runner.h>
#include <limits.h>
#include <math.h>
#if defined(__linux__)
#include <sched.h>
#endif
#include <setjmp.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "decoder.h"
#include "encoder.h"
#include "header.h"
#include "huffman.h"
#include "parallel.h"
#include "ppm.h"

enum {
    CODEC_N148 = 0,
    CODEC_JPEG = 1,
    CODEC_JXL_E3 = 2,
    CODEC_JXL_E7 = 3,
    CODEC_COUNT = 4
};

static const char *const CODEC_NAMES[CODEC_COUNT] = {
    "n148i", "jpeg", "jxl_e3", "jxl_e7"
};

typedef struct {
    const char *input;
    const char *output_prefix;
    int n148_quality;
    int jpeg_quality;
    float jxl_distance;
    int reps;
    int warmups;
    int chroma;
    int n148_threads;
    int jxl_threads;
    int jpeg_cpu;
    double sample_ms;
    unsigned active_mask;
} Options;

typedef struct {
    unsigned char *compressed;
    size_t compressed_size;
    size_t payload_size;
    HuffSpec specs[HUFFMAN_TABLE_COUNT];
    unsigned char *decoded;
    int width;
    int height;
    int encode_inner;
    int decode_inner;
} CodecState;

typedef struct {
    struct jpeg_error_mgr base;
    jmp_buf jump;
} JpegError;

#if defined(__linux__)
typedef cpu_set_t CpuAffinity;

static int capture_affinity(CpuAffinity *mask) {
    return sched_getaffinity(0, sizeof(*mask), mask) == 0;
}

static int single_cpu_affinity(const CpuAffinity *allowed, int cpu,
                               CpuAffinity *single) {
    if (cpu < 0 || cpu >= CPU_SETSIZE || !CPU_ISSET(cpu, allowed)) return 0;
    CPU_ZERO(single);
    CPU_SET(cpu, single);
    return 1;
}

static int apply_affinity(const CpuAffinity *mask) {
    return sched_setaffinity(0, sizeof(*mask), mask) == 0;
}
#else
typedef int CpuAffinity;

static int capture_affinity(CpuAffinity *mask) {
    *mask = 0;
    return 1;
}

static int single_cpu_affinity(const CpuAffinity *allowed, int cpu,
                               CpuAffinity *single) {
    (void) allowed;
    (void) cpu;
    (void) single;
    return 0;
}

static int apply_affinity(const CpuAffinity *mask) {
    (void) mask;
    return 1;
}
#endif

static double now_ms(void) {
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return ts.tv_sec * 1000.0 + ts.tv_nsec / 1000000.0;
}

static void jpeg_error_exit(j_common_ptr common) {
    JpegError *error = (JpegError *) common->err;
    longjmp(error->jump, 1);
}

static void free_state(CodecState *state) {
    free(state->compressed);
    free(state->decoded);
    memset(state, 0, sizeof(*state));
}

static void memory_write_u32(unsigned char *destination, uint32_t value) {
    destination[0] = (unsigned char) (value & 0xffu);
    destination[1] = (unsigned char) ((value >> 8) & 0xffu);
    destination[2] = (unsigned char) ((value >> 16) & 0xffu);
    destination[3] = (unsigned char) ((value >> 24) & 0xffu);
}

static uint32_t memory_read_u32(const unsigned char *source) {
    return (uint32_t) source[0] |
        ((uint32_t) source[1] << 8) |
        ((uint32_t) source[2] << 16) |
        ((uint32_t) source[3] << 24);
}

static int n148_encode_once(const Image *image, const Options *options,
                            CodecState *state) {
    Plane y = {0}, cb = {0}, cr = {0};
    EncodeStats stats;
    unsigned char *payload = NULL;
    HuffSpec specs[HUFFMAN_TABLE_COUNT];
    int ok = split_channels((Image *) image, &y, &cb, &cr, options->chroma);
    if (ok) {
        ok = encode_image(&y, &cb, &cr, options->n148_quality, 1, specs,
                          &payload, &stats);
    }
    free_plane(&y);
    free_plane(&cb);
    free_plane(&cr);
    if (!ok) {
        free(payload);
        return 0;
    }

    if (stats.data_size <= 0 || stats.data_size > UINT32_MAX ||
        stats.table_size < 0 ||
        (size_t) stats.table_size > SIZE_MAX - N148I_HEADER_SIZE ||
        (size_t) stats.data_size >
            SIZE_MAX - N148I_HEADER_SIZE - (size_t) stats.table_size) {
        free(payload);
        return 0;
    }
    size_t complete_size = (size_t) N148I_HEADER_SIZE +
        (size_t) stats.table_size + (size_t) stats.data_size;
    unsigned char *complete = (unsigned char *) malloc(complete_size);
    if (!complete) {
        free(payload);
        return 0;
    }

    memcpy(complete, N148I_MAGIC, N148I_MAGIC_LEN);
    complete[5] = N148I_VERSION;
    memory_write_u32(complete + 6, (uint32_t) image->width);
    memory_write_u32(complete + 10, (uint32_t) image->height);
    complete[14] = (unsigned char) options->n148_quality;
    complete[15] = (unsigned char) options->chroma;
    complete[16] = 1;
    memory_write_u32(complete + 17, (uint32_t) stats.data_size);
    size_t offset = N148I_HEADER_SIZE;
    for (int table = 0; table < HUFFMAN_TABLE_COUNT; table++) {
        if (!huffman_spec_is_valid(&specs[table])) {
            free(payload);
            free(complete);
            return 0;
        }
        for (int length = 1; length <= 16; length++)
            complete[offset++] = (unsigned char) specs[table].bits[length];
        memcpy(complete + offset, specs[table].values,
               (size_t) specs[table].value_count);
        offset += (size_t) specs[table].value_count;
    }
    if (offset != N148I_HEADER_SIZE + (size_t) stats.table_size) {
        free(payload);
        free(complete);
        return 0;
    }
    memcpy(complete + offset, payload, (size_t) stats.data_size);
    free(payload);

    free(state->compressed);
    state->compressed = complete;
    state->payload_size = (size_t) stats.data_size;
    state->compressed_size = complete_size;
    memcpy(state->specs, specs, sizeof(specs));
    return 1;
}

static int n148_decode_once(const Options *options, CodecState *state) {
    Plane y = {0}, cb = {0}, cr = {0};
    DecodeStats stats;
    Image image = {0};
    (void) options;
    if (!state->compressed || state->compressed_size < N148I_HEADER_SIZE ||
        memcmp(state->compressed, N148I_MAGIC, N148I_MAGIC_LEN) != 0 ||
        state->compressed[5] != N148I_VERSION ||
        memory_read_u32(state->compressed + 6) != (uint32_t) state->width ||
        memory_read_u32(state->compressed + 10) != (uint32_t) state->height ||
        state->compressed[14] < 1 || state->compressed[14] > 100 ||
        state->compressed[15] > CHROMA_420 || state->compressed[16] != 1) {
        return 0;
    }
    uint32_t data_size = memory_read_u32(state->compressed + 17);
    if (data_size == 0) return 0;
#if LONG_MAX < UINT32_MAX
    if (data_size > (uint32_t) LONG_MAX) return 0;
#endif
    size_t offset = N148I_HEADER_SIZE;
    HuffSpec specs[HUFFMAN_TABLE_COUNT];
    for (int table = 0; table < HUFFMAN_TABLE_COUNT; table++) {
        HuffSpec *spec = &specs[table];
        memset(spec, 0, sizeof(*spec));
        if (offset + 16 > state->compressed_size) return 0;
        for (int length = 1; length <= 16; length++) {
            int count = state->compressed[offset++];
            spec->bits[length] = count;
            spec->value_count += count;
            if (spec->value_count > HUFFMAN_MAX_SYMBOLS) return 0;
        }
        if (spec->value_count == 0 ||
            offset + (size_t) spec->value_count > state->compressed_size)
            return 0;
        memcpy(spec->values, state->compressed + offset,
               (size_t) spec->value_count);
        offset += (size_t) spec->value_count;
        if (!huffman_spec_is_valid(spec)) return 0;
    }
    if ((size_t) data_size != state->compressed_size - offset) return 0;
    int ok = decode_image(state->compressed + offset, (long) data_size,
                          state->width, state->height,
                          state->compressed[14], state->compressed[15],
                          specs, &y, &cb, &cr, &stats);
    if (ok && stats.bytes_consumed != (long) data_size) {
        fprintf(stderr, "N.148i consumed %ld of %zu payload bytes\n",
                stats.bytes_consumed, (size_t) data_size);
        ok = 0;
    }
    if (ok) ok = merge_channels(&y, &cb, &cr, 1, &image);
    free_plane(&y);
    free_plane(&cb);
    free_plane(&cr);
    if (!ok || image.width != state->width || image.height != state->height) {
        free_image(&image);
        return 0;
    }
    free(state->decoded);
    state->decoded = image.pixels;
    return 1;
}

static void jpeg_sampling(struct jpeg_compress_struct *jpeg, int chroma) {
    jpeg->comp_info[0].h_samp_factor = chroma == CHROMA_444 ? 1 : 2;
    jpeg->comp_info[0].v_samp_factor = chroma == CHROMA_420 ? 2 : 1;
    jpeg->comp_info[1].h_samp_factor = 1;
    jpeg->comp_info[1].v_samp_factor = 1;
    jpeg->comp_info[2].h_samp_factor = 1;
    jpeg->comp_info[2].v_samp_factor = 1;
}

static int jpeg_encode_once(const Image *image, const Options *options,
                            CodecState *state) {
    struct jpeg_compress_struct jpeg;
    JpegError error;
    unsigned char *data = NULL;
    unsigned long size = 0;

    jpeg.err = jpeg_std_error(&error.base);
    error.base.error_exit = jpeg_error_exit;
    if (setjmp(error.jump)) {
        jpeg_destroy_compress(&jpeg);
        free(data);
        return 0;
    }
    jpeg_create_compress(&jpeg);
    jpeg_mem_dest(&jpeg, &data, &size);
    jpeg.image_width = (JDIMENSION) image->width;
    jpeg.image_height = (JDIMENSION) image->height;
    jpeg.input_components = 3;
    jpeg.in_color_space = JCS_RGB;
    jpeg_set_defaults(&jpeg);
    jpeg_set_quality(&jpeg, options->jpeg_quality, TRUE);
    jpeg_sampling(&jpeg, options->chroma);
    jpeg.optimize_coding = TRUE;
    jpeg_start_compress(&jpeg, TRUE);
    while (jpeg.next_scanline < jpeg.image_height) {
        JSAMPROW row = image->pixels +
            (size_t) jpeg.next_scanline * image->width * 3;
        jpeg_write_scanlines(&jpeg, &row, 1);
    }
    jpeg_finish_compress(&jpeg);
    jpeg_destroy_compress(&jpeg);

    free(state->compressed);
    state->compressed = data;
    state->compressed_size = (size_t) size;
    state->payload_size = (size_t) size;
    return 1;
}

static int jpeg_decode_once(CodecState *state) {
    struct jpeg_decompress_struct jpeg;
    JpegError error;
    unsigned char *pixels = NULL;
    int width = 0, height = 0;

    jpeg.err = jpeg_std_error(&error.base);
    error.base.error_exit = jpeg_error_exit;
    if (setjmp(error.jump)) {
        jpeg_destroy_decompress(&jpeg);
        free(pixels);
        return 0;
    }
    jpeg_create_decompress(&jpeg);
    jpeg_mem_src(&jpeg, state->compressed,
                 (unsigned long) state->compressed_size);
    jpeg_read_header(&jpeg, TRUE);
    jpeg.out_color_space = JCS_RGB;
    jpeg_start_decompress(&jpeg);
    width = (int) jpeg.output_width;
    height = (int) jpeg.output_height;
    size_t stride = (size_t) width * jpeg.output_components;
    pixels = (unsigned char *) malloc(stride * (size_t) height);
    if (!pixels) {
        jpeg_destroy_decompress(&jpeg);
        return 0;
    }
    while (jpeg.output_scanline < jpeg.output_height) {
        JSAMPROW row = pixels + (size_t) jpeg.output_scanline * stride;
        jpeg_read_scanlines(&jpeg, &row, 1);
    }
    jpeg_finish_decompress(&jpeg);
    jpeg_destroy_decompress(&jpeg);
    if (width != state->width || height != state->height) {
        free(pixels);
        return 0;
    }
    free(state->decoded);
    state->decoded = pixels;
    return 1;
}

static int jxl_encode_once(const Image *image, const Options *options,
                           int effort, void *runner, CodecState *state) {
    JxlEncoder *encoder = JxlEncoderCreate(NULL);
    JxlEncoderFrameSettings *frame = NULL;
    unsigned char *compressed = NULL;
    size_t capacity = 65536;
    size_t used = 0;
    int ok = 0;
    if (!encoder) goto cleanup;
    if (JxlEncoderSetParallelRunner(encoder, JxlThreadParallelRunner, runner) !=
        JXL_ENC_SUCCESS) goto cleanup;

    JxlPixelFormat format = {3, JXL_TYPE_UINT8, JXL_NATIVE_ENDIAN, 0};
    JxlBasicInfo info;
    JxlEncoderInitBasicInfo(&info);
    info.xsize = (uint32_t) image->width;
    info.ysize = (uint32_t) image->height;
    info.bits_per_sample = 8;
    info.exponent_bits_per_sample = 0;
    info.num_color_channels = 3;
    info.num_extra_channels = 0;
    info.alpha_bits = 0;
    info.uses_original_profile = JXL_FALSE;
    if (JxlEncoderSetBasicInfo(encoder, &info) != JXL_ENC_SUCCESS)
        goto cleanup;

    JxlColorEncoding color;
    JxlColorEncodingSetToSRGB(&color, JXL_FALSE);
    if (JxlEncoderSetColorEncoding(encoder, &color) != JXL_ENC_SUCCESS)
        goto cleanup;
    frame = JxlEncoderFrameSettingsCreate(encoder, NULL);
    if (!frame ||
        JxlEncoderFrameSettingsSetOption(
            frame, JXL_ENC_FRAME_SETTING_EFFORT, effort) != JXL_ENC_SUCCESS ||
        JxlEncoderSetFrameDistance(frame, options->jxl_distance) !=
            JXL_ENC_SUCCESS ||
        JxlEncoderAddImageFrame(frame, &format, image->pixels,
            (size_t) image->width * image->height * 3) != JXL_ENC_SUCCESS)
        goto cleanup;
    JxlEncoderCloseInput(encoder);

    compressed = (unsigned char *) malloc(capacity);
    if (!compressed) goto cleanup;
    for (;;) {
        unsigned char *next = compressed + used;
        size_t available = capacity - used;
        JxlEncoderStatus status =
            JxlEncoderProcessOutput(encoder, &next, &available);
        used = (size_t) (next - compressed);
        if (status == JXL_ENC_SUCCESS) break;
        if (status != JXL_ENC_NEED_MORE_OUTPUT) goto cleanup;
        if (capacity > SIZE_MAX / 2) goto cleanup;
        capacity *= 2;
        unsigned char *grown =
            (unsigned char *) realloc(compressed, capacity);
        if (!grown) goto cleanup;
        compressed = grown;
    }

    free(state->compressed);
    state->compressed = compressed;
    compressed = NULL;
    state->compressed_size = used;
    state->payload_size = used;
    ok = 1;

cleanup:
    free(compressed);
    JxlEncoderDestroy(encoder);
    return ok;
}

static int jxl_decode_once(void *runner, CodecState *state) {
    JxlDecoder *decoder = JxlDecoderCreate(NULL);
    unsigned char *pixels = NULL;
    int got_info = 0;
    int got_image = 0;
    int ok = 0;
    JxlPixelFormat format = {3, JXL_TYPE_UINT8, JXL_NATIVE_ENDIAN, 0};
    if (!decoder) goto cleanup;
    if (JxlDecoderSetParallelRunner(decoder, JxlThreadParallelRunner, runner) !=
            JXL_DEC_SUCCESS ||
        JxlDecoderSubscribeEvents(decoder,
            JXL_DEC_BASIC_INFO | JXL_DEC_FULL_IMAGE) != JXL_DEC_SUCCESS)
        goto cleanup;
    JxlDecoderSetInput(decoder, state->compressed, state->compressed_size);
    JxlDecoderCloseInput(decoder);

    for (;;) {
        JxlDecoderStatus status = JxlDecoderProcessInput(decoder);
        if (status == JXL_DEC_BASIC_INFO) {
            JxlBasicInfo info;
            if (JxlDecoderGetBasicInfo(decoder, &info) != JXL_DEC_SUCCESS ||
                (int) info.xsize != state->width ||
                (int) info.ysize != state->height)
                goto cleanup;
            got_info = 1;
        } else if (status == JXL_DEC_NEED_IMAGE_OUT_BUFFER) {
            size_t bytes = 0;
            if (!got_info ||
                JxlDecoderImageOutBufferSize(decoder, &format, &bytes) !=
                    JXL_DEC_SUCCESS ||
                bytes != (size_t) state->width * state->height * 3)
                goto cleanup;
            pixels = (unsigned char *) malloc(bytes);
            if (!pixels ||
                JxlDecoderSetImageOutBuffer(decoder, &format, pixels, bytes) !=
                    JXL_DEC_SUCCESS)
                goto cleanup;
        } else if (status == JXL_DEC_FULL_IMAGE) {
            got_image = 1;
        } else if (status == JXL_DEC_SUCCESS) {
            ok = got_info && got_image && pixels != NULL;
            break;
        } else if (status == JXL_DEC_NEED_MORE_INPUT ||
                   status == JXL_DEC_ERROR) {
            goto cleanup;
        }
    }

    if (ok) {
        free(state->decoded);
        state->decoded = pixels;
        pixels = NULL;
    }

cleanup:
    free(pixels);
    JxlDecoderDestroy(decoder);
    return ok;
}

static int encode_once(int codec, const Image *image, const Options *options,
                       void *jxl_runner, CodecState states[CODEC_COUNT]) {
    if (codec == CODEC_N148)
        return n148_encode_once(image, options, &states[codec]);
    if (codec == CODEC_JPEG)
        return jpeg_encode_once(image, options, &states[codec]);
    return jxl_encode_once(image, options,
                           codec == CODEC_JXL_E3 ? 3 : 7,
                           jxl_runner, &states[codec]);
}

static int decode_once(int codec, const Options *options, void *jxl_runner,
                       CodecState states[CODEC_COUNT]) {
    if (codec == CODEC_N148)
        return n148_decode_once(options, &states[codec]);
    if (codec == CODEC_JPEG)
        return jpeg_decode_once(&states[codec]);
    return jxl_decode_once(jxl_runner, &states[codec]);
}

static int codec_affinity(int codec, const CpuAffinity *all,
                          const CpuAffinity *jpeg, int pin_jpeg) {
    return apply_affinity(codec == CODEC_JPEG && pin_jpeg ? jpeg : all);
}

static int calibrated_inner(double elapsed, double target_ms) {
    if (!(elapsed > 0.0) || !isfinite(elapsed)) return 1;
    int inner = (int) ceil(target_ms / elapsed);
    if (inner < 1) inner = 1;
    if (inner > 256) inner = 256;
    return inner;
}

static int measure_encode(int codec, int inner, const Image *image,
                          const Options *options, void *jxl_runner,
                          CodecState states[CODEC_COUNT], double *elapsed) {
    double start = now_ms();
    for (int i = 0; i < inner; i++) {
        if (!encode_once(codec, image, options, jxl_runner, states)) return 0;
    }
    *elapsed = (now_ms() - start) / inner;
    return 1;
}

static int measure_decode(int codec, int inner, const Options *options,
                          void *jxl_runner, CodecState states[CODEC_COUNT],
                          double *elapsed) {
    double start = now_ms();
    for (int i = 0; i < inner; i++) {
        if (!decode_once(codec, options, jxl_runner, states)) return 0;
    }
    *elapsed = (now_ms() - start) / inner;
    return 1;
}

static int save_reconstruction(const char *prefix, const char *codec,
                               const CodecState *state) {
    if (!prefix) return 1;
    size_t length = strlen(prefix) + strlen(codec) + 6;
    char *path = (char *) malloc(length);
    if (!path) return 0;
    snprintf(path, length, "%s-%s.ppm", prefix, codec);
    Image output;
    output.width = state->width;
    output.height = state->height;
    output.pixels = state->decoded;
    int ok = save_ppm(path, &output);
    free(path);
    return ok;
}

static unsigned parse_codecs(const char *value) {
    if (strcmp(value, "all") == 0) return (1u << CODEC_COUNT) - 1u;
    if (strcmp(value, "n148i") == 0) return 1u << CODEC_N148;
    if (strcmp(value, "jpeg") == 0) return 1u << CODEC_JPEG;
    if (strcmp(value, "jxl_e3") == 0) return 1u << CODEC_JXL_E3;
    if (strcmp(value, "jxl_e7") == 0) return 1u << CODEC_JXL_E7;
    return 0;
}

static void usage(const char *program) {
    fprintf(stderr,
        "usage: %s --input IMAGE.ppm [options]\n"
        "  --n148-quality N    N.148i quality, default 60\n"
        "  --jpeg-quality N    JPEG quality, default 60\n"
        "  --jxl-distance X    JPEG XL distance, default 2.5\n"
        "  --reps N            measured samples, default 15\n"
        "  --warmups N         warmup samples, default 3\n"
        "  --sample-ms X       target duration per batched sample, default 20\n"
        "  --chroma N          N.148i/JPEG chroma 0/1/2, default 2\n"
        "  --n148-threads N    total N.148i threads, default 1\n"
        "  --jxl-threads N     JPEG XL worker threads (0 = caller), default 0\n"
        "  --jpeg-cpu N        pin JPEG to this logical CPU, default -1\n"
        "  --codecs LIST       all or one codec name, default all\n"
        "  --output-prefix P   write P-codec.ppm after timing\n",
        program);
}

static int parse_options(int argc, char **argv, Options *options) {
    *options = (Options) {
        .input = NULL,
        .output_prefix = NULL,
        .n148_quality = 60,
        .jpeg_quality = 60,
        .jxl_distance = 2.5f,
        .reps = 15,
        .warmups = 3,
        .chroma = CHROMA_420,
        .n148_threads = 1,
        .jxl_threads = 0,
        .jpeg_cpu = -1,
        .sample_ms = 20.0,
        .active_mask = (1u << CODEC_COUNT) - 1u,
    };
    static const struct option LONG_OPTIONS[] = {
        {"input", required_argument, NULL, 'i'},
        {"n148-quality", required_argument, NULL, 'n'},
        {"jpeg-quality", required_argument, NULL, 'q'},
        {"jxl-distance", required_argument, NULL, 'd'},
        {"reps", required_argument, NULL, 'r'},
        {"warmups", required_argument, NULL, 'w'},
        {"sample-ms", required_argument, NULL, 's'},
        {"chroma", required_argument, NULL, 'c'},
        {"n148-threads", required_argument, NULL, 't'},
        {"jxl-threads", required_argument, NULL, 'j'},
        {"jpeg-cpu", required_argument, NULL, 'p'},
        {"codecs", required_argument, NULL, 'k'},
        {"output-prefix", required_argument, NULL, 'o'},
        {"help", no_argument, NULL, 'h'},
        {NULL, 0, NULL, 0},
    };
    int option;
    while ((option = getopt_long(argc, argv, "i:n:q:d:r:w:s:c:t:j:p:k:o:h",
                                 LONG_OPTIONS, NULL)) != -1) {
        switch (option) {
            case 'i': options->input = optarg; break;
            case 'n': options->n148_quality = atoi(optarg); break;
            case 'q': options->jpeg_quality = atoi(optarg); break;
            case 'd': options->jxl_distance = strtof(optarg, NULL); break;
            case 'r': options->reps = atoi(optarg); break;
            case 'w': options->warmups = atoi(optarg); break;
            case 's': options->sample_ms = strtod(optarg, NULL); break;
            case 'c': options->chroma = atoi(optarg); break;
            case 't': options->n148_threads = atoi(optarg); break;
            case 'j': options->jxl_threads = atoi(optarg); break;
            case 'p': options->jpeg_cpu = atoi(optarg); break;
            case 'k': options->active_mask = parse_codecs(optarg); break;
            case 'o': options->output_prefix = optarg; break;
            case 'h': usage(argv[0]); return 0;
            default: return -1;
        }
    }
    if (!options->input || options->active_mask == 0 ||
        options->n148_quality < 1 || options->n148_quality > 100 ||
        options->jpeg_quality < 1 || options->jpeg_quality > 100 ||
        !(options->jxl_distance > 0.0f) || options->jxl_distance > 25.0f ||
        options->reps < 1 || options->warmups < 0 ||
        !(options->sample_ms > 0.0) || options->chroma < 0 ||
        options->chroma > 2 || options->n148_threads < 1 ||
        options->n148_threads > 32 || options->jxl_threads < 0 ||
        options->jpeg_cpu < -1) {
        usage(argv[0]);
        return -1;
    }
    return 1;
}

int main(int argc, char **argv) {
    Options options;
    int parsed = parse_options(argc, argv, &options);
    if (parsed <= 0) return parsed == 0 ? EXIT_SUCCESS : EXIT_FAILURE;

    Image original = {0};
    CodecState states[CODEC_COUNT] = {{0}};
    CpuAffinity all_affinity, jpeg_affinity;
    int affinity_captured = 0;
    int pin_jpeg = options.jpeg_cpu >= 0;
    void *jxl_runner = NULL;
    int active[CODEC_COUNT];
    int active_count = 0;
    int result = EXIT_FAILURE;

    if (!load_ppm(options.input, &original)) goto cleanup;
    if (!capture_affinity(&all_affinity)) {
        fprintf(stderr, "could not configure CPU affinity: %s\n",
                strerror(errno));
        goto cleanup;
    }
    affinity_captured = 1;
    if (pin_jpeg && !single_cpu_affinity(&all_affinity, options.jpeg_cpu,
                                         &jpeg_affinity)) {
        fprintf(stderr, "could not configure CPU affinity: %s\n",
                strerror(errno));
        goto cleanup;
    }
    n148_set_thread_count(options.n148_threads);
    if (options.active_mask & ((1u << CODEC_JXL_E3) | (1u << CODEC_JXL_E7))) {
        jxl_runner = JxlThreadParallelRunnerCreate(NULL,
                                                   (size_t) options.jxl_threads);
        if (!jxl_runner) {
            fprintf(stderr, "could not create JPEG XL thread runner\n");
            goto cleanup;
        }
    }
    for (int codec = 0; codec < CODEC_COUNT; codec++) {
        if (options.active_mask & (1u << codec)) active[active_count++] = codec;
        states[codec].width = original.width;
        states[codec].height = original.height;
    }

    /* One unmeasured call calibrates each batch and verifies every path. */
    for (int index = 0; index < active_count; index++) {
        int codec = active[index];
        if (!codec_affinity(codec, &all_affinity, &jpeg_affinity, pin_jpeg))
            goto cleanup;
        double start = now_ms();
        if (!encode_once(codec, &original, &options, jxl_runner, states)) {
            fprintf(stderr, "%s encode calibration failed\n", CODEC_NAMES[codec]);
            goto cleanup;
        }
        states[codec].encode_inner =
            calibrated_inner(now_ms() - start, options.sample_ms);

        start = now_ms();
        if (!decode_once(codec, &options, jxl_runner, states)) {
            fprintf(stderr, "%s decode calibration failed\n", CODEC_NAMES[codec]);
            goto cleanup;
        }
        states[codec].decode_inner =
            calibrated_inner(now_ms() - start, options.sample_ms);
    }

    printf("meta,%d,%d,%d,%d,%.9g,%d,%d,%d,%d,%u,%d\n",
           original.width, original.height, options.n148_quality,
           options.jpeg_quality, options.jxl_distance, options.reps,
           options.warmups, options.chroma, options.n148_threads,
           (unsigned) JxlEncoderVersion(), options.jxl_threads);
    for (int index = 0; index < active_count; index++) {
        int codec = active[index];
        printf("calibration,%s,%d,%d\n", CODEC_NAMES[codec],
               states[codec].encode_inner, states[codec].decode_inner);
    }

    for (int rep = -options.warmups; rep < options.reps; rep++) {
        double encode_times[CODEC_COUNT] = {0};
        double decode_times[CODEC_COUNT] = {0};
        int rotation = (rep + options.warmups) % active_count;
        for (int pass = 0; pass < active_count; pass++) {
            int codec = active[(pass + rotation) % active_count];
            if (!codec_affinity(codec, &all_affinity, &jpeg_affinity,
                                pin_jpeg) ||
                !measure_encode(codec, states[codec].encode_inner, &original,
                                &options, jxl_runner, states,
                                &encode_times[codec])) {
                fprintf(stderr, "%s encode sample failed\n", CODEC_NAMES[codec]);
                goto cleanup;
            }
        }
        for (int pass = 0; pass < active_count; pass++) {
            int codec = active[(active_count - 1 - pass + rotation) %
                               active_count];
            if (!codec_affinity(codec, &all_affinity, &jpeg_affinity,
                                pin_jpeg) ||
                !measure_decode(codec, states[codec].decode_inner, &options,
                                jxl_runner, states, &decode_times[codec])) {
                fprintf(stderr, "%s decode sample failed\n", CODEC_NAMES[codec]);
                goto cleanup;
            }
        }
        if (rep >= 0) {
            for (int index = 0; index < active_count; index++) {
                int codec = active[index];
                printf("sample,%s,%d,%.12f,%.12f\n", CODEC_NAMES[codec], rep,
                       encode_times[codec], decode_times[codec]);
            }
        }
    }

    if (!apply_affinity(&all_affinity)) goto cleanup;
    for (int index = 0; index < active_count; index++) {
        int codec = active[index];
        if (!states[codec].decoded || states[codec].compressed_size == 0 ||
            !save_reconstruction(options.output_prefix, CODEC_NAMES[codec],
                                 &states[codec])) {
            fprintf(stderr, "%s output validation failed\n", CODEC_NAMES[codec]);
            goto cleanup;
        }
        printf("result,%s,%zu,%s\n", CODEC_NAMES[codec],
               states[codec].compressed_size,
               options.output_prefix ? "reconstruction_written" : "validated");
    }
    fflush(stdout);
    result = EXIT_SUCCESS;

cleanup:
    if (affinity_captured) apply_affinity(&all_affinity);
    for (int codec = 0; codec < CODEC_COUNT; codec++) free_state(&states[codec]);
    JxlThreadParallelRunnerDestroy(jxl_runner);
    free_image(&original);
    return result;
}

Na V2, ele ficou com 902 linhas:

/*
 * In-memory final benchmark driver for N.148i, libjpeg-turbo, JPEG XL,
 * and WebP.
 *
 * Copyright (c) Micilini Roll. Licensed under the MIT License.
 *
 * This file is measurement-only instrumentation.  It deliberately calls the
 * codec libraries directly, keeps disk I/O outside timed regions, uses
 * persistent worker pools, alternates codec order, and emits every timing
 * sample so the statistical analysis is independently reproducible.
 */
#define _GNU_SOURCE

#include <errno.h>
#include <getopt.h>
#include <stddef.h>
#include <stdio.h>
#include <jpeglib.h>
#ifndef N148_BENCH_NO_JXL
#include <jxl/decode.h>
#include <jxl/encode.h>
#include <jxl/thread_parallel_runner.h>
#endif
#include <webp/decode.h>
#include <webp/encode.h>
#include <limits.h>
#include <math.h>
#if defined(__linux__)
#include <sched.h>
#endif
#include <setjmp.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "n148i.h"
#include "ppm.h"

/* Compile this same timing harness against the frozen public V1 library.
   Its options structure ends at thread_count. No V2 compatibility path is
   used for the V1 benchmark. */
#ifdef N148_BENCH_V1
#define N148I_FORMAT_VERSION_1 1
#define N148I_DEFAULT_FEATURES 0u
#endif

enum {
    CODEC_N148_CURRENT = 0,
    CODEC_N148_FORMAT_1 = 1,
    CODEC_JPEG = 2,
    CODEC_WEBP_M4 = 3,
    CODEC_WEBP_M6 = 4,
    CODEC_JXL_E3 = 5,
    CODEC_JXL_E7 = 6,
    CODEC_COUNT = 7
};

static const char *const CODEC_NAMES[CODEC_COUNT] = {
    "n148i", "n148i_format_1", "jpeg", "webp_m4", "webp_m6",
    "jxl_e3", "jxl_e7"
};

#define ALL_CODEC_MASK ((1u << CODEC_COUNT) - 1u)

typedef struct {
    const char *input;
    const char *output_prefix;
    int n148_quality;
    int n148_chroma_quality;
    int n148_effort;
    uint32_t n148_feature_flags;
    int jpeg_quality;
    float webp_quality;
    float jxl_distance;
    int reps;
    int warmups;
    int chroma;
    int n148_threads;
    int jxl_threads;
    int webp_thread_level;
    int jpeg_cpu;
    double sample_ms;
    unsigned active_mask;
} Options;

typedef struct {
    unsigned char *compressed;
    size_t compressed_size;
    unsigned char *decoded;
    int width;
    int height;
    int encode_inner;
    int decode_inner;
} CodecState;

typedef struct {
    struct jpeg_error_mgr base;
    jmp_buf jump;
} JpegError;

#if defined(__linux__)
typedef cpu_set_t CpuAffinity;

static int capture_affinity(CpuAffinity *mask) {
    return sched_getaffinity(0, sizeof(*mask), mask) == 0;
}

static int single_cpu_affinity(const CpuAffinity *allowed, int cpu,
                               CpuAffinity *single) {
    if (cpu < 0 || cpu >= CPU_SETSIZE || !CPU_ISSET(cpu, allowed)) return 0;
    CPU_ZERO(single);
    CPU_SET(cpu, single);
    return 1;
}

static int apply_affinity(const CpuAffinity *mask) {
    return sched_setaffinity(0, sizeof(*mask), mask) == 0;
}
#else
typedef int CpuAffinity;

static int capture_affinity(CpuAffinity *mask) {
    *mask = 0;
    return 1;
}

static int single_cpu_affinity(const CpuAffinity *allowed, int cpu,
                               CpuAffinity *single) {
    (void) allowed;
    (void) cpu;
    (void) single;
    return 0;
}

static int apply_affinity(const CpuAffinity *mask) {
    (void) mask;
    return 1;
}
#endif

static double now_ms(void) {
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return ts.tv_sec * 1000.0 + ts.tv_nsec / 1000000.0;
}

static void jpeg_error_exit(j_common_ptr common) {
    JpegError *error = (JpegError *) common->err;
    longjmp(error->jump, 1);
}

static int is_public_n148(int codec) {
    return codec == CODEC_N148_CURRENT || codec == CODEC_N148_FORMAT_1;
}

static void free_state(int codec, CodecState *state) {
    if (is_public_n148(codec)) {
        n148i_free_buffer(state->compressed);
        n148i_free_buffer(state->decoded);
    } else {
        free(state->compressed);
        free(state->decoded);
    }
    memset(state, 0, sizeof(*state));
}

static int n148_encode_once(const Image *image, const Options *options,
                            uint32_t format_version, CodecState *state) {
    n148i_image_t source = {
        image->pixels,
        (uint32_t) image->width,
        (uint32_t) image->height,
        (size_t) image->width * 3u,
    };
    n148i_encode_options_t settings;
    n148i_encode_options_init(&settings);
    settings.quality = options->n148_quality;
    settings.chroma = (n148i_chroma_t) options->chroma;
    settings.optimize_huffman = 1;
    settings.thread_count = options->n148_threads;
#ifndef N148_BENCH_V1
    settings.format_version = format_version;
    settings.feature_flags = format_version == N148I_FORMAT_VERSION_1 ?
        0u : options->n148_feature_flags;
    settings.effort = format_version == N148I_FORMAT_VERSION_1 ?
        0 : options->n148_effort;
    settings.chroma_quality = format_version == N148I_FORMAT_VERSION_1 ?
        0 : options->n148_chroma_quality;
#else
    (void)format_version;
#endif

    uint8_t *compressed = NULL;
    size_t compressed_size = 0;
    if (n148i_encode_memory(&source, &settings, &compressed,
                            &compressed_size) != N148I_OK) {
        n148i_free_buffer(compressed);
        return 0;
    }
    n148i_free_buffer(state->compressed);
    state->compressed = compressed;
    state->compressed_size = compressed_size;
    return 1;
}

static int n148_decode_once(CodecState *state) {
    n148i_image_t decoded = {0};
    if (n148i_decode_memory(state->compressed, state->compressed_size,
                            &decoded) != N148I_OK ||
        decoded.width != (uint32_t) state->width ||
        decoded.height != (uint32_t) state->height || !decoded.pixels) {
        n148i_free_image(&decoded);
        return 0;
    }
    n148i_free_buffer(state->decoded);
    state->decoded = decoded.pixels;
    decoded.pixels = NULL;
    return 1;
}

static void jpeg_sampling(struct jpeg_compress_struct *jpeg, int chroma) {
    jpeg->comp_info[0].h_samp_factor = chroma == N148I_CHROMA_444 ? 1 : 2;
    jpeg->comp_info[0].v_samp_factor = chroma == N148I_CHROMA_420 ? 2 : 1;
    jpeg->comp_info[1].h_samp_factor = 1;
    jpeg->comp_info[1].v_samp_factor = 1;
    jpeg->comp_info[2].h_samp_factor = 1;
    jpeg->comp_info[2].v_samp_factor = 1;
}

static int jpeg_encode_once(const Image *image, const Options *options,
                            CodecState *state) {
    struct jpeg_compress_struct jpeg;
    JpegError error;
    unsigned char *data = NULL;
    unsigned long size = 0;

    jpeg.err = jpeg_std_error(&error.base);
    error.base.error_exit = jpeg_error_exit;
    if (setjmp(error.jump)) {
        jpeg_destroy_compress(&jpeg);
        free(data);
        return 0;
    }
    jpeg_create_compress(&jpeg);
    jpeg_mem_dest(&jpeg, &data, &size);
    jpeg.image_width = (JDIMENSION) image->width;
    jpeg.image_height = (JDIMENSION) image->height;
    jpeg.input_components = 3;
    jpeg.in_color_space = JCS_RGB;
    jpeg_set_defaults(&jpeg);
    jpeg_set_quality(&jpeg, options->jpeg_quality, TRUE);
    jpeg_sampling(&jpeg, options->chroma);
    jpeg.optimize_coding = TRUE;
    jpeg_start_compress(&jpeg, TRUE);
    while (jpeg.next_scanline < jpeg.image_height) {
        JSAMPROW row = image->pixels +
            (size_t) jpeg.next_scanline * image->width * 3;
        jpeg_write_scanlines(&jpeg, &row, 1);
    }
    jpeg_finish_compress(&jpeg);
    jpeg_destroy_compress(&jpeg);

    free(state->compressed);
    state->compressed = data;
    state->compressed_size = (size_t) size;
    return 1;
}

static int jpeg_decode_once(CodecState *state) {
    struct jpeg_decompress_struct jpeg;
    JpegError error;
    unsigned char *pixels = NULL;
    int width = 0, height = 0;

    jpeg.err = jpeg_std_error(&error.base);
    error.base.error_exit = jpeg_error_exit;
    if (setjmp(error.jump)) {
        jpeg_destroy_decompress(&jpeg);
        free(pixels);
        return 0;
    }
    jpeg_create_decompress(&jpeg);
    jpeg_mem_src(&jpeg, state->compressed,
                 (unsigned long) state->compressed_size);
    jpeg_read_header(&jpeg, TRUE);
    jpeg.out_color_space = JCS_RGB;
    jpeg_start_decompress(&jpeg);
    width = (int) jpeg.output_width;
    height = (int) jpeg.output_height;
    size_t stride = (size_t) width * jpeg.output_components;
    pixels = (unsigned char *) malloc(stride * (size_t) height);
    if (!pixels) {
        jpeg_destroy_decompress(&jpeg);
        return 0;
    }
    while (jpeg.output_scanline < jpeg.output_height) {
        JSAMPROW row = pixels + (size_t) jpeg.output_scanline * stride;
        jpeg_read_scanlines(&jpeg, &row, 1);
    }
    jpeg_finish_decompress(&jpeg);
    jpeg_destroy_decompress(&jpeg);
    if (width != state->width || height != state->height) {
        free(pixels);
        return 0;
    }
    free(state->decoded);
    state->decoded = pixels;
    return 1;
}

#ifndef N148_BENCH_NO_JXL
static int jxl_encode_once(const Image *image, const Options *options,
                           int effort, void *runner, CodecState *state) {
    JxlEncoder *encoder = JxlEncoderCreate(NULL);
    JxlEncoderFrameSettings *frame = NULL;
    unsigned char *compressed = NULL;
    size_t capacity = 65536;
    size_t used = 0;
    int ok = 0;
    if (!encoder) goto cleanup;
    if (JxlEncoderSetParallelRunner(encoder, JxlThreadParallelRunner, runner) !=
        JXL_ENC_SUCCESS) goto cleanup;

    JxlPixelFormat format = {3, JXL_TYPE_UINT8, JXL_NATIVE_ENDIAN, 0};
    JxlBasicInfo info;
    JxlEncoderInitBasicInfo(&info);
    info.xsize = (uint32_t) image->width;
    info.ysize = (uint32_t) image->height;
    info.bits_per_sample = 8;
    info.exponent_bits_per_sample = 0;
    info.num_color_channels = 3;
    info.num_extra_channels = 0;
    info.alpha_bits = 0;
    info.uses_original_profile = JXL_FALSE;
    if (JxlEncoderSetBasicInfo(encoder, &info) != JXL_ENC_SUCCESS)
        goto cleanup;

    JxlColorEncoding color;
    JxlColorEncodingSetToSRGB(&color, JXL_FALSE);
    if (JxlEncoderSetColorEncoding(encoder, &color) != JXL_ENC_SUCCESS)
        goto cleanup;
    frame = JxlEncoderFrameSettingsCreate(encoder, NULL);
    if (!frame ||
        JxlEncoderFrameSettingsSetOption(
            frame, JXL_ENC_FRAME_SETTING_EFFORT, effort) != JXL_ENC_SUCCESS ||
        JxlEncoderSetFrameDistance(frame, options->jxl_distance) !=
            JXL_ENC_SUCCESS ||
        JxlEncoderAddImageFrame(frame, &format, image->pixels,
            (size_t) image->width * image->height * 3) != JXL_ENC_SUCCESS)
        goto cleanup;
    JxlEncoderCloseInput(encoder);

    compressed = (unsigned char *) malloc(capacity);
    if (!compressed) goto cleanup;
    for (;;) {
        unsigned char *next = compressed + used;
        size_t available = capacity - used;
        JxlEncoderStatus status =
            JxlEncoderProcessOutput(encoder, &next, &available);
        used = (size_t) (next - compressed);
        if (status == JXL_ENC_SUCCESS) break;
        if (status != JXL_ENC_NEED_MORE_OUTPUT) goto cleanup;
        if (capacity > SIZE_MAX / 2) goto cleanup;
        capacity *= 2;
        unsigned char *grown =
            (unsigned char *) realloc(compressed, capacity);
        if (!grown) goto cleanup;
        compressed = grown;
    }

    free(state->compressed);
    state->compressed = compressed;
    compressed = NULL;
    state->compressed_size = used;
    ok = 1;

cleanup:
    free(compressed);
    JxlEncoderDestroy(encoder);
    return ok;
}

static int jxl_decode_once(void *runner, CodecState *state) {
    JxlDecoder *decoder = JxlDecoderCreate(NULL);
    unsigned char *pixels = NULL;
    int got_info = 0;
    int got_image = 0;
    int ok = 0;
    JxlPixelFormat format = {3, JXL_TYPE_UINT8, JXL_NATIVE_ENDIAN, 0};
    if (!decoder) goto cleanup;
    if (JxlDecoderSetParallelRunner(decoder, JxlThreadParallelRunner, runner) !=
            JXL_DEC_SUCCESS ||
        JxlDecoderSubscribeEvents(decoder,
            JXL_DEC_BASIC_INFO | JXL_DEC_FULL_IMAGE) != JXL_DEC_SUCCESS)
        goto cleanup;
    JxlDecoderSetInput(decoder, state->compressed, state->compressed_size);
    JxlDecoderCloseInput(decoder);

    for (;;) {
        JxlDecoderStatus status = JxlDecoderProcessInput(decoder);
        if (status == JXL_DEC_BASIC_INFO) {
            JxlBasicInfo info;
            if (JxlDecoderGetBasicInfo(decoder, &info) != JXL_DEC_SUCCESS ||
                (int) info.xsize != state->width ||
                (int) info.ysize != state->height)
                goto cleanup;
            got_info = 1;
        } else if (status == JXL_DEC_NEED_IMAGE_OUT_BUFFER) {
            size_t bytes = 0;
            if (!got_info ||
                JxlDecoderImageOutBufferSize(decoder, &format, &bytes) !=
                    JXL_DEC_SUCCESS ||
                bytes != (size_t) state->width * state->height * 3)
                goto cleanup;
            pixels = (unsigned char *) malloc(bytes);
            if (!pixels ||
                JxlDecoderSetImageOutBuffer(decoder, &format, pixels, bytes) !=
                    JXL_DEC_SUCCESS)
                goto cleanup;
        } else if (status == JXL_DEC_FULL_IMAGE) {
            got_image = 1;
        } else if (status == JXL_DEC_SUCCESS) {
            ok = got_info && got_image && pixels != NULL;
            break;
        } else if (status == JXL_DEC_NEED_MORE_INPUT ||
                   status == JXL_DEC_ERROR) {
            goto cleanup;
        }
    }

    if (ok) {
        free(state->decoded);
        state->decoded = pixels;
        pixels = NULL;
    }

cleanup:
    free(pixels);
    JxlDecoderDestroy(decoder);
    return ok;
}
#endif

typedef struct {
    uint8_t *data;
    size_t size;
    size_t capacity;
} WebPOutput;

static int webp_write(const uint8_t *data, size_t data_size,
                      const WebPPicture *picture) {
    WebPOutput *output = (WebPOutput *) picture->custom_ptr;
    if (!output || data_size > SIZE_MAX - output->size) return 0;
    size_t required = output->size + data_size;
    if (required > output->capacity) {
        size_t capacity = output->capacity ? output->capacity : 65536u;
        while (capacity < required) {
            if (capacity > SIZE_MAX / 2u) {
                capacity = required;
                break;
            }
            capacity *= 2u;
        }
        uint8_t *grown = (uint8_t *) realloc(output->data, capacity);
        if (!grown) return 0;
        output->data = grown;
        output->capacity = capacity;
    }
    memcpy(output->data + output->size, data, data_size);
    output->size = required;
    return 1;
}

static int webp_encode_once(const Image *image, const Options *options,
                            int method, CodecState *state) {
    WebPConfig config;
    WebPPicture picture;
    WebPOutput output = {0};
    int ok = 0;
    if (!WebPConfigInit(&config) || !WebPPictureInit(&picture)) return 0;
    config.lossless = 0;
    config.quality = options->webp_quality;
    config.method = method;
    config.thread_level = options->webp_thread_level;
    if (!WebPValidateConfig(&config)) goto cleanup;

    /* Lossy WebP's native input is YUV420. Leaving use_argb disabled makes
       WebPPictureImportRGB perform the documented RGB-to-YUV conversion. */
    picture.use_argb = 0;
    picture.width = image->width;
    picture.height = image->height;
    picture.writer = webp_write;
    picture.custom_ptr = &output;
    if (!WebPPictureImportRGB(&picture, image->pixels, image->width * 3) ||
        !WebPEncode(&config, &picture) || output.size == 0) goto cleanup;

    free(state->compressed);
    state->compressed = output.data;
    output.data = NULL;
    state->compressed_size = output.size;
    ok = 1;

cleanup:
    WebPPictureFree(&picture);
    free(output.data);
    return ok;
}

static int webp_decode_once(CodecState *state) {
    int width = 0;
    int height = 0;
    if (!WebPGetInfo(state->compressed, state->compressed_size,
                     &width, &height) ||
        width != state->width || height != state->height ||
        (size_t) width > SIZE_MAX / 3u / (size_t) height) return 0;
    size_t stride = (size_t) width * 3u;
    size_t bytes = stride * (size_t) height;
    uint8_t *pixels = (uint8_t *) malloc(bytes);
    if (!pixels || !WebPDecodeRGBInto(
            state->compressed, state->compressed_size, pixels, bytes,
            (int) stride)) {
        free(pixels);
        return 0;
    }
    free(state->decoded);
    state->decoded = pixels;
    return 1;
}

static int encode_once(int codec, const Image *image, const Options *options,
                       void *jxl_runner, CodecState states[CODEC_COUNT]) {
    if (codec == CODEC_N148_CURRENT || codec == CODEC_N148_FORMAT_1)
        return n148_encode_once(
            image, options,
            codec == CODEC_N148_CURRENT ? N148I_FORMAT_VERSION :
                                          N148I_FORMAT_VERSION_1,
            &states[codec]);
    if (codec == CODEC_JPEG)
        return jpeg_encode_once(image, options, &states[codec]);
    if (codec == CODEC_JXL_E3 || codec == CODEC_JXL_E7) {
#ifdef N148_BENCH_NO_JXL
        return 0;
#else
        return jxl_encode_once(image, options,
                               codec == CODEC_JXL_E3 ? 3 : 7,
                               jxl_runner, &states[codec]);
#endif
    }
    return webp_encode_once(image, options,
                            codec == CODEC_WEBP_M4 ? 4 : 6,
                            &states[codec]);
}

static int decode_once(int codec, const Options *options, void *jxl_runner,
                       CodecState states[CODEC_COUNT]) {
    (void) options;
    if (codec == CODEC_N148_CURRENT || codec == CODEC_N148_FORMAT_1)
        return n148_decode_once(&states[codec]);
    if (codec == CODEC_JPEG)
        return jpeg_decode_once(&states[codec]);
    if (codec == CODEC_JXL_E3 || codec == CODEC_JXL_E7) {
#ifdef N148_BENCH_NO_JXL
        return 0;
#else
        return jxl_decode_once(jxl_runner, &states[codec]);
#endif
    }
    return webp_decode_once(&states[codec]);
}

static int codec_affinity(int codec, const CpuAffinity *all,
                          const CpuAffinity *jpeg, int pin_jpeg) {
    return apply_affinity(codec == CODEC_JPEG && pin_jpeg ? jpeg : all);
}

static int calibrated_inner(double elapsed, double target_ms) {
    if (!(elapsed > 0.0) || !isfinite(elapsed)) return 1;
    int inner = (int) ceil(target_ms / elapsed);
    if (inner < 1) inner = 1;
    if (inner > 256) inner = 256;
    return inner;
}

static int measure_encode(int codec, int inner, const Image *image,
                          const Options *options, void *jxl_runner,
                          CodecState states[CODEC_COUNT], double *elapsed) {
    double start = now_ms();
    for (int i = 0; i < inner; i++) {
        if (!encode_once(codec, image, options, jxl_runner, states)) return 0;
    }
    *elapsed = (now_ms() - start) / inner;
    return 1;
}

static int measure_decode(int codec, int inner, const Options *options,
                          void *jxl_runner, CodecState states[CODEC_COUNT],
                          double *elapsed) {
    double start = now_ms();
    for (int i = 0; i < inner; i++) {
        if (!decode_once(codec, options, jxl_runner, states)) return 0;
    }
    *elapsed = (now_ms() - start) / inner;
    return 1;
}

static int save_reconstruction(const char *prefix, const char *codec,
                               const CodecState *state) {
    if (!prefix) return 1;
    size_t length = strlen(prefix) + strlen(codec) + 6;
    char *path = (char *) malloc(length);
    if (!path) return 0;
    snprintf(path, length, "%s-%s.ppm", prefix, codec);
    Image output;
    output.width = state->width;
    output.height = state->height;
    output.pixels = state->decoded;
    int ok = save_ppm(path, &output);
    free(path);
    return ok;
}

static unsigned parse_codecs(const char *value) {
    if (strcmp(value, "all") == 0) return ALL_CODEC_MASK;
    if (strcmp(value, "n148i") == 0) return 1u << CODEC_N148_CURRENT;
    if (strcmp(value, "n148i_all") == 0)
        return (1u << CODEC_N148_CURRENT) | (1u << CODEC_N148_FORMAT_1);
    if (strcmp(value, "n148i_format_1") == 0)
        return 1u << CODEC_N148_FORMAT_1;
    if (strcmp(value, "jpeg") == 0) return 1u << CODEC_JPEG;
    if (strcmp(value, "jxl_e3") == 0) return 1u << CODEC_JXL_E3;
    if (strcmp(value, "jxl_e7") == 0) return 1u << CODEC_JXL_E7;
    if (strcmp(value, "webp_m4") == 0) return 1u << CODEC_WEBP_M4;
    if (strcmp(value, "webp_m6") == 0) return 1u << CODEC_WEBP_M6;
    return 0;
}

static void usage(const char *program) {
    fprintf(stderr,
        "usage: %s --input IMAGE.ppm [options]\n"
        "  --n148-quality N    N.148i quality, default 60\n"
        "  --n148-chroma-quality N  chroma quality, 0 = calibrated default\n"
        "  --n148-effort N     N.148i search effort, default 3\n"
        "  --n148-feature-flags N  N.148i feature mask, decimal or 0x hex\n"
        "  --jpeg-quality N    JPEG quality, default 60\n"
        "  --webp-quality X    WebP quality, default 60\n"
        "  --jxl-distance X    JPEG XL distance, default 2.5\n"
        "  --reps N            measured samples, default 15\n"
        "  --warmups N         warmup samples, default 3\n"
        "  --sample-ms X       target duration per batched sample, default 20\n"
        "  --chroma N          N.148i/JPEG chroma 0/1/2, default 2\n"
        "  --n148-threads N    total N.148i threads, default 1\n"
        "  --jxl-threads N     JPEG XL worker threads (0 = caller), default 0\n"
        "  --webp-thread-level N  WebP internal threading, 0 or 1\n"
        "  --jpeg-cpu N        pin JPEG to this logical CPU, default -1\n"
        "  --codecs LIST       all, n148i_all, or one codec name\n"
        "  --output-prefix P   write P-codec.ppm after timing\n",
        program);
}

static int parse_options(int argc, char **argv, Options *options) {
    *options = (Options) {
        .input = NULL,
        .output_prefix = NULL,
        .n148_quality = 60,
        .n148_chroma_quality = 0,
        .n148_effort = 3,
        .n148_feature_flags = N148I_DEFAULT_FEATURES,
        .jpeg_quality = 60,
        .webp_quality = 60.0f,
        .jxl_distance = 2.5f,
        .reps = 15,
        .warmups = 3,
        .chroma = N148I_CHROMA_420,
        .n148_threads = 1,
        .jxl_threads = 0,
        .webp_thread_level = 0,
        .jpeg_cpu = -1,
        .sample_ms = 20.0,
        .active_mask = ALL_CODEC_MASK,
    };
    static const struct option LONG_OPTIONS[] = {
        {"input", required_argument, NULL, 'i'},
        {"n148-quality", required_argument, NULL, 'n'},
        {"n148-chroma-quality", required_argument, NULL, 'C'},
        {"n148-effort", required_argument, NULL, 'e'},
        {"n148-feature-flags", required_argument, NULL, 'F'},
        {"jpeg-quality", required_argument, NULL, 'q'},
        {"webp-quality", required_argument, NULL, 'b'},
        {"jxl-distance", required_argument, NULL, 'd'},
        {"reps", required_argument, NULL, 'r'},
        {"warmups", required_argument, NULL, 'w'},
        {"sample-ms", required_argument, NULL, 's'},
        {"chroma", required_argument, NULL, 'c'},
        {"n148-threads", required_argument, NULL, 't'},
        {"jxl-threads", required_argument, NULL, 'j'},
        {"webp-thread-level", required_argument, NULL, 'u'},
        {"jpeg-cpu", required_argument, NULL, 'p'},
        {"codecs", required_argument, NULL, 'k'},
        {"output-prefix", required_argument, NULL, 'o'},
        {"help", no_argument, NULL, 'h'},
        {NULL, 0, NULL, 0},
    };
    int option;
    while ((option = getopt_long(argc, argv,
                                 "i:n:C:e:F:q:b:d:r:w:s:c:t:j:u:p:k:o:h",
                                 LONG_OPTIONS, NULL)) != -1) {
        switch (option) {
            case 'i': options->input = optarg; break;
            case 'n': options->n148_quality = atoi(optarg); break;
            case 'C': options->n148_chroma_quality = atoi(optarg); break;
            case 'e': options->n148_effort = atoi(optarg); break;
            case 'F': {
                char *end = NULL;
                errno = 0;
                unsigned long value = strtoul(optarg, &end, 0);
                if (errno || !end || *end || value > UINT32_MAX) return -1;
                options->n148_feature_flags = (uint32_t) value;
                break;
            }
            case 'q': options->jpeg_quality = atoi(optarg); break;
            case 'b': options->webp_quality = strtof(optarg, NULL); break;
            case 'd': options->jxl_distance = strtof(optarg, NULL); break;
            case 'r': options->reps = atoi(optarg); break;
            case 'w': options->warmups = atoi(optarg); break;
            case 's': options->sample_ms = strtod(optarg, NULL); break;
            case 'c': options->chroma = atoi(optarg); break;
            case 't': options->n148_threads = atoi(optarg); break;
            case 'j': options->jxl_threads = atoi(optarg); break;
            case 'u': options->webp_thread_level = atoi(optarg); break;
            case 'p': options->jpeg_cpu = atoi(optarg); break;
            case 'k': options->active_mask = parse_codecs(optarg); break;
            case 'o': options->output_prefix = optarg; break;
            case 'h': usage(argv[0]); return 0;
            default: return -1;
        }
    }
    if (!options->input || options->active_mask == 0 ||
        options->n148_quality < 1 || options->n148_quality > 100 ||
        options->n148_chroma_quality < 0 ||
        options->n148_chroma_quality > 100 ||
        options->n148_effort < 0 || options->n148_effort > 9 ||
        options->jpeg_quality < 1 || options->jpeg_quality > 100 ||
        !(options->webp_quality >= 0.0f) || options->webp_quality > 100.0f ||
        !(options->jxl_distance > 0.0f) || options->jxl_distance > 25.0f ||
        options->reps < 1 || options->warmups < 0 ||
        !(options->sample_ms > 0.0) || options->chroma < 0 ||
        options->chroma > 2 || options->n148_threads < 1 ||
        options->n148_threads > 32 || options->jxl_threads < 0 ||
        options->webp_thread_level < 0 || options->webp_thread_level > 1 ||
        options->jpeg_cpu < -1) {
        usage(argv[0]);
        return -1;
    }
    return 1;
}

int main(int argc, char **argv) {
    Options options;
    int parsed = parse_options(argc, argv, &options);
    if (parsed <= 0) return parsed == 0 ? EXIT_SUCCESS : EXIT_FAILURE;

    Image original = {0};
    CodecState states[CODEC_COUNT] = {{0}};
    CpuAffinity all_affinity, jpeg_affinity;
    int affinity_captured = 0;
    int pin_jpeg = options.jpeg_cpu >= 0;
    void *jxl_runner = NULL;
    int active[CODEC_COUNT];
    int active_count = 0;
    int result = EXIT_FAILURE;

    if (!load_ppm(options.input, &original)) goto cleanup;
    if (!capture_affinity(&all_affinity)) {
        fprintf(stderr, "could not configure CPU affinity: %s\n",
                strerror(errno));
        goto cleanup;
    }
    affinity_captured = 1;
    if (pin_jpeg && !single_cpu_affinity(&all_affinity, options.jpeg_cpu,
                                         &jpeg_affinity)) {
        fprintf(stderr, "could not configure CPU affinity: %s\n",
                strerror(errno));
        goto cleanup;
    }
    if (options.active_mask & ((1u << CODEC_JXL_E3) | (1u << CODEC_JXL_E7))) {
#ifdef N148_BENCH_NO_JXL
        fprintf(stderr, "JPEG XL is unavailable in this benchmark build\n");
        goto cleanup;
#else
        jxl_runner = JxlThreadParallelRunnerCreate(NULL,
                                                   (size_t) options.jxl_threads);
        if (!jxl_runner) {
            fprintf(stderr, "could not create JPEG XL thread runner\n");
            goto cleanup;
        }
#endif
    }
    for (int codec = 0; codec < CODEC_COUNT; codec++) {
        if (options.active_mask & (1u << codec)) active[active_count++] = codec;
        states[codec].width = original.width;
        states[codec].height = original.height;
    }

    /* One unmeasured call calibrates each batch and verifies every path. */
    for (int index = 0; index < active_count; index++) {
        int codec = active[index];
        if (!codec_affinity(codec, &all_affinity, &jpeg_affinity, pin_jpeg))
            goto cleanup;
        double start = now_ms();
        if (!encode_once(codec, &original, &options, jxl_runner, states)) {
            fprintf(stderr, "%s encode calibration failed\n", CODEC_NAMES[codec]);
            goto cleanup;
        }
        states[codec].encode_inner =
            calibrated_inner(now_ms() - start, options.sample_ms);

        start = now_ms();
        if (!decode_once(codec, &options, jxl_runner, states)) {
            fprintf(stderr, "%s decode calibration failed\n", CODEC_NAMES[codec]);
            goto cleanup;
        }
        states[codec].decode_inner =
            calibrated_inner(now_ms() - start, options.sample_ms);
    }

    printf("meta,%d,%d,%d,%d,%.9g,%d,%d,%d,%d,%u,%d\n",
           original.width, original.height, options.n148_quality,
           options.jpeg_quality, options.jxl_distance, options.reps,
           options.warmups, options.chroma, options.n148_threads,
#ifdef N148_BENCH_NO_JXL
           0u, options.jxl_threads);
#else
           (unsigned) JxlEncoderVersion(), options.jxl_threads);
#endif
    for (int index = 0; index < active_count; index++) {
        int codec = active[index];
        printf("calibration,%s,%d,%d\n", CODEC_NAMES[codec],
               states[codec].encode_inner, states[codec].decode_inner);
    }

    for (int rep = -options.warmups; rep < options.reps; rep++) {
        double encode_times[CODEC_COUNT] = {0};
        double decode_times[CODEC_COUNT] = {0};
        int rotation = (rep + options.warmups) % active_count;
        for (int pass = 0; pass < active_count; pass++) {
            int codec = active[(pass + rotation) % active_count];
            if (!codec_affinity(codec, &all_affinity, &jpeg_affinity,
                                pin_jpeg) ||
                !measure_encode(codec, states[codec].encode_inner, &original,
                                &options, jxl_runner, states,
                                &encode_times[codec])) {
                fprintf(stderr, "%s encode sample failed\n", CODEC_NAMES[codec]);
                goto cleanup;
            }
        }
        for (int pass = 0; pass < active_count; pass++) {
            int codec = active[(active_count - 1 - pass + rotation) %
                               active_count];
            if (!codec_affinity(codec, &all_affinity, &jpeg_affinity,
                                pin_jpeg) ||
                !measure_decode(codec, states[codec].decode_inner, &options,
                                jxl_runner, states, &decode_times[codec])) {
                fprintf(stderr, "%s decode sample failed\n", CODEC_NAMES[codec]);
                goto cleanup;
            }
        }
        if (rep >= 0) {
            for (int index = 0; index < active_count; index++) {
                int codec = active[index];
                printf("sample,%s,%d,%.12f,%.12f\n", CODEC_NAMES[codec], rep,
                       encode_times[codec], decode_times[codec]);
            }
        }
    }

    if (!apply_affinity(&all_affinity)) goto cleanup;
    for (int index = 0; index < active_count; index++) {
        int codec = active[index];
        if (!states[codec].decoded || states[codec].compressed_size == 0 ||
            !save_reconstruction(options.output_prefix, CODEC_NAMES[codec],
                                 &states[codec])) {
            fprintf(stderr, "%s output validation failed\n", CODEC_NAMES[codec]);
            goto cleanup;
        }
        printf("result,%s,%zu,%s\n", CODEC_NAMES[codec],
               states[codec].compressed_size,
               options.output_prefix ? "reconstruction_written" : "validated");
    }
    fflush(stdout);
    result = EXIT_SUCCESS;

cleanup:
    if (affinity_captured) apply_affinity(&all_affinity);
    for (int codec = 0; codec < CODEC_COUNT; codec++)
        free_state(codec, &states[codec]);
#ifndef N148_BENCH_NO_JXL
    JxlThreadParallelRunnerDestroy(jxl_runner);
#endif
    free_image(&original);
    return result;
}

A pasta src: os arquivos da V1 que continuaram iguais

Estes 9 arquivos não mudaram nenhuma linha, mas estão aqui completos para que a V2 fique inteira no artigo.

src/header.c

O header.c escreve e lê os campos do cabeçalho byte a byte, como no artigo 14.

Ele não mudou da V1 para a V2, e o arquivo completo tem 90 linhas:

#include <string.h>

#include "header.h"

void write_u8(FILE *file, uint8_t value) {
    fputc(value, file);
}

void write_u32(FILE *file, uint32_t value) {
    fputc((value) & 0xFF, file); // Little-endian, byte by byte.
    fputc((value >> 8) & 0xFF, file);
    fputc((value >> 16) & 0xFF, file);
    fputc((value >> 24) & 0xFF, file);
}

uint8_t read_u8(FILE *file) {
    return (uint8_t)fgetc(file);
}

uint32_t read_u32(FILE *file) {
    uint32_t b0 = (uint32_t)fgetc(file);
    uint32_t b1 = (uint32_t)fgetc(file);
    uint32_t b2 = (uint32_t)fgetc(file);
    uint32_t b3 = (uint32_t)fgetc(file);

    return b0 | (b1 << 8) | (b2 << 16) | (b3 << 24);
}

int write_header(FILE *file, N148iHeader *header) {
    if (fwrite(N148I_MAGIC, 1, N148I_MAGIC_LEN, file) != N148I_MAGIC_LEN) {
        return 0;
    }
    write_u8(file, header->version);
    write_u32(file, header->width);
    write_u32(file, header->height);
    write_u8(file, header->quality);
    write_u8(file, header->chroma);
    write_u8(file, header->optimized);
    write_u32(file, header->data_size);
    return ferror(file) == 0;
}

int read_header(FILE *file, N148iHeader *header) {
    char magic[6] = {0};
    if (fread(magic, 1, N148I_MAGIC_LEN, file) != N148I_MAGIC_LEN) {
        return 0;
    }
    if (memcmp(magic, N148I_MAGIC, N148I_MAGIC_LEN) != 0) {
        return 0;
    }

    unsigned char fields[16];
    if (fread(fields, 1, sizeof(fields), file) != sizeof(fields)) {
        return 0;
    }

    header->version = fields[0];
    header->width =
        (uint32_t)fields[1] |
        ((uint32_t)fields[2] << 8) |
        ((uint32_t)fields[3] << 16) |
        ((uint32_t)fields[4] << 24);
    header->height =
        (uint32_t)fields[5] |
        ((uint32_t)fields[6] << 8) |
        ((uint32_t)fields[7] << 16) |
        ((uint32_t)fields[8] << 24);
    header->quality = fields[9];
    header->chroma = fields[10];
    header->optimized = fields[11];
    header->data_size =
        (uint32_t)fields[12] |
        ((uint32_t)fields[13] << 8) |
        ((uint32_t)fields[14] << 16) |
        ((uint32_t)fields[15] << 24);
    return 1;
}

const char *chroma_name(uint8_t chroma) {
    switch (chroma) {
        case CHROMA_444:
            return "4:4:4";
        case CHROMA_422:
            return "4:2:2";
        case CHROMA_420:
            return "4:2:0";
        default:
            return "unknown";
    }
}

src/huffman.h

O huffman.h é a interface do Huffman, dos artigos 6 e 13, que a V2 ainda usa para ler e escrever o formato 1.

Ele não mudou da V1 para a V2, e o arquivo completo tem 35 linhas:

#ifndef HUFFMAN_H
#define HUFFMAN_H

#include <stdio.h>

#define HUFFMAN_TABLE_COUNT 4
#define HUFFMAN_MAX_SYMBOLS 256

enum {
    HUFFMAN_DC_LUMA = 0,
    HUFFMAN_AC_LUMA = 1,
    HUFFMAN_DC_CHROMA = 2,
    HUFFMAN_AC_CHROMA = 3
};

// Canonical Huffman table description. bits[length] stores how many codes
// have that length; values stores their symbols in canonical order.
typedef struct {
    int bits[17];
    unsigned char values[HUFFMAN_MAX_SYMBOLS];
    int value_count;
} HuffSpec;

void huffman_default_specs(HuffSpec specs[HUFFMAN_TABLE_COUNT]);
int huffman_build_optimized(const long frequencies[HUFFMAN_MAX_SYMBOLS],
                            HuffSpec *spec);
int huffman_spec_is_valid(const HuffSpec *spec);

long huffman_tables_size(const HuffSpec specs[HUFFMAN_TABLE_COUNT]);
int write_huffman_tables(FILE *file,
                         const HuffSpec specs[HUFFMAN_TABLE_COUNT]);
int read_huffman_tables(FILE *file,
                        HuffSpec specs[HUFFMAN_TABLE_COUNT]);

#endif

src/huffman.c

O huffman.c implementa esse Huffman, com a construção das tabelas e dos códigos.

Ele não mudou da V1 para a V2, e o arquivo completo tem 248 linhas:

#include <string.h>

#include "huffman.h"
#include "tables.h"

#define RESERVED_SYMBOL 256
#define MAX_CODE_LENGTH 32

static void copy_spec(HuffSpec *spec, const int bits[17],
                      const unsigned char *values, int value_count) {
    memcpy(spec->bits, bits, sizeof(spec->bits));
    memcpy(spec->values, values, (size_t)value_count);
    spec->value_count = value_count;
}

void huffman_default_specs(HuffSpec specs[HUFFMAN_TABLE_COUNT]) {
    copy_spec(&specs[HUFFMAN_DC_LUMA],
              BITS_DC_LUMA, VAL_DC_LUMA, 12);
    copy_spec(&specs[HUFFMAN_AC_LUMA],
              BITS_AC_LUMA, VAL_AC_LUMA, 162);
    copy_spec(&specs[HUFFMAN_DC_CHROMA],
              BITS_DC_CHROMA, VAL_DC_CHROMA, 12);
    copy_spec(&specs[HUFFMAN_AC_CHROMA],
              BITS_AC_CHROMA, VAL_AC_CHROMA, 162);
}

// JPEG Annex K.2 computes code lengths without allocating a tree. The
// others array links every symbol already merged into the same branch.
static void compute_code_sizes(const long frequency_input[256],
                               int code_size[257]) {
    long frequency[257];
    int others[257];

    for (int i = 0; i < 256; i++) {
        frequency[i] = frequency_input[i];
    }
    frequency[RESERVED_SYMBOL] = 1;

    for (int i = 0; i <= RESERVED_SYMBOL; i++) {
        code_size[i] = 0;
        others[i] = -1;
    }

    for (;;) {
        int first = -1;
        int second = -1;
        long first_frequency = 0;
        long second_frequency = 0;

        // Ties deliberately select the highest symbol, matching Annex K.
        for (int i = 0; i <= RESERVED_SYMBOL; i++) {
            if (frequency[i] == 0) {
                continue;
            }
            if (first < 0 || frequency[i] <= first_frequency) {
                second = first;
                second_frequency = first_frequency;
                first = i;
                first_frequency = frequency[i];
            } else if (second < 0 || frequency[i] <= second_frequency) {
                second = i;
                second_frequency = frequency[i];
            }
        }

        if (second < 0) {
            break;
        }

        frequency[first] += frequency[second];
        frequency[second] = 0;

        code_size[first]++;
        while (others[first] != -1) {
            first = others[first];
            code_size[first]++;
        }
        others[first] = second;

        code_size[second]++;
        while (others[second] != -1) {
            second = others[second];
            code_size[second]++;
        }
    }
}

// Squeeze codes longer than 16 bits down to JPEG's canonical-table limit.
static int limit_to_16_bits(int bits[33]) {
    for (int length = MAX_CODE_LENGTH; length > 16; length--) {
        while (bits[length] > 0) {
            int shorter = length - 2;
            while (shorter > 0 && bits[shorter] == 0) {
                shorter--;
            }
            if (shorter == 0 || bits[length] < 2) {
                return 0;
            }

            bits[length] -= 2;
            bits[length - 1]++;
            bits[shorter + 1] += 2;
            bits[shorter]--;
        }
    }
    return 1;
}

int huffman_build_optimized(const long frequencies[256], HuffSpec *spec) {
    int code_size[257];
    int bits[33] = {0};
    int symbol_count = 0;

    compute_code_sizes(frequencies, code_size);

    for (int symbol = 0; symbol <= RESERVED_SYMBOL; symbol++) {
        int length = code_size[symbol];
        if (length < 0 || length > MAX_CODE_LENGTH) {
            return 0;
        }
        if (length > 0) {
            bits[length]++;
        }
        if (symbol < RESERVED_SYMBOL && frequencies[symbol] > 0) {
            symbol_count++;
        }
    }

    if (symbol_count == 0 || !limit_to_16_bits(bits)) {
        return 0;
    }

    // Remove the reserved all-ones code from the longest occupied length.
    int longest = 16;
    while (longest > 0 && bits[longest] == 0) {
        longest--;
    }
    if (longest == 0) {
        return 0;
    }
    bits[longest]--;

    memset(spec, 0, sizeof(*spec));
    for (int length = 1; length <= 16; length++) {
        spec->bits[length] = bits[length];
    }

    // Annex K orders equal-length symbols by symbol value. Length limiting
    // changes the counts, but the original order remains canonical.
    for (int length = 1; length <= MAX_CODE_LENGTH; length++) {
        for (int symbol = 0; symbol < 256; symbol++) {
            if (code_size[symbol] == length) {
                spec->values[spec->value_count++] =
                    (unsigned char)symbol;
            }
        }
    }

    return spec->value_count == symbol_count &&
           huffman_spec_is_valid(spec);
}

int huffman_spec_is_valid(const HuffSpec *spec) {
    if (!spec || spec->value_count <= 0 ||
        spec->value_count > HUFFMAN_MAX_SYMBOLS) {
        return 0;
    }

    int count = 0;
    int code = 0;
    for (int length = 1; length <= 16; length++) {
        int length_count = spec->bits[length];
        if (length_count < 0 || length_count > 255 ||
            code + length_count > (1 << length)) {
            return 0;
        }
        count += length_count;
        code = (code + length_count) << 1;
    }
    if (count != spec->value_count) {
        return 0;
    }

    unsigned char seen[256] = {0};
    for (int i = 0; i < spec->value_count; i++) {
        if (seen[spec->values[i]]) {
            return 0;
        }
        seen[spec->values[i]] = 1;
    }
    return 1;
}

long huffman_tables_size(const HuffSpec specs[HUFFMAN_TABLE_COUNT]) {
    long size = 0;
    for (int table = 0; table < HUFFMAN_TABLE_COUNT; table++) {
        size += 16 + specs[table].value_count;
    }
    return size;
}

int write_huffman_tables(FILE *file,
                         const HuffSpec specs[HUFFMAN_TABLE_COUNT]) {
    for (int table = 0; table < HUFFMAN_TABLE_COUNT; table++) {
        if (!huffman_spec_is_valid(&specs[table])) {
            return 0;
        }
        for (int length = 1; length <= 16; length++) {
            if (fputc(specs[table].bits[length], file) == EOF) {
                return 0;
            }
        }
        if (fwrite(specs[table].values, 1,
                   (size_t)specs[table].value_count, file) !=
            (size_t)specs[table].value_count) {
            return 0;
        }
    }
    return ferror(file) == 0;
}

int read_huffman_tables(FILE *file,
                        HuffSpec specs[HUFFMAN_TABLE_COUNT]) {
    for (int table = 0; table < HUFFMAN_TABLE_COUNT; table++) {
        HuffSpec *spec = &specs[table];
        memset(spec, 0, sizeof(*spec));

        for (int length = 1; length <= 16; length++) {
            int count = fgetc(file);
            if (count == EOF) {
                return 0;
            }
            spec->bits[length] = count;
            spec->value_count += count;
            if (spec->value_count > HUFFMAN_MAX_SYMBOLS) {
                return 0;
            }
        }

        if (spec->value_count == 0 ||
            fread(spec->values, 1, (size_t)spec->value_count, file) !=
                (size_t)spec->value_count ||
            !huffman_spec_is_valid(spec)) {
            return 0;
        }
    }
    return 1;
}

src/cpu.h

O cpu.h declara a detecção dos recursos do processador, do artigo 22, que decide uma vez só se o codec usa o caminho escalar ou o AVX2.

Ele não mudou da V1 para a V2, e o arquivo completo tem 30 linhas:

/*
 * N.148 codec - runtime CPU feature detection.
 *
 * The codec ships several implementations of its hot loops: a portable
 * scalar one that runs anywhere, and hand-tuned SIMD ones. Which path
 * runs is decided ONCE at startup by asking the CPU what it supports,
 * so a single binary stays fast on modern machines and correct on old
 * ones.
 */
#ifndef CPU_H
#define CPU_H

#define N148_CPU_BASELINE 0
#define N148_CPU_SSE2     1
#define N148_CPU_AVX2     2
#define N148_CPU_AVX2_FMA 3

// Detects the CPU once and caches the answer.
int n148_cpu_level(void);

// Returns the hardware-detected level, ignoring any test override.
int n148_cpu_detected_level(void);

// Human readable name of the active path, for reporting.
const char *n148_cpu_name(void);

// Forces a level (used by the test suite to compare paths).
void n148_cpu_force(int level);

#endif

src/cpu.c

O cpu.c implementa essa detecção, perguntando ao processador quais instruções ele suporta logo no começo do programa.

Ele não mudou da V1 para a V2, e o arquivo completo tem 85 linhas:

#include "cpu.h"

#if defined(__x86_64__) || defined(__i386__)
#define N148_X86 1
#endif

#ifdef N148_X86
#if defined(_MSC_VER)
#include <intrin.h>
static void cpuid_count(int leaf, int sub, int regs[4]) {
    __cpuidex(regs, leaf, sub);
}
#else
#include <cpuid.h>
static void cpuid_count(int leaf, int sub, int regs[4]) {
    __cpuid_count(leaf, sub, regs[0], regs[1], regs[2], regs[3]);
}
#endif

// The OS must also agree to save the wide registers on a context
// switch. Checking CPUID alone is not enough: xgetbv tells us whether
// the operating system has enabled AVX state saving.
static int os_supports_avx(void) {
#if defined(_MSC_VER)
    unsigned long long xcr = _xgetbv(0);
#else
    unsigned int eax, edx;
    __asm__ volatile (".byte 0x0f, 0x01, 0xd0" : "=a"(eax), "=d"(edx) : "c"(0));
    unsigned long long xcr = ((unsigned long long) edx << 32) | eax;
#endif
    return (xcr & 0x6) == 0x6;      // XMM and YMM state enabled
}
#endif

static int detected = -1;
static int forced   = -1;

static int detect(void) {
#ifdef N148_X86
    int regs[4];

    cpuid_count(0, 0, regs);
    int max_leaf = regs[0];

    cpuid_count(1, 0, regs);
    int has_sse2   = (regs[3] >> 26) & 1;
    int has_fma    = (regs[2] >> 12) & 1;
    int has_osxsave= (regs[2] >> 27) & 1;
    int has_avx    = (regs[2] >> 28) & 1;

    int has_avx2 = 0;
    if (max_leaf >= 7) {
        cpuid_count(7, 0, regs);
        has_avx2 = (regs[1] >> 5) & 1;
    }

    if (has_avx2 && has_avx && has_osxsave && os_supports_avx())
        return has_fma ? N148_CPU_AVX2_FMA : N148_CPU_AVX2;
    if (has_sse2)
        return N148_CPU_SSE2;
#endif
    return N148_CPU_BASELINE;
}

int n148_cpu_level(void) {
    if (forced >= 0) return forced;
    if (detected < 0) detected = detect();
    return detected;
}

int n148_cpu_detected_level(void) {
    if (detected < 0) detected = detect();
    return detected;
}

void n148_cpu_force(int level) { forced = level; }

const char *n148_cpu_name(void) {
    switch (n148_cpu_level()) {
        case N148_CPU_AVX2_FMA: return "AVX2+FMA";
        case N148_CPU_AVX2: return "AVX2";
        case N148_CPU_SSE2: return "SSE2";
        default:            return "scalar";
    }
}

src/parallel.h

O parallel.h é o ajudante de paralelismo do artigo 24, que divide um intervalo entre as threads e espera todas terminarem.

Ele não mudou da V1 para a V2, e o arquivo completo tem 26 linhas:

/*
 * N.148 codec - a small parallel helper.
 *
 * Several stages of the codec are embarrassingly parallel: colour
 * conversion, the forward transform and the final reconstruction all
 * treat rows (or rows of blocks) independently. This helper splits a
 * range across worker threads and waits for them, without pulling in
 * a full thread pool.
 *
 * Build without N148_THREADS defined, or set the thread count to 1,
 * and everything runs inline on the calling thread.
 */
#ifndef PARALLEL_H
#define PARALLEL_H

// Number of workers the codec will use. Defaults to the number of
// cores reported by the system, clamped to a sane maximum.
int  n148_thread_count(void);
void n148_set_thread_count(int count);

// Calls body(start, end, index, context) over [0, total) split into
// contiguous chunks, one per worker.
typedef void (*ParallelBody)(long start, long end, int worker, void *context);
void n148_parallel_for(long total, ParallelBody body, void *context);

#endif

src/parallel.c

O parallel.c implementa esse ajudante com threads POSIX e roda tudo na thread atual quando as threads estão desligadas.

Ele não mudou da V1 para a V2, e o arquivo completo tem 197 linhas:

#include <stdlib.h>
#include "parallel.h"

#define N148_MAX_THREADS 32

#if defined(_WIN32) && !defined(N148_NO_THREADS)
#include <windows.h>
#elif !defined(N148_NO_THREADS) && (defined(__unix__) || defined(__APPLE__))
#include <pthread.h>
#include <unistd.h>
#define N148_HAVE_PTHREADS 1
#elif defined(__unix__) || defined(__APPLE__)
#include <unistd.h>
#endif

static int configured = 0;

static int detect_cores(void) {
#if defined(N148_NO_THREADS)
    return 1;
#elif defined(_WIN32)
    SYSTEM_INFO info;
    GetSystemInfo(&info);
    return (int) info.dwNumberOfProcessors;
#elif defined(_SC_NPROCESSORS_ONLN)
    long count = sysconf(_SC_NPROCESSORS_ONLN);
    return count > 0 ? (int) count : 1;
#else
    return 1;
#endif
}

int n148_thread_count(void) {
    if (configured == 0) {
        configured = detect_cores();
        if (configured < 1) configured = 1;
        if (configured > N148_MAX_THREADS) configured = N148_MAX_THREADS;
    }
    return configured;
}

void n148_set_thread_count(int count) {
    if (count < 1) count = 1;
    if (count > N148_MAX_THREADS) count = N148_MAX_THREADS;
#ifdef N148_NO_THREADS
    count = 1;
#endif
    configured = count;
}

#ifdef N148_HAVE_PTHREADS
typedef struct {
    int index;
    unsigned long generation;
} WorkerSlot;

typedef struct {
    pthread_mutex_t state_lock;
    pthread_mutex_t dispatch_lock;
    pthread_cond_t work_ready;
    pthread_cond_t work_done;
    pthread_t threads[N148_MAX_THREADS - 1];
    WorkerSlot slots[N148_MAX_THREADS - 1];
    int initialized;
    int capacity;
    int participants;
    int remaining;
    int stopping;
    unsigned long generation;
    long total;
    ParallelBody body;
    void *context;
} ThreadPool;

static ThreadPool pool = {
    .state_lock = PTHREAD_MUTEX_INITIALIZER,
    .dispatch_lock = PTHREAD_MUTEX_INITIALIZER,
    .work_ready = PTHREAD_COND_INITIALIZER,
    .work_done = PTHREAD_COND_INITIALIZER
};

static void *pool_worker(void *raw) {
    WorkerSlot *slot = (WorkerSlot *) raw;
    pthread_mutex_lock(&pool.state_lock);

    for (;;) {
        while (!pool.stopping && slot->generation == pool.generation)
            pthread_cond_wait(&pool.work_ready, &pool.state_lock);
        if (pool.stopping) break;

        slot->generation = pool.generation;
        int index = slot->index;
        if (index >= pool.participants) continue;

        long total = pool.total;
        int participants = pool.participants;
        ParallelBody body = pool.body;
        void *context = pool.context;
        long start = total * index / participants;
        long end = total * (index + 1) / participants;

        pthread_mutex_unlock(&pool.state_lock);
        body(start, end, index, context);
        pthread_mutex_lock(&pool.state_lock);

        if (--pool.remaining == 0)
            pthread_cond_signal(&pool.work_done);
    }

    pthread_mutex_unlock(&pool.state_lock);
    return NULL;
}

static void pool_shutdown(void) {
    pthread_mutex_lock(&pool.dispatch_lock);
    if (!pool.initialized) {
        pthread_mutex_unlock(&pool.dispatch_lock);
        return;
    }

    pthread_mutex_lock(&pool.state_lock);
    pool.stopping = 1;
    pool.generation++;
    pthread_cond_broadcast(&pool.work_ready);
    pthread_mutex_unlock(&pool.state_lock);

    for (int i = 0; i < pool.capacity; i++)
        pthread_join(pool.threads[i], NULL);
    pool.initialized = 0;
    pool.capacity = 0;
    pthread_mutex_unlock(&pool.dispatch_lock);
}

/* Called with dispatch_lock held. */
static void pool_initialize(int background_workers) {
    if (pool.initialized) return;

    pool.initialized = 1;
    pool.capacity = 0;
    pool.stopping = 0;
    pool.generation = 0;
    if (background_workers > N148_MAX_THREADS - 1)
        background_workers = N148_MAX_THREADS - 1;

    for (int i = 0; i < background_workers; i++) {
        WorkerSlot *slot = &pool.slots[i];
        slot->index = i + 1;
        slot->generation = 0;
        if (pthread_create(&pool.threads[i], NULL, pool_worker, slot) != 0)
            break;
        pool.capacity++;
    }
    atexit(pool_shutdown);
}
#endif

void n148_parallel_for(long total, ParallelBody body, void *context) {
    if (total <= 0) return;

    int workers = n148_thread_count();
    if (workers <= 1 || total < 8) {
        body(0, total, 0, context);
        return;
    }
    if (workers > total) workers = (int) total;

#ifdef N148_HAVE_PTHREADS
    pthread_mutex_lock(&pool.dispatch_lock);
    pool_initialize(workers - 1);
    if (workers > pool.capacity + 1) workers = pool.capacity + 1;
    if (workers <= 1) {
        pthread_mutex_unlock(&pool.dispatch_lock);
        body(0, total, 0, context);
        return;
    }

    pthread_mutex_lock(&pool.state_lock);
    pool.total = total;
    pool.participants = workers;
    pool.remaining = workers - 1;
    pool.body = body;
    pool.context = context;
    pool.generation++;
    pthread_cond_broadcast(&pool.work_ready);
    pthread_mutex_unlock(&pool.state_lock);

    body(0, total / workers, 0, context);

    pthread_mutex_lock(&pool.state_lock);
    while (pool.remaining != 0)
        pthread_cond_wait(&pool.work_done, &pool.state_lock);
    pthread_mutex_unlock(&pool.state_lock);
    pthread_mutex_unlock(&pool.dispatch_lock);
#else
    body(0, total, 0, context);
#endif
}

src/bench_cli.c

O bench_cli.c mede o tempo de encode e de decode do caminho da V1, e foi a ferramenta usada no bloco de desempenho, do artigo 19 ao artigo 24.

Ele não mudou da V1 para a V2, e o arquivo completo tem 63 linhas:

/* Benchmark CLI for N.148i — part of the N.148 project (MIT, (c) Micilini Roll) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include "header.h"
#include "tables.h"
#include "ppm.h"
#include "encoder.h"
#include "decoder.h"
#include "parallel.h"

static double now(void){struct timespec t;clock_gettime(CLOCK_MONOTONIC,&t);return t.tv_sec+t.tv_nsec/1e9;}

int main(int argc, char **argv) {
    if (argc < 3) { printf("usage: bench in.ppm quality [reps] [chroma] [threads]\n"); return 1; }
    const char *in = argv[1];
    int quality = atoi(argv[2]);
    int reps = (argc>3)?atoi(argv[3]):10;
    int chroma = (argc>4)?atoi(argv[4]):CHROMA_420;
    if (argc > 5) n148_set_thread_count(atoi(argv[5]));

    Image original;
    if (!load_ppm(in, &original)) return 1;

    /* --- ENCODE timing (color conversion + entropy coding) --- */
    double t = now();
    unsigned char *compressed = NULL; EncodeStats st; HuffSpec specs[4];
    for (int i=0;i<reps;i++){
        Plane y,cb,cr;
        split_channels(&original,&y,&cb,&cr,chroma);
        if (compressed) { free(compressed); compressed=NULL; }
        encode_image(&y,&cb,&cr,quality,1,specs,&compressed,&st);
        free_plane(&y); free_plane(&cb); free_plane(&cr);
    }
    double t_enc = (now()-t)/reps*1000;

    long total = 21 + st.table_size + st.data_size;

    /* --- DECODE timing --- */
    t = now();
    Image dec; memset(&dec,0,sizeof(dec));
    for (int i=0;i<reps;i++){
        Plane dy,dcb,dcr; DecodeStats ds;
        decode_image(compressed, st.data_size, original.width, original.height,
                     quality, chroma, specs, &dy,&dcb,&dcr,&ds);
        if (dec.pixels) free_image(&dec);
        merge_channels(&dy,&dcb,&dcr,1,&dec);
        free_plane(&dy); free_plane(&dcb); free_plane(&dcr);
    }
    double t_dec = (now()-t)/reps*1000;

    /* --- PSNR --- */
    double mse=0; long n=(long)original.width*original.height*3;
    for (long i=0;i<n;i++){ double d=(double)original.pixels[i]-(double)dec.pixels[i]; mse+=d*d; }
    mse/=n;
    double psnr = (mse==0)?999.0:10.0*log10(255.0*255.0/mse);

    printf("%-14s %dx%d q=%d | enc %7.2f ms | dec %7.2f ms | %8ld B | PSNR %6.2f dB\n",
           in, original.width, original.height, quality, t_enc, t_dec, total, psnr);
    return 0;
}

src/compare_cli.c

O compare_cli.c compara o N.148i com o libjpeg-turbo na memória, com a mesma imagem já carregada para os dois, como no artigo 25.

Ele não mudou da V1 para a V2, e o arquivo completo tem 396 linhas:

/*
 * In-memory N.148i vs libjpeg-turbo benchmark.
 *
 * Both codecs receive the same already-loaded RGB image.  Timings include
 * colour conversion, transform, entropy coding/decoding, allocation and
 * reconstruction, but exclude disk I/O and PSNR calculation.
 */
#define _GNU_SOURCE
#include <math.h>
#if defined(__linux__)
#include <sched.h>
#endif
#include <setjmp.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <jpeglib.h>

#include "decoder.h"
#include "encoder.h"
#include "header.h"
#include "ppm.h"
#include "parallel.h"

typedef struct {
    struct jpeg_error_mgr base;
    jmp_buf jump;
} JpegError;

static void jpeg_error_exit(j_common_ptr common) {
    JpegError *error = (JpegError *) common->err;
    longjmp(error->jump, 1);
}

static double now_ms(void) {
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return ts.tv_sec * 1000.0 + ts.tv_nsec / 1000000.0;
}

static int compare_double(const void *left, const void *right) {
    double a = *(const double *) left;
    double b = *(const double *) right;
    return (a > b) - (a < b);
}

static double median(double *values, int count) {
    qsort(values, (size_t) count, sizeof(*values), compare_double);
    if (count & 1) return values[count / 2];
    return (values[count / 2 - 1] + values[count / 2]) * 0.5;
}

#if defined(__linux__)
typedef cpu_set_t CpuAffinity;

static int capture_affinity(CpuAffinity *mask) {
    return sched_getaffinity(0, sizeof(*mask), mask) == 0;
}

static int select_affinity_cpu(const CpuAffinity *allowed, int cpu,
                               CpuAffinity *single) {
    if (cpu < 0 || cpu >= CPU_SETSIZE || !CPU_ISSET(cpu, allowed)) return 0;
    CPU_ZERO(single);
    CPU_SET(cpu, single);
    return 1;
}

static int apply_affinity(const CpuAffinity *mask) {
    return sched_setaffinity(0, sizeof(*mask), mask) == 0;
}
#else
typedef int CpuAffinity;

static int capture_affinity(CpuAffinity *mask) {
    *mask = 0;
    return 1;
}

static int select_affinity_cpu(const CpuAffinity *allowed, int cpu,
                               CpuAffinity *single) {
    (void) allowed;
    (void) cpu;
    (void) single;
    return 0;
}

static int apply_affinity(const CpuAffinity *mask) {
    (void) mask;
    return 1;
}
#endif

static double image_psnr(const Image *original, const unsigned char *decoded) {
    long count = (long) original->width * original->height * 3;
    double error = 0.0;
    for (long i = 0; i < count; i++) {
        double difference = (double) original->pixels[i] - decoded[i];
        error += difference * difference;
    }
    error /= count;
    return error == 0.0 ? 999.0 : 10.0 * log10(255.0 * 255.0 / error);
}

static int n148_encode(const Image *image, int quality, int chroma,
                       unsigned char **data, long *size,
                       HuffSpec specs[HUFFMAN_TABLE_COUNT]) {
    Plane y = {0}, cb = {0}, cr = {0};
    EncodeStats stats;
    if (!split_channels((Image *) image, &y, &cb, &cr, chroma)) return 0;
    int ok = encode_image(&y, &cb, &cr, quality, 1, specs, data, &stats);
    free_plane(&y);
    free_plane(&cb);
    free_plane(&cr);
    if (!ok) return 0;
    *size = 21 + stats.table_size + stats.data_size;
    return 1;
}

static int n148_decode(const unsigned char *data, long payload_size,
                       int width, int height, int quality, int chroma,
                       const HuffSpec specs[HUFFMAN_TABLE_COUNT], Image *output,
                       double *plane_ms, double *merge_ms) {
    Plane y = {0}, cb = {0}, cr = {0};
    DecodeStats stats;
    double start = now_ms();
    int ok = decode_image((unsigned char *) data, payload_size, width, height,
                          quality, chroma, specs, &y, &cb, &cr, &stats);
    double split = now_ms();
    if (ok) ok = merge_channels(&y, &cb, &cr, 1, output);
    double merged = now_ms();
    free_plane(&y);
    free_plane(&cb);
    free_plane(&cr);
    if (plane_ms) *plane_ms = split - start;
    if (merge_ms) *merge_ms = merged - split;
    return ok;
}

static void jpeg_sampling(struct jpeg_compress_struct *jpeg, int chroma) {
    jpeg->comp_info[0].h_samp_factor = chroma == CHROMA_444 ? 1 : 2;
    jpeg->comp_info[0].v_samp_factor = chroma == CHROMA_420 ? 2 : 1;
    jpeg->comp_info[1].h_samp_factor = 1;
    jpeg->comp_info[1].v_samp_factor = 1;
    jpeg->comp_info[2].h_samp_factor = 1;
    jpeg->comp_info[2].v_samp_factor = 1;
}

static int jpeg_encode(const Image *image, int quality, int chroma,
                       unsigned char **data, unsigned long *size) {
    struct jpeg_compress_struct jpeg;
    JpegError error;
    jpeg.err = jpeg_std_error(&error.base);
    error.base.error_exit = jpeg_error_exit;
    if (setjmp(error.jump)) {
        jpeg_destroy_compress(&jpeg);
        free(*data);
        *data = NULL;
        return 0;
    }

    jpeg_create_compress(&jpeg);
    jpeg_mem_dest(&jpeg, data, size);
    jpeg.image_width = (JDIMENSION) image->width;
    jpeg.image_height = (JDIMENSION) image->height;
    jpeg.input_components = 3;
    jpeg.in_color_space = JCS_RGB;
    jpeg_set_defaults(&jpeg);
    jpeg_set_quality(&jpeg, quality, TRUE);
    jpeg_sampling(&jpeg, chroma);
    jpeg.optimize_coding = TRUE;

    jpeg_start_compress(&jpeg, TRUE);
    while (jpeg.next_scanline < jpeg.image_height) {
        JSAMPROW row = image->pixels +
            (long) jpeg.next_scanline * image->width * 3;
        jpeg_write_scanlines(&jpeg, &row, 1);
    }
    jpeg_finish_compress(&jpeg);
    jpeg_destroy_compress(&jpeg);
    return 1;
}

static int jpeg_decode(const unsigned char *data, unsigned long size,
                       unsigned char **pixels, int *width, int *height) {
    struct jpeg_decompress_struct jpeg;
    JpegError error;
    jpeg.err = jpeg_std_error(&error.base);
    error.base.error_exit = jpeg_error_exit;
    if (setjmp(error.jump)) {
        jpeg_destroy_decompress(&jpeg);
        free(*pixels);
        *pixels = NULL;
        return 0;
    }

    jpeg_create_decompress(&jpeg);
    jpeg_mem_src(&jpeg, data, size);
    jpeg_read_header(&jpeg, TRUE);
    jpeg.out_color_space = JCS_RGB;
    jpeg_start_decompress(&jpeg);

    *width = (int) jpeg.output_width;
    *height = (int) jpeg.output_height;
    size_t stride = (size_t) *width * jpeg.output_components;
    *pixels = (unsigned char *) malloc(stride * (size_t) *height);
    if (!*pixels) {
        jpeg_destroy_decompress(&jpeg);
        return 0;
    }

    while (jpeg.output_scanline < jpeg.output_height) {
        JSAMPROW row = *pixels + (size_t) jpeg.output_scanline * stride;
        jpeg_read_scanlines(&jpeg, &row, 1);
    }
    jpeg_finish_decompress(&jpeg);
    jpeg_destroy_decompress(&jpeg);
    return 1;
}

int main(int argc, char **argv) {
    if (argc < 3) {
        fprintf(stderr,
                "usage: %s image.ppm quality [reps] [chroma] [threads] "
                "[jpeg_cpu]\n",
                argv[0]);
        return EXIT_FAILURE;
    }

    const char *path = argv[1];
    int quality = atoi(argv[2]);
    int reps = argc > 3 ? atoi(argv[3]) : 30;
    int chroma = argc > 4 ? atoi(argv[4]) : CHROMA_420;
    int jpeg_cpu = argc > 6 ? atoi(argv[6]) : -1;
    if (argc > 5) n148_set_thread_count(atoi(argv[5]));
    if (quality < 1 || quality > 100 || reps < 1 ||
        chroma < 0 || chroma > 2 || jpeg_cpu < -1) {
        fprintf(stderr, "invalid quality, repetition count or chroma mode\n");
        return EXIT_FAILURE;
    }

    Image original = {0};
    if (!load_ppm(path, &original)) return EXIT_FAILURE;

    CpuAffinity n148_affinity, jpeg_affinity;
    int pin_jpeg = jpeg_cpu >= 0;
    if (pin_jpeg &&
        (!capture_affinity(&n148_affinity) ||
         !select_affinity_cpu(&n148_affinity, jpeg_cpu, &jpeg_affinity))) {
        fprintf(stderr, "jpeg_cpu is unavailable or affinity control failed\n");
        return EXIT_FAILURE;
    }

    double *n148_enc = (double *) malloc((size_t) reps * sizeof(double));
    double *n148_dec = (double *) malloc((size_t) reps * sizeof(double));
    double *n148_planes = (double *) malloc((size_t) reps * sizeof(double));
    double *n148_merge = (double *) malloc((size_t) reps * sizeof(double));
    double *jpeg_enc = (double *) malloc((size_t) reps * sizeof(double));
    double *jpeg_dec = (double *) malloc((size_t) reps * sizeof(double));
    if (!n148_enc || !n148_dec || !n148_planes || !n148_merge ||
        !jpeg_enc || !jpeg_dec) return EXIT_FAILURE;

    unsigned char *n148_data = NULL, *jpeg_data = NULL;
    long n148_file_size = 0;
    unsigned long jpeg_size = 0;
    HuffSpec specs[HUFFMAN_TABLE_COUNT];
    Image n148_image = {0};
    unsigned char *jpeg_pixels = NULL;
    int jpeg_width = 0, jpeg_height = 0;
    const int warmups = reps < 5 ? 1 : 5;

    /* Alternate which codec runs first on every trial.  This keeps turbo
       frequency, cache temperature and slow thermal drift from favouring
       whichever implementation happened to be measured first. */
    for (int i = -warmups; i < reps; i++) {
        int n148_first = ((i + warmups) & 1) == 0;
        for (int pass = 0; pass < 2; pass++) {
            if ((pass == 0) == n148_first) {
                unsigned char *data = NULL;
                long size = 0;
                HuffSpec trial_specs[HUFFMAN_TABLE_COUNT];
                if (pin_jpeg && !apply_affinity(&n148_affinity)) {
                    fprintf(stderr, "could not restore N.148i CPU affinity\n");
                    return EXIT_FAILURE;
                }
                double start = now_ms();
                int ok = n148_encode(&original, quality, chroma, &data, &size,
                                     trial_specs);
                double elapsed = now_ms() - start;
                if (!ok) return EXIT_FAILURE;
                if (i >= 0) n148_enc[i] = elapsed;
                free(n148_data);
                n148_data = data;
                n148_file_size = size;
                memcpy(specs, trial_specs, sizeof(specs));
            } else {
                unsigned char *data = NULL;
                unsigned long size = 0;
                if (pin_jpeg && !apply_affinity(&jpeg_affinity)) {
                    fprintf(stderr, "could not pin JPEG CPU affinity\n");
                    return EXIT_FAILURE;
                }
                double start = now_ms();
                int ok = jpeg_encode(&original, quality, chroma, &data, &size);
                double elapsed = now_ms() - start;
                if (!ok) return EXIT_FAILURE;
                if (i >= 0) jpeg_enc[i] = elapsed;
                free(jpeg_data);
                jpeg_data = data;
                jpeg_size = size;
            }
        }
    }

    /* encode_image returns entropy bytes separately from the complete file. */
    long n148_payload_size = n148_file_size - 21 - huffman_tables_size(specs);
    for (int i = -warmups; i < reps; i++) {
        int n148_first = ((i + warmups) & 1) == 0;
        for (int pass = 0; pass < 2; pass++) {
            if ((pass == 0) == n148_first) {
                Image decoded = {0};
                double plane_ms, merge_ms;
                free_image(&n148_image);
                if (pin_jpeg && !apply_affinity(&n148_affinity)) {
                    fprintf(stderr, "could not restore N.148i CPU affinity\n");
                    return EXIT_FAILURE;
                }
                double start = now_ms();
                int ok = n148_decode(n148_data, n148_payload_size,
                                     original.width, original.height, quality,
                                     chroma, specs, &decoded,
                                     &plane_ms, &merge_ms);
                double elapsed = now_ms() - start;
                if (!ok) return EXIT_FAILURE;
                if (i >= 0) {
                    n148_dec[i] = elapsed;
                    n148_planes[i] = plane_ms;
                    n148_merge[i] = merge_ms;
                }
                n148_image = decoded;
            } else {
                unsigned char *pixels = NULL;
                int width = 0, height = 0;
                free(jpeg_pixels);
                jpeg_pixels = NULL;
                if (pin_jpeg && !apply_affinity(&jpeg_affinity)) {
                    fprintf(stderr, "could not pin JPEG CPU affinity\n");
                    return EXIT_FAILURE;
                }
                double start = now_ms();
                int ok = jpeg_decode(jpeg_data, jpeg_size, &pixels,
                                     &width, &height);
                double elapsed = now_ms() - start;
                if (!ok || width != original.width || height != original.height)
                    return EXIT_FAILURE;
                if (i >= 0) jpeg_dec[i] = elapsed;
                jpeg_pixels = pixels;
                jpeg_width = width;
                jpeg_height = height;
            }
        }
    }

    if (pin_jpeg && !apply_affinity(&n148_affinity)) {
        fprintf(stderr, "could not restore process CPU affinity\n");
        return EXIT_FAILURE;
    }

    double ne = median(n148_enc, reps), nd = median(n148_dec, reps);
    double np = median(n148_planes, reps), nm = median(n148_merge, reps);
    double je = median(jpeg_enc, reps), jd = median(jpeg_dec, reps);
    double npsnr = image_psnr(&original, n148_image.pixels);
    double jpsnr = image_psnr(&original, jpeg_pixels);

    printf("%s %dx%d q=%d chroma=%d threads=%d reps=%d\n",
           path, original.width, original.height, quality, chroma,
           n148_thread_count(), reps);
    printf("N148i  enc %8.3f ms  dec %8.3f ms  %8ld B  PSNR %7.3f dB\n",
           ne, nd, n148_file_size, npsnr);
    printf("JPEG   enc %8.3f ms  dec %8.3f ms  %8lu B  PSNR %7.3f dB\n",
           je, jd, jpeg_size, jpsnr);
    printf("N/J    enc %8.3fx    dec %8.3fx    %8.3fx size\n",
           ne / je, nd / jd, (double) n148_file_size / jpeg_size);
    printf("N148i decode stages: planes %8.3f ms  merge %8.3f ms  other %8.3f ms\n",
           np, nm, nd - np - nm);

    (void) jpeg_width;
    (void) jpeg_height;
    free(n148_enc); free(n148_dec); free(n148_planes); free(n148_merge);
    free(jpeg_enc); free(jpeg_dec);
    free(n148_data); free(jpeg_data); free(jpeg_pixels);
    free_image(&n148_image);
    free_image(&original);
    return EXIT_SUCCESS;
}

A pasta src: os arquivos novos da V2

Agora vêm os 34 arquivos que nasceram na V2, na ordem dos artigos da Fase 5.

Os arquivos terminados em .inc não são compilados sozinhos: outro arquivo inclui cada um deles no meio do próprio código, mas fique tranquilo que eu vou indicar qual é...

Os arquivos novos da pasta src formam o caminho que uma imagem percorre na V2, da leitura do PPM até o arquivo comprimido.

Novos na pasta src: o rANS e os contextos

src/rans.h

O rans.h é a interface do rANS, o codificador que estudamos no artigo 27, com os modelos adaptativos do artigo 29.

O arquivo completo tem 107 linhas:

/*
 * N.148i range Asymmetric Numeral System coder
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#ifndef N148_RANS_H
#define N148_RANS_H

#include <stddef.h>
#include <stdint.h>

#define N148_RANS_SCALE_BITS 12
#define N148_RANS_TOTAL (1u << N148_RANS_SCALE_BITS)
#define N148_RANS_LOWER_BOUND (1u << 23)
#define N148_RANS_ALPHABET_SIZE 256

typedef struct {
    uint16_t frequency[N148_RANS_ALPHABET_SIZE];
    uint16_t cumulative[N148_RANS_ALPHABET_SIZE + 1];
    uint8_t symbol_for_slot[N148_RANS_TOTAL];
    /* Fixed-model decode reads both values after resolving a slot. */
    uint32_t decode_pair[N148_RANS_ALPHABET_SIZE];
    uint16_t used_symbols;
} N148RansModel;

/* Mutable fixed-total model used by format 7. A Fenwick tree keeps prefix
   sums and inverse lookup deterministic without rebuilding the 4096-entry
   table after every symbol. */
typedef struct {
    uint16_t frequency[N148_RANS_ALPHABET_SIZE];
    uint16_t fenwick[N148_RANS_ALPHABET_SIZE + 1];
    uint8_t active_symbols[N148_RANS_ALPHABET_SIZE];
    uint16_t used_symbols;
} N148RansAdaptiveModel;

typedef struct {
    const N148RansModel *model;
    const N148RansModel *model_base;
    N148RansAdaptiveModel *adaptive_models;
    size_t adaptive_model_count;
    size_t adaptive_model_limit;
    const uint8_t *adaptive_model_flags;
    size_t adaptive_model_flag_count;
    uint8_t adaptation_rate_shift;
    const uint8_t *next;
    const uint8_t *end;
    uint32_t state;
    int valid;
} N148RansDecoder;

/* Normalize nonzero counts to exactly 2^12 without dropping used symbols. */
int n148_rans_build_model(const uint32_t counts[N148_RANS_ALPHABET_SIZE],
                          N148RansModel *model);

/* Rebuild cumulative and decoding tables from serialized frequencies. */
int n148_rans_prepare_model(N148RansModel *model);

/* The caller owns the returned stream and releases it with free(). */
int n148_rans_encode(const uint8_t *symbols, size_t symbol_count,
                     const N148RansModel *model,
                     uint8_t **stream, size_t *stream_size);

/* Each symbol may select a model known independently by the decoder. */
int n148_rans_encode_mixed(const uint8_t *symbols,
                           const uint8_t *model_indexes,
                           size_t symbol_count,
                           const N148RansModel *models, size_t model_count,
                           uint8_t **stream, size_t *stream_size);

/* Format 7 adaptive coding. Models start from the serialized static image
   histograms and move toward each observed symbol by 1 / 2^rate_shift while
   retaining a frequency of at least one for every initially used symbol. */
int n148_rans_encode_mixed_adaptive(
    const uint8_t *symbols, const uint8_t *model_indexes,
    size_t symbol_count, const N148RansModel *models, size_t model_count,
    size_t adaptive_model_limit, const uint8_t *adaptive_model_flags,
    size_t adaptive_model_flag_count, uint8_t adaptation_rate_shift,
    uint8_t **stream, size_t *stream_size, uint64_t *final_model_hash);

int n148_rans_adaptive_model_init(N148RansAdaptiveModel *adaptive,
                                  const N148RansModel *initial);
int n148_rans_adaptive_model_update(N148RansAdaptiveModel *adaptive,
                                    uint8_t symbol,
                                    uint8_t adaptation_rate_shift);
uint64_t n148_rans_adaptive_models_hash(
    const N148RansAdaptiveModel *models, size_t model_count);

int n148_rans_decoder_init(N148RansDecoder *decoder,
                           const N148RansModel *model,
                           const uint8_t *stream, size_t stream_size);
int n148_rans_decoder_init_mixed(N148RansDecoder *decoder,
                                 const uint8_t *stream, size_t stream_size);
int n148_rans_decoder_init_mixed_adaptive(
    N148RansDecoder *decoder, const uint8_t *stream, size_t stream_size,
    const N148RansModel *initial_models,
    N148RansAdaptiveModel *adaptive_models, size_t model_count,
    size_t adaptive_model_limit, const uint8_t *adaptive_model_flags,
    size_t adaptive_model_flag_count, uint8_t adaptation_rate_shift);
int n148_rans_decode_symbol(N148RansDecoder *decoder, uint8_t *symbol);
int n148_rans_decode_symbol_with_model(N148RansDecoder *decoder,
                                       const N148RansModel *model,
                                       uint8_t *symbol);
int n148_rans_decoder_finished(const N148RansDecoder *decoder);

#endif

src/rans.c

O rans.c implementa o rANS com probabilidades de 12 bits de precisão, a codificação e a decodificação dos símbolos e a atualização das probabilidades adaptativas.

O arquivo completo tem 633 linhas:

/*
 * N.148i range Asymmetric Numeral System coder
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 *
 * This is a deliberately compact educational byte-rANS implementation. The
 * encoder visits symbols in reverse and grows its output backwards; decoding
 * then consumes both symbols and renormalization bytes in forward order.
 */

#include "rans.h"

#include <limits.h>
#ifdef N148_RANS_DIAGNOSTICS
#include <stdio.h>
#endif
#include <stdlib.h>
#include <string.h>

#define RANS_LOWER_BOUND N148_RANS_LOWER_BOUND

typedef struct {
    uint16_t frequency;
    uint16_t cumulative;
} N148RansSymbolState;

static int adaptive_model_enabled(size_t model,
                                  size_t adaptive_model_limit,
                                  const uint8_t *flags,
                                  size_t flag_count) {
    if (flags)
        return model < flag_count &&
            ((flags[model >> 3] >> (model & 7u)) & 1u) != 0;
    return model < adaptive_model_limit;
}

static uint32_t read_u32_le(const uint8_t *source) {
    return (uint32_t) source[0] |
        ((uint32_t) source[1] << 8) |
        ((uint32_t) source[2] << 16) |
        ((uint32_t) source[3] << 24);
}

static void write_u32_le(uint8_t *destination, uint32_t value) {
    destination[0] = (uint8_t) value;
    destination[1] = (uint8_t) (value >> 8);
    destination[2] = (uint8_t) (value >> 16);
    destination[3] = (uint8_t) (value >> 24);
}

static uint32_t adaptive_prefix_sum(const N148RansAdaptiveModel *model,
                                    unsigned int symbol) {
    uint32_t sum = 0;
    for (unsigned int index = symbol; index; index &= index - 1u)
        sum += model->fenwick[index];
    return sum;
}

static void adaptive_add(N148RansAdaptiveModel *model,
                         unsigned int symbol, int delta) {
    for (unsigned int index = symbol + 1u;
         index <= N148_RANS_ALPHABET_SIZE;
         index += index & (0u - index)) {
        model->fenwick[index] = (uint16_t)(
            (int) model->fenwick[index] + delta);
    }
}

static inline int bonus_higher(uint8_t left, uint8_t right,
                               const uint32_t remainder[256]) {
    /* The original scan gives the smaller symbol the first tied bonus. */
    return remainder[left] > remainder[right] ||
        (remainder[left] == remainder[right] && left < right);
}

static inline void bonus_heap_sift_down(uint8_t heap[256], int count,
                                        int start,
                                        const uint32_t remainder[256]) {
    int parent = start;
    uint8_t value = heap[parent];
    while (2 * parent + 1 < count) {
        int child = 2 * parent + 1;
        if (child + 1 < count &&
            bonus_higher(heap[child + 1], heap[child], remainder))
            child++;
        if (!bonus_higher(heap[child], value, remainder)) break;
        heap[parent] = heap[child];
        parent = child;
    }
    heap[parent] = value;
}

int n148_rans_adaptive_model_init(N148RansAdaptiveModel *adaptive,
                                  const N148RansModel *initial) {
    if (!adaptive || !initial || initial->used_symbols == 0) return 0;
    memset(adaptive, 0, sizeof(*adaptive));
    uint32_t total = 0;
    for (unsigned int symbol = 0; symbol < N148_RANS_ALPHABET_SIZE;
         symbol++) {
        uint16_t frequency = initial->frequency[symbol];
        adaptive->frequency[symbol] = frequency;
        if (frequency) {
            adaptive->active_symbols[adaptive->used_symbols] = (uint8_t) symbol;
            adaptive->used_symbols++;
            adaptive_add(adaptive, symbol, frequency);
            total += frequency;
        }
    }
    return adaptive->used_symbols == initial->used_symbols &&
        total == N148_RANS_TOTAL;
}

int n148_rans_adaptive_model_update(N148RansAdaptiveModel *model,
                                    uint8_t observed,
                                    uint8_t adaptation_rate_shift) {
    if (!model || adaptation_rate_shift == 0 ||
        adaptation_rate_shift > 15 || model->frequency[observed] == 0 ||
        model->used_symbols == 0) return 0;
    if (model->used_symbols == 1) return 1;

    /* The total stays fixed, and every active symbol retains one count.
       Excluding the observed symbol leaves exactly this many transferable
       counts in the other active symbols. */
    uint32_t available = N148_RANS_TOTAL - model->used_symbols -
        ((uint32_t) model->frequency[observed] - 1u);
    uint32_t transfer = available >> adaptation_rate_shift;
    if (transfer == 0) return 1;
    /* If available = transfer * 2^shift + remainder, division of
       transfer * capacity needs only a shift and one signed correction. */
    uint32_t divisor_remainder =
        available - (transfer << adaptation_rate_shift);

    uint16_t deduction[N148_RANS_ALPHABET_SIZE] = {0};
    uint32_t remainder[N148_RANS_ALPHABET_SIZE] = {0};
    uint8_t bonus_heap[N148_RANS_ALPHABET_SIZE];
    uint32_t assigned = 0;
    for (unsigned int active = 0; active < model->used_symbols; active++) {
        unsigned int symbol = model->active_symbols[active];
        if (symbol == observed || model->frequency[symbol] <= 1) continue;
        uint32_t capacity = (uint32_t) model->frequency[symbol] - 1u;
        uint32_t base = capacity >> adaptation_rate_shift;
        int32_t excess = (int32_t)(
            transfer * (capacity - (base << adaptation_rate_shift))) -
            (int32_t)(base * divisor_remainder);
        deduction[symbol] = (uint16_t)(excess < 0 ? base - 1u : base);
        remainder[symbol] =
            (uint32_t)(excess < 0 ? excess + (int32_t) available : excess);
        assigned += deduction[symbol];
    }
    int bonus_count = 0;
    for (unsigned int active = 0; active < model->used_symbols; active++) {
        unsigned int symbol = model->active_symbols[active];
        if (symbol != observed &&
            deduction[symbol] < (uint32_t) model->frequency[symbol] - 1u)
            bonus_heap[bonus_count++] = (uint8_t) symbol;
    }
    for (int parent = bonus_count / 2 - 1; parent >= 0; parent--)
        bonus_heap_sift_down(bonus_heap, bonus_count, parent, remainder);
    while (assigned < transfer) {
        if (bonus_count == 0) return 0;
        unsigned int best = bonus_heap[0];
        deduction[best]++;
        assigned++;
        bonus_count--;
        if (bonus_count) {
            bonus_heap[0] = bonus_heap[bonus_count];
            bonus_heap_sift_down(bonus_heap, bonus_count, 0, remainder);
        }
    }

    for (unsigned int active = 0; active < model->used_symbols; active++) {
        unsigned int symbol = model->active_symbols[active];
        if (!deduction[symbol]) continue;
        model->frequency[symbol] = (uint16_t)(
            model->frequency[symbol] - deduction[symbol]);
        adaptive_add(model, symbol, -(int) deduction[symbol]);
    }
    model->frequency[observed] = (uint16_t)(
        model->frequency[observed] + transfer);
    adaptive_add(model, observed, (int) transfer);
    return adaptive_prefix_sum(model, N148_RANS_ALPHABET_SIZE) ==
        N148_RANS_TOTAL;
}

uint64_t n148_rans_adaptive_models_hash(
    const N148RansAdaptiveModel *models, size_t model_count) {
    uint64_t hash = 14695981039346656037ull;
    if (!models && model_count) return 0;
    for (size_t model = 0; model < model_count; model++) {
        for (unsigned int symbol = 0; symbol < N148_RANS_ALPHABET_SIZE;
             symbol++) {
            uint16_t frequency = models[model].frequency[symbol];
            hash ^= (uint8_t) frequency;
            hash *= 1099511628211ull;
            hash ^= (uint8_t)(frequency >> 8);
            hash *= 1099511628211ull;
        }
    }
    return hash;
}

int n148_rans_prepare_model(N148RansModel *model) {
    if (!model) return 0;
    uint32_t cumulative = 0;
    uint16_t used = 0;
    for (int symbol = 0; symbol < N148_RANS_ALPHABET_SIZE; symbol++) {
        model->cumulative[symbol] = (uint16_t) cumulative;
        uint32_t frequency = model->frequency[symbol];
        model->decode_pair[symbol] =
            (cumulative << 16) | frequency;
        if (frequency) {
            if (frequency > N148_RANS_TOTAL ||
                cumulative + frequency > N148_RANS_TOTAL) {
                return 0;
            }
            memset(model->symbol_for_slot + cumulative, symbol, frequency);
            cumulative += frequency;
            used++;
        }
    }
    model->cumulative[N148_RANS_ALPHABET_SIZE] = (uint16_t) cumulative;
    model->used_symbols = used;
    return used > 0 && cumulative == N148_RANS_TOTAL;
}

int n148_rans_build_model(const uint32_t counts[N148_RANS_ALPHABET_SIZE],
                          N148RansModel *model) {
    if (!counts || !model) return 0;
    memset(model, 0, sizeof(*model));

    uint64_t total = 0;
    int used = 0;
    for (int symbol = 0; symbol < N148_RANS_ALPHABET_SIZE; symbol++) {
        total += counts[symbol];
        if (counts[symbol]) used++;
    }
    if (total == 0 || used > (int) N148_RANS_TOTAL) return 0;

    uint32_t normalized_total = 0;
    for (int symbol = 0; symbol < N148_RANS_ALPHABET_SIZE; symbol++) {
        if (!counts[symbol]) continue;
        uint64_t scaled = (uint64_t) counts[symbol] * N148_RANS_TOTAL;
        uint32_t frequency = (uint32_t) (scaled / total);
        if (frequency == 0) frequency = 1;
        model->frequency[symbol] = (uint16_t) frequency;
        normalized_total += frequency;
    }

    /* Largest-remainder balancing expressed with integers. The score is the
       ideal scaled count minus the currently assigned count, so adding one
       lowers it by exactly `total` and subtracting one raises it likewise. */
    while (normalized_total < N148_RANS_TOTAL) {
        int best = -1;
        int64_t best_score = INT64_MIN;
        for (int symbol = 0; symbol < N148_RANS_ALPHABET_SIZE; symbol++) {
            if (!counts[symbol]) continue;
            int64_t score =
                (int64_t)((uint64_t) counts[symbol] * N148_RANS_TOTAL) -
                (int64_t)((uint64_t) model->frequency[symbol] * total);
            if (score > best_score) {
                best_score = score;
                best = symbol;
            }
        }
        if (best < 0 || model->frequency[best] == UINT16_MAX) return 0;
        model->frequency[best]++;
        normalized_total++;
    }
    while (normalized_total > N148_RANS_TOTAL) {
        int best = -1;
        int64_t best_score = INT64_MAX;
        for (int symbol = 0; symbol < N148_RANS_ALPHABET_SIZE; symbol++) {
            if (model->frequency[symbol] <= 1) continue;
            int64_t score =
                (int64_t)((uint64_t) counts[symbol] * N148_RANS_TOTAL) -
                (int64_t)((uint64_t) model->frequency[symbol] * total);
            if (score < best_score) {
                best_score = score;
                best = symbol;
            }
        }
        if (best < 0) return 0;
        model->frequency[best]--;
        normalized_total--;
    }
    return n148_rans_prepare_model(model);
}

int n148_rans_encode_mixed(const uint8_t *symbols,
                           const uint8_t *model_indexes,
                           size_t symbol_count,
                           const N148RansModel *models, size_t model_count,
                           uint8_t **stream, size_t *stream_size) {
    if ((!symbols && symbol_count) || (!model_indexes && symbol_count) ||
        !models || model_count == 0 || model_count > 256 || !stream ||
        !stream_size) {
        return 0;
    }
    *stream = NULL;
    *stream_size = 0;
    if (symbol_count > (SIZE_MAX - 16) / 2) return 0;
    size_t capacity = symbol_count * 2 + 16;
    uint8_t *storage = (uint8_t *) malloc(capacity);
    if (!storage) return 0;
    uint8_t *begin = storage;
    uint8_t *cursor = storage + capacity;
    uint32_t state = RANS_LOWER_BOUND;

    for (size_t remaining = symbol_count; remaining > 0; remaining--) {
        uint8_t symbol = symbols[remaining - 1];
        uint8_t model_index = model_indexes[remaining - 1];
        if (model_index >= model_count ||
            models[model_index].used_symbols == 0) {
            free(storage);
            return 0;
        }
        const N148RansModel *model = &models[model_index];
        uint32_t frequency = model->frequency[symbol];
        uint32_t cumulative = model->cumulative[symbol];
        if (frequency == 0) {
            free(storage);
            return 0;
        }
        uint32_t threshold =
            ((RANS_LOWER_BOUND >> N148_RANS_SCALE_BITS) << 8) * frequency;
        while (state >= threshold) {
            if (cursor == begin) {
                free(storage);
                return 0;
            }
            *--cursor = (uint8_t) state;
            state >>= 8;
        }
        state = (state / frequency) * N148_RANS_TOTAL +
            state % frequency + cumulative;
    }
    if ((size_t)(cursor - begin) < 4) {
        free(storage);
        return 0;
    }
    cursor -= 4;
    write_u32_le(cursor, state);
    size_t used = (size_t)((storage + capacity) - cursor);
    memmove(storage, cursor, used);
    uint8_t *compact = (uint8_t *) realloc(storage, used);
    if (compact) storage = compact;
    *stream = storage;
    *stream_size = used;
    return 1;
}

int n148_rans_encode_mixed_adaptive(
    const uint8_t *symbols, const uint8_t *model_indexes,
    size_t symbol_count, const N148RansModel *models, size_t model_count,
    size_t adaptive_model_limit, const uint8_t *adaptive_model_flags,
    size_t adaptive_model_flag_count, uint8_t adaptation_rate_shift,
    uint8_t **stream, size_t *stream_size, uint64_t *final_model_hash) {
    if ((!symbols && symbol_count) || (!model_indexes && symbol_count) ||
        !models || model_count == 0 || model_count > 256 || !stream ||
        !stream_size || adaptive_model_limit > model_count ||
        (adaptive_model_flags &&
         adaptive_model_flag_count > model_count) ||
        adaptation_rate_shift == 0 ||
        adaptation_rate_shift > 15 ||
        symbol_count > SIZE_MAX / sizeof(N148RansSymbolState)) return 0;
    *stream = NULL;
    *stream_size = 0;
    if (final_model_hash) *final_model_hash = 0;
    uint64_t computed_model_hash = 0;

    N148RansAdaptiveModel *adaptive = (N148RansAdaptiveModel *) calloc(
        model_count, sizeof(*adaptive));
    N148RansSymbolState *states = symbol_count ?
        (N148RansSymbolState *) malloc(symbol_count * sizeof(*states)) : NULL;
    if (!adaptive || (symbol_count && !states)) {
        free(adaptive);
        free(states);
        return 0;
    }
    for (size_t model = 0; model < model_count; model++) {
        if (!n148_rans_adaptive_model_init(&adaptive[model],
                                           &models[model])) {
#ifdef N148_RANS_DIAGNOSTICS
            fprintf(stderr, "adaptive init failed for model %zu\n", model);
#endif
            free(adaptive);
            free(states);
            return 0;
        }
    }
    for (size_t index = 0; index < symbol_count; index++) {
        uint8_t model_index = model_indexes[index];
        uint8_t symbol = symbols[index];
        if (model_index >= model_count ||
            adaptive[model_index].frequency[symbol] == 0) {
#ifdef N148_RANS_DIAGNOSTICS
            fprintf(stderr, "adaptive missing symbol at %zu model %u symbol %u\n",
                    index, model_index, symbol);
#endif
            free(adaptive);
            free(states);
            return 0;
        }
        states[index].frequency = adaptive[model_index].frequency[symbol];
        states[index].cumulative = (uint16_t) adaptive_prefix_sum(
            &adaptive[model_index], symbol);
        if (adaptive_model_enabled(
                model_index, adaptive_model_limit, adaptive_model_flags,
                adaptive_model_flag_count) &&
            !n148_rans_adaptive_model_update(
                &adaptive[model_index], symbol, adaptation_rate_shift)) {
#ifdef N148_RANS_DIAGNOSTICS
            fprintf(stderr, "adaptive update failed at %zu model %u symbol %u\n",
                    index, model_index, symbol);
#endif
            free(adaptive);
            free(states);
            return 0;
        }
    }
    if (final_model_hash)
        computed_model_hash = n148_rans_adaptive_models_hash(
            adaptive, model_count);
    free(adaptive);

    if (symbol_count > (SIZE_MAX - 16) / 4) {
        free(states);
        return 0;
    }
    size_t capacity = symbol_count * 4 + 16;
    uint8_t *storage = (uint8_t *) malloc(capacity);
    if (!storage) {
        free(states);
        return 0;
    }
    uint8_t *begin = storage;
    uint8_t *cursor = storage + capacity;
    uint32_t state = RANS_LOWER_BOUND;
    for (size_t remaining = symbol_count; remaining > 0; remaining--) {
        uint32_t frequency = states[remaining - 1].frequency;
        uint32_t cumulative = states[remaining - 1].cumulative;
        uint32_t threshold =
            ((RANS_LOWER_BOUND >> N148_RANS_SCALE_BITS) << 8) * frequency;
        while (state >= threshold) {
            if (cursor == begin) {
                free(storage);
                free(states);
                return 0;
            }
            *--cursor = (uint8_t) state;
            state >>= 8;
        }
        state = (state / frequency) * N148_RANS_TOTAL +
            state % frequency + cumulative;
    }
    free(states);
    if ((size_t)(cursor - begin) < 4) {
        free(storage);
        return 0;
    }
    cursor -= 4;
    write_u32_le(cursor, state);
    size_t used = (size_t)((storage + capacity) - cursor);
    memmove(storage, cursor, used);
    uint8_t *compact = (uint8_t *) realloc(storage, used);
    if (compact) storage = compact;
    *stream = storage;
    *stream_size = used;
    if (final_model_hash) *final_model_hash = computed_model_hash;
    return 1;
}

int n148_rans_encode(const uint8_t *symbols, size_t symbol_count,
                     const N148RansModel *model,
                     uint8_t **stream, size_t *stream_size) {
    if ((!symbols && symbol_count) || !model) return 0;
    uint8_t *indexes = NULL;
    if (symbol_count) {
        indexes = (uint8_t *) calloc(symbol_count, 1);
        if (!indexes) return 0;
    }
    int result = n148_rans_encode_mixed(
        symbols, indexes, symbol_count, model, 1, stream, stream_size);
    free(indexes);
    return result;
}

int n148_rans_decoder_init(N148RansDecoder *decoder,
                           const N148RansModel *model,
                           const uint8_t *stream, size_t stream_size) {
    if (!decoder || !model || !stream || stream_size < 4 ||
        model->used_symbols == 0) {
        return 0;
    }
    memset(decoder, 0, sizeof(*decoder));
    decoder->model = model;
    decoder->state = read_u32_le(stream);
    decoder->next = stream + 4;
    decoder->end = stream + stream_size;
    decoder->valid = decoder->state >= RANS_LOWER_BOUND;
    return decoder->valid;
}

int n148_rans_decoder_init_mixed(N148RansDecoder *decoder,
                                 const uint8_t *stream, size_t stream_size) {
    if (!decoder || !stream || stream_size < 4) return 0;
    memset(decoder, 0, sizeof(*decoder));
    decoder->model = NULL;
    decoder->state = read_u32_le(stream);
    decoder->next = stream + 4;
    decoder->end = stream + stream_size;
    decoder->valid = decoder->state >= RANS_LOWER_BOUND;
    return decoder->valid;
}

int n148_rans_decoder_init_mixed_adaptive(
    N148RansDecoder *decoder, const uint8_t *stream, size_t stream_size,
    const N148RansModel *initial_models,
    N148RansAdaptiveModel *adaptive_models, size_t model_count,
    size_t adaptive_model_limit, const uint8_t *adaptive_model_flags,
    size_t adaptive_model_flag_count, uint8_t adaptation_rate_shift) {
    if (!decoder || !initial_models || !adaptive_models ||
        model_count == 0 || model_count > 256 ||
        adaptive_model_limit > model_count ||
        (adaptive_model_flags && adaptive_model_flag_count > model_count) ||
        adaptation_rate_shift == 0 || adaptation_rate_shift > 15 ||
        !n148_rans_decoder_init_mixed(decoder, stream, stream_size)) return 0;
    for (size_t model = 0; model < model_count; model++) {
        if (!n148_rans_adaptive_model_init(&adaptive_models[model],
                                           &initial_models[model])) {
            decoder->valid = 0;
            return 0;
        }
    }
    decoder->model_base = initial_models;
    decoder->adaptive_models = adaptive_models;
    decoder->adaptive_model_count = model_count;
    decoder->adaptive_model_limit = adaptive_model_limit;
    decoder->adaptive_model_flags = adaptive_model_flags;
    decoder->adaptive_model_flag_count = adaptive_model_flag_count;
    decoder->adaptation_rate_shift = adaptation_rate_shift;
    return 1;
}

static int decode_symbol_adaptive(N148RansDecoder *decoder,
                                  N148RansAdaptiveModel *model,
                                  int update_model, uint8_t *symbol) {
    uint32_t slot = decoder->state & (N148_RANS_TOTAL - 1u);
    unsigned int index = 0;
    uint32_t cumulative = 0;
    for (unsigned int step = N148_RANS_ALPHABET_SIZE; step; step >>= 1) {
        unsigned int next = index + step;
        if (next <= N148_RANS_ALPHABET_SIZE &&
            cumulative + model->fenwick[next] <= slot) {
            index = next;
            cumulative += model->fenwick[next];
        }
    }
    if (index >= N148_RANS_ALPHABET_SIZE ||
        model->frequency[index] == 0) {
        decoder->valid = 0;
        return 0;
    }
    uint32_t frequency = model->frequency[index];
    decoder->state = frequency *
        (decoder->state >> N148_RANS_SCALE_BITS) + slot - cumulative;
    while (decoder->state < RANS_LOWER_BOUND) {
        if (decoder->next == decoder->end) {
            decoder->valid = 0;
            return 0;
        }
        decoder->state = (decoder->state << 8) | *decoder->next++;
    }
    *symbol = (uint8_t) index;
    if (update_model && !n148_rans_adaptive_model_update(
            model, *symbol, decoder->adaptation_rate_shift)) {
        decoder->valid = 0;
        return 0;
    }
    return 1;
}

int n148_rans_decode_symbol_with_model(N148RansDecoder *decoder,
                                       const N148RansModel *model,
                                       uint8_t *symbol) {
    if (!decoder || !model || !symbol || !decoder->valid ||
        model->used_symbols == 0) return 0;
    if (decoder->adaptive_models) {
        if (!decoder->model_base || model < decoder->model_base ||
            model >= decoder->model_base + decoder->adaptive_model_count) {
            decoder->valid = 0;
            return 0;
        }
        size_t model_index = (size_t)(model - decoder->model_base);
        return decode_symbol_adaptive(
            decoder, &decoder->adaptive_models[model_index],
            adaptive_model_enabled(
                model_index, decoder->adaptive_model_limit,
                decoder->adaptive_model_flags,
                decoder->adaptive_model_flag_count), symbol);
    }
    uint32_t slot = decoder->state & (N148_RANS_TOTAL - 1u);
    uint8_t decoded = model->symbol_for_slot[slot];
    uint32_t frequency = model->frequency[decoded];
    uint32_t cumulative = model->cumulative[decoded];
    if (frequency == 0 || slot < cumulative || slot >= cumulative + frequency) {
        decoder->valid = 0;
        return 0;
    }
    decoder->state = frequency *
        (decoder->state >> N148_RANS_SCALE_BITS) + slot - cumulative;
    while (decoder->state < RANS_LOWER_BOUND) {
        if (decoder->next == decoder->end) {
            decoder->valid = 0;
            return 0;
        }
        decoder->state = (decoder->state << 8) | *decoder->next++;
    }
    *symbol = decoded;
    return 1;
}

int n148_rans_decode_symbol(N148RansDecoder *decoder, uint8_t *symbol) {
    if (!decoder || !decoder->model) return 0;
    return n148_rans_decode_symbol_with_model(
        decoder, decoder->model, symbol);
}

int n148_rans_decoder_finished(const N148RansDecoder *decoder) {
    return decoder && decoder->valid && decoder->next == decoder->end &&
        decoder->state == RANS_LOWER_BOUND;
}

src/entropy_payload.h

O entropy_payload.h é a interface do codificador de entropia dos formatos 2 e 3, que organiza os símbolos em contextos, como no artigo 28.

O arquivo completo tem 80 linhas:

/*
 * N.148i entropy-payload interface
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#ifndef N148_ENTROPY_PAYLOAD_H
#define N148_ENTROPY_PAYLOAD_H

#include <stddef.h>
#include <stdint.h>

#include "adaptive_quant.h"
#include "encoder.h"
#include "ppm.h"
#include "variable_transform.h"

#define N148_EXTENDED_HEADER_SIZE 32u
#define N148_FEATURE_RANS (1u << 0)
#define N148_FEATURE_CONTEXT (1u << 1)
#define N148_FEATURE_INTRA (1u << 2)
#define N148_FEATURE_PERCEPTUAL_COLOR (1u << 3)
#define N148_FEATURE_ADAPTIVE_QUANT (1u << 4)
#define N148_FEATURE_VARIABLE_TRANSFORM (1u << 5)
#define N148_FEATURE_RDO (1u << 6)
#define N148_FEATURE_LOOP_FILTER (1u << 7)
#define N148_FORMAT_2_SUPPORTED_FEATURES \
    (N148_FEATURE_RANS | N148_FEATURE_CONTEXT | N148_FEATURE_INTRA | \
     N148_FEATURE_PERCEPTUAL_COLOR | N148_FEATURE_ADAPTIVE_QUANT | \
     N148_FEATURE_VARIABLE_TRANSFORM | N148_FEATURE_RDO | \
     N148_FEATURE_LOOP_FILTER)

typedef struct {
    uint64_t hash;
    uint32_t symbol_count;
} N148ContextTrace;

typedef struct {
    uint8_t *values;
    size_t count;
} N148PredictionModes;

typedef struct {
    uint8_t *metadata;
    size_t metadata_size;
    uint8_t *payload;
    size_t payload_size;
} N148EncodedPayload;

int n148_encode_format_2(Plane *y, Plane *cb, Plane *cr, int quality,
                   uint32_t features, int effort, N148EncodedPayload *output);

int n148_decode_format_2(const uint8_t *metadata, size_t metadata_size,
                   const uint8_t *payload, size_t payload_size,
                   int width, int height, int quality, int chroma,
                   uint32_t features,
                   Plane *y, Plane *cb, Plane *cr);

/* Validation hook: recover the exact zig-zag quantized coefficient arrays. */
int n148_decode_format_2_coefficients(const uint8_t *metadata, size_t metadata_size,
                                const uint8_t *payload, size_t payload_size,
                                int width, int height, int chroma,
                                uint32_t features,
                                N148CoeffPlane coefficients[3],
                                N148ContextTrace *trace,
                                N148PredictionModes *prediction,
                                N148AdaptiveMap *adaptive_map,
                                N148TransformMap *transform_map);

/* Validation hook: derive the encoder-side model sequence from coefficients. */
int n148_trace_base_contexts(const N148CoeffPlane coefficients[3],
                           int width, int height, int chroma,
                           uint32_t features,
                           N148ContextTrace *trace);

void n148_encoded_payload_release(N148EncodedPayload *encoded);
void n148_prediction_modes_release(N148PredictionModes *prediction);

#endif

src/entropy_payload.c

O entropy_payload.c é o segundo maior arquivo da V2, com o codificador e o decodificador completos dos formatos 2 e 3: os contextos dos coeficientes, os modos de predição e os fluxos entregues ao rANS.

O arquivo completo tem 4.826 linhas:

/*
 * N.148i entropy payload
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 *
 * rANS changes only representation. Context modeling selects probability models
 * from previously decoded coefficients. Blocks are still transformed and
 * quantized by the exact format-1 path, and amplitude bits remain raw, which keeps
 * the syntax easy to inspect and proves entropy coding cannot alter values.
 */

#include "entropy_payload.h"

#include <limits.h>
#include <math.h>
#ifdef N148_RANS_DIAGNOSTICS
#include <stdio.h>
#endif
#include <stdlib.h>
#include <string.h>

#include "adaptive_quant.h"
#include "decoder.h"
#include "header.h"
#include "huffman.h"
#include "intra.h"
#include "loop_filter.h"
#include "rans.h"
#include "segmentation.h"
#include "variable_transform.h"
#include "predictive_codec.h"
#include "directional_intra.h"

#define ENTROPY_METADATA_REVISION_BASE 1u
#define ENTROPY_METADATA_REVISION_RICH 2u
#define PAYLOAD_REVISION_ENTROPY 1u
#define PAYLOAD_REVISION_INTRA 2u
#define PAYLOAD_REVISION_ADAPTIVE_QUANT 3u
#define PAYLOAD_REVISION_VARIABLE_TRANSFORM 4u
#define PAYLOAD_REVISION_DIRECTIONAL_INTRA 5u
#define PAYLOAD_REVISION_JOINT_CHROMA 6u
#define PAYLOAD_REVISION_SEGMENTATION 7u
#define PAYLOAD_REVISION_JOINT_SEGMENTATION 8u
#define PAYLOAD_REVISION_ADAPTIVE_FILTER 9u
#define PAYLOAD_REVISION_JOINT_ADAPTIVE_FILTER 10u
#define PAYLOAD_REVISION_VARIABLE_LUMA 11u
#define PAYLOAD_REVISION_RICH_CONTEXT 12u
#define INTRA_MODE_CODER_RANS 1u
#define ADAPTIVE_MAP_CODER_RANS 1u
#define TRANSFORM_MAP_CODER_RANS 2u
#define PARTITION_MAP_CODER_RANS 4u
#define SEGMENT_MAP_CODER_RANS 8u
#define ENTROPY_CODER_HUFFMAN 0u
#define ENTROPY_CODER_RANS 1u
#define BASE_COEFFICIENT_MODEL_COUNT 4
#define CONTEXT_DC_BUCKETS 3
#define CONTEXT_BANDS 4
#define CONTEXT_ACTIVITY_BUCKETS 2
#define CONTEXT_DC_MODELS (2 * CONTEXT_DC_BUCKETS)
#define CONTEXT_AC_MODELS \
    (2 * CONTEXT_BANDS * CONTEXT_ACTIVITY_BUCKETS)
#define CONTEXT_MODEL_COUNT \
    (CONTEXT_DC_MODELS + CONTEXT_AC_MODELS)
#define BLOCK_INTRA_MODE_CONTEXTS (N148_INTRA_MODE_COUNT + 2)
#define BLOCK_INTRA_MODELS (2 * BLOCK_INTRA_MODE_CONTEXTS)
#define ADAPTIVE_MAP_MODEL_COUNT 1
#define TRANSFORM_MAP_MODEL_COUNT 1
#define DIRECTIONAL_MODE_CONTEXTS (N148_DIRECTIONAL_INTRA_MODE_COUNT + 2)
#define DIRECTIONAL_MODELS (2 * DIRECTIONAL_MODE_CONTEXTS)
#define PARTITION_MODEL_COUNT 1
#define SEGMENTATION_MODEL_COUNT 1
#define LUMA_TRANSFORM_MODEL_COUNT 1
#define RICH_LUMA_SIZE_CLASSES 3
#define RICH_POSITION_BUCKETS 5
#define RICH_ACTIVITY_BUCKETS 3
#define RICH_PREDICTION_CLASSES 2
#define RICH_LUMA_DC_MODELS \
    (RICH_LUMA_SIZE_CLASSES * CONTEXT_DC_BUCKETS * \
     RICH_PREDICTION_CLASSES)
#define RICH_LUMA_AC_MODELS \
    (RICH_LUMA_SIZE_CLASSES * RICH_POSITION_BUCKETS * \
     RICH_ACTIVITY_BUCKETS * RICH_PREDICTION_CLASSES)
#define RICH_CHROMA_DC_MODELS CONTEXT_DC_BUCKETS
#define RICH_CHROMA_AC_MODELS \
    (CONTEXT_BANDS * CONTEXT_ACTIVITY_BUCKETS)
#define RICH_CONTEXT_MODEL_COUNT \
    (RICH_LUMA_DC_MODELS + RICH_LUMA_AC_MODELS + \
     RICH_CHROMA_DC_MODELS + RICH_CHROMA_AC_MODELS)
#define RICH_ADAPTIVE_MODEL_COUNT \
    (RICH_LUMA_DC_MODELS + RICH_LUMA_AC_MODELS)
#define RICH_ADAPTIVE_MASK_SIZE \
    ((RICH_ADAPTIVE_MODEL_COUNT + 7) / 8)
#define MAX_MODEL_COUNT 256
#define PLANE_COUNT 3

enum {
    BASE_DC_LUMA_MODEL = 0,
    BASE_AC_LUMA_MODEL = 1,
    BASE_DC_CHROMA_MODEL = 2,
    BASE_AC_CHROMA_MODEL = 3,
};

#define CONTEXT_TRACE_OFFSET 14695981039346656037ull
#define CONTEXT_TRACE_PRIME 1099511628211ull

typedef struct {
    uint8_t *data;
    size_t size;
    size_t capacity;
    int valid;
} ByteWriter;

typedef struct {
    const uint8_t *data;
    size_t size;
    size_t position;
    int valid;
} ByteReader;

typedef struct {
    ByteWriter symbols;
    ByteWriter model_indexes;
    ByteWriter amplitudes;
    size_t amplitude_bits;
} TokenStream;

typedef struct {
    const uint8_t *next;
    const uint8_t *end;
    uint64_t cache;
    size_t bits_remaining;
    unsigned int cached_bits;
    int valid;
} BitReader;

typedef struct {
    ByteWriter *writer;
    size_t bit_count;
} PackedWriter;

typedef struct {
    ByteReader *reader;
    size_t bit_count;
    int valid;
} PackedReader;

static void writer_init(ByteWriter *writer) {
    memset(writer, 0, sizeof(*writer));
    writer->valid = 1;
}

static int writer_reserve(ByteWriter *writer, size_t extra) {
    if (!writer->valid || extra > SIZE_MAX - writer->size) return 0;
    size_t needed = writer->size + extra;
    if (needed <= writer->capacity) return 1;
    size_t capacity = writer->capacity ? writer->capacity : 256;
    while (capacity < needed) {
        if (capacity > SIZE_MAX / 2) {
            capacity = needed;
            break;
        }
        capacity *= 2;
    }
    uint8_t *grown = (uint8_t *) realloc(writer->data, capacity);
    if (!grown) {
        writer->valid = 0;
        return 0;
    }
    writer->data = grown;
    writer->capacity = capacity;
    return 1;
}

static int writer_bytes(ByteWriter *writer, const void *data, size_t size) {
    if (!writer_reserve(writer, size)) return 0;
    if (size) memcpy(writer->data + writer->size, data, size);
    writer->size += size;
    return 1;
}

static int writer_u8(ByteWriter *writer, uint8_t value) {
    return writer_bytes(writer, &value, 1);
}

static int writer_u32(ByteWriter *writer, uint32_t value) {
    uint8_t bytes[4] = {
        (uint8_t) value, (uint8_t)(value >> 8),
        (uint8_t)(value >> 16), (uint8_t)(value >> 24),
    };
    return writer_bytes(writer, bytes, sizeof(bytes));
}

static int writer_varuint(ByteWriter *writer, uint32_t value) {
    do {
        uint8_t byte = (uint8_t)(value & 0x7fu);
        value >>= 7;
        if (value) byte |= 0x80u;
        if (!writer_u8(writer, byte)) return 0;
    } while (value);
    return 1;
}

static uint8_t *writer_detach(ByteWriter *writer, size_t *size) {
    if (!writer->valid) return NULL;
    uint8_t *data = writer->data;
    *size = writer->size;
    writer->data = NULL;
    writer->size = 0;
    writer->capacity = 0;
    return data;
}

static void writer_release(ByteWriter *writer) {
    free(writer->data);
    memset(writer, 0, sizeof(*writer));
}

static void reader_init(ByteReader *reader, const uint8_t *data, size_t size) {
    reader->data = data;
    reader->size = size;
    reader->position = 0;
    reader->valid = data != NULL || size == 0;
}

static const uint8_t *reader_bytes(ByteReader *reader, size_t size) {
    if (!reader->valid || reader->position > reader->size ||
        size > reader->size - reader->position) {
        reader->valid = 0;
        return NULL;
    }
    const uint8_t *result = reader->data + reader->position;
    reader->position += size;
    return result;
}

static uint8_t reader_u8(ByteReader *reader) {
    const uint8_t *bytes = reader_bytes(reader, 1);
    return bytes ? bytes[0] : 0;
}

static uint32_t reader_u32(ByteReader *reader) {
    const uint8_t *bytes = reader_bytes(reader, 4);
    return bytes ? (uint32_t) bytes[0] |
        ((uint32_t) bytes[1] << 8) |
        ((uint32_t) bytes[2] << 16) |
        ((uint32_t) bytes[3] << 24) : 0;
}

static uint32_t reader_varuint(ByteReader *reader) {
    uint32_t value = 0;
    for (int shift = 0; shift <= 28; shift += 7) {
        uint8_t byte = reader_u8(reader);
        if (!reader->valid) return 0;
        if (shift == 28 && (byte & 0xf0u)) {
            reader->valid = 0;
            return 0;
        }
        value |= (uint32_t)(byte & 0x7fu) << shift;
        if (!(byte & 0x80u)) {
            if (shift > 0 && (byte & 0x7fu) == 0) reader->valid = 0;
            return reader->valid ? value : 0;
        }
    }
    reader->valid = 0;
    return 0;
}

static int reader_finished(const ByteReader *reader) {
    return reader->valid && reader->position == reader->size;
}

static void packed_writer_init(PackedWriter *packed, ByteWriter *writer) {
    packed->writer = writer;
    packed->bit_count = 0;
}

static int packed_writer_bits(PackedWriter *packed, uint32_t value, int count) {
    for (int bit = count - 1; bit >= 0; bit--) {
        size_t offset = packed->bit_count & 7u;
        if (offset == 0 && !writer_u8(packed->writer, 0)) return 0;
        if (value & (1u << bit))
            packed->writer->data[packed->writer->size - 1] |=
                (uint8_t)(1u << (7u - offset));
        packed->bit_count++;
    }
    return 1;
}

static void packed_reader_init(PackedReader *packed, ByteReader *reader) {
    packed->reader = reader;
    packed->bit_count = 0;
    packed->valid = reader->valid;
}

static uint32_t packed_reader_bits(PackedReader *packed, int count) {
    uint32_t value = 0;
    if (!packed->valid || count < 0 || count > 16) {
        packed->valid = 0;
        return 0;
    }
    for (int bit = 0; bit < count; bit++) {
        size_t byte = packed->reader->position + (packed->bit_count >> 3);
        if (byte >= packed->reader->size) {
            packed->valid = 0;
            return 0;
        }
        value = (value << 1) |
            ((packed->reader->data[byte] >>
              (7u - (packed->bit_count & 7u))) & 1u);
        packed->bit_count++;
    }
    return value;
}

static int packed_reader_finish(PackedReader *packed) {
    if (!packed->valid) {
        packed->reader->valid = 0;
        return 0;
    }
    size_t bytes = (packed->bit_count + 7u) / 8u;
    if (packed->reader->position > packed->reader->size ||
        bytes > packed->reader->size - packed->reader->position) {
        packed->reader->valid = 0;
        return 0;
    }
    if ((packed->bit_count & 7u) && bytes) {
        uint8_t padding =
            (uint8_t)((1u << (8u - (packed->bit_count & 7u))) - 1u);
        if (packed->reader->data[packed->reader->position + bytes - 1] &
            padding) {
            packed->reader->valid = 0;
            return 0;
        }
    }
    packed->reader->position += bytes;
    return 1;
}

static int coefficient_category(int value) {
    unsigned int magnitude = value < 0 ?
        0u - (unsigned int)value : (unsigned int)value;
#if defined(__GNUC__) || defined(__clang__)
    return magnitude ? (int)(sizeof(magnitude) * CHAR_BIT) -
        __builtin_clz(magnitude) : 0;
#else
    int bits = 0;
    while (magnitude) { magnitude >>= 1; bits++; }
    return bits;
#endif
}

static uint32_t coefficient_amplitude(int value, int bits) {
    if (bits == 0) return 0;
    uint32_t mask = (1u << bits) - 1u;
    return value < 0 ? ((uint32_t)(value - 1) & mask) :
        ((uint32_t) value & mask);
}

static int token_bits(TokenStream *tokens, uint32_t value, int count) {
    if (count < 0 || count > 16) return 0;
    /* Insert the next byte fragment in stream order, including when the
       previous coefficient left a partially filled byte. */
    while (count) {
        unsigned offset = (unsigned)(tokens->amplitude_bits & 7u);
        if (offset == 0 && !writer_u8(&tokens->amplitudes, 0)) return 0;
        int chunk = 8 - (int)offset;
        if (chunk > count) chunk = count;
        unsigned bits = (value >> (count - chunk)) & ((1u << chunk) - 1u);
        tokens->amplitudes.data[tokens->amplitudes.size - 1] |=
            (uint8_t)(bits << (8 - offset - chunk));
        tokens->amplitude_bits += (unsigned)chunk;
        count -= chunk;
    }
    return 1;
}

static int token_symbol(TokenStream *tokens, int model, uint8_t symbol) {
    return writer_u8(&tokens->symbols, symbol) &&
        writer_u8(&tokens->model_indexes, (uint8_t) model);
}

static int context_dc_bucket(int previous_category) {
    if (previous_category == 0) return 0;
    return previous_category <= 3 ? 1 : 2;
}

static int context_band(int position) {
    return (position >= 6) + (position >= 15) + (position >= 28);
}

static int neighbor_is_active(const N148CoeffPlane *coefficients,
                              long block, int blocks_x, int position) {
    if (block % blocks_x != 0) {
        int value = coefficients->coefficients[(block - 1) * 64 + position];
        if (value <= -4 || value >= 4) return 1;
    }
    if (block >= blocks_x) {
        int value = coefficients->coefficients[
            (block - blocks_x) * 64 + position];
        if (value <= -4 || value >= 4) return 1;
    }
    return 0;
}

static int context_dc_model(int plane_class, int previous_category) {
    return plane_class * CONTEXT_DC_BUCKETS +
        context_dc_bucket(previous_category);
}

static int context_ac_model(const N148CoeffPlane *coefficients,
                            long block, int blocks_x, int plane_class,
                            int position, int previous_category) {
    int active = previous_category >= 3 ||
        neighbor_is_active(coefficients, block, blocks_x, position);
    return CONTEXT_DC_MODELS +
        ((plane_class * CONTEXT_BANDS + context_band(position)) *
         CONTEXT_ACTIVITY_BUCKETS) + active;
}

static void context_trace_init(N148ContextTrace *trace) {
    if (!trace) return;
    trace->hash = CONTEXT_TRACE_OFFSET;
    trace->symbol_count = 0;
}

static int context_trace_add(N148ContextTrace *trace, int model) {
    if (!trace) return 1;
    if (trace->symbol_count == UINT32_MAX || model < 0 || model > UINT8_MAX)
        return 0;
    trace->hash ^= (uint8_t) model;
    trace->hash *= CONTEXT_TRACE_PRIME;
    trace->symbol_count++;
    return 1;
}

static int tokenize_plane(const N148CoeffPlane *coefficients,
                          int blocks_x, int plane_class, int use_context,
                          int absolute_dc,
                          TokenStream *tokens) {
    int previous_dc = 0;
    int previous_dc_category = 0;
    int base_dc_model = plane_class ? BASE_DC_CHROMA_MODEL : BASE_DC_LUMA_MODEL;
    int base_ac_model = plane_class ? BASE_AC_CHROMA_MODEL : BASE_AC_LUMA_MODEL;

    for (long block = 0; block < coefficients->count; block++) {
        const short *values = coefficients->coefficients + block * 64;
        int difference = absolute_dc ? values[0] : values[0] - previous_dc;
        previous_dc = values[0];
        int bits = coefficient_category(difference);
        int model = use_context ?
            context_dc_model(plane_class, previous_dc_category) :
            base_dc_model;
        if (bits > 16 || !token_symbol(tokens, model, (uint8_t) bits) ||
            !token_bits(tokens, coefficient_amplitude(difference, bits), bits)) {
            return 0;
        }
        previous_dc_category = bits;

        int next_position = 1;
        int previous_ac_category = 0;
        unsigned long long mask = coefficients->nonzero_masks[block] & ~1ull;
        while (mask) {
            int position = 0;
#if defined(__GNUC__) || defined(__clang__)
            position = __builtin_ctzll(mask);
#else
            unsigned long long probe = mask;
            while (!(probe & 1u)) { position++; probe >>= 1; }
#endif
            int run = position - next_position;
            while (run > 15) {
                model = use_context ? context_ac_model(
                    coefficients, block, blocks_x, plane_class,
                    next_position, previous_ac_category) : base_ac_model;
                if (!token_symbol(tokens, model, 0xf0u)) return 0;
                next_position += 16;
                previous_ac_category = 0;
                run -= 16;
            }
            int value = values[position];
            bits = coefficient_category(value);
            model = use_context ? context_ac_model(
                coefficients, block, blocks_x, plane_class,
                next_position, previous_ac_category) : base_ac_model;
            if (bits < 1 || bits > 15 ||
                !token_symbol(tokens, model,
                              (uint8_t)((run << 4) | bits)) ||
                !token_bits(tokens, coefficient_amplitude(value, bits), bits)) {
                return 0;
            }
            next_position = position + 1;
            previous_ac_category = bits;
            mask &= mask - 1;
        }
        if (next_position < 64) {
            model = use_context ? context_ac_model(
                coefficients, block, blocks_x, plane_class,
                next_position, previous_ac_category) : base_ac_model;
            if (!token_symbol(tokens, model, 0)) return 0;
        }
    }
    return tokens->symbols.valid && tokens->model_indexes.valid &&
        tokens->amplitudes.valid &&
        tokens->symbols.size == tokens->model_indexes.size;
}

/* A split directional-intra cell contains four independent 4x4 transforms. Encoding their
   DC and end-of-block events independently is both the truthful syntax and a
   materially better rate model than pretending the packed values form one
   64-coefficient transform. */
static int directional_context_ac_model(const N148CoeffPlane *coefficients,
                               long block, int blocks_x, int plane_class,
                               int packed_position, int local_position,
                               int previous_category) {
    int active = previous_category >= 3 || neighbor_is_active(
        coefficients, block, blocks_x, packed_position);
    return CONTEXT_DC_MODELS +
        ((plane_class * CONTEXT_BANDS + context_band(local_position)) *
         CONTEXT_ACTIVITY_BUCKETS) + active;
}

static int tokenize_directional_coefficient_unit(
    const N148CoeffPlane *coefficients, long block, int blocks_x,
    int plane_class, int use_context, int packed_offset, int length,
    int *previous_dc_category, TokenStream *tokens) {
    const short *values = coefficients->coefficients + block * 64 +
        packed_offset;
    int base_dc_model = plane_class ? BASE_DC_CHROMA_MODEL : BASE_DC_LUMA_MODEL;
    int base_ac_model = plane_class ? BASE_AC_CHROMA_MODEL : BASE_AC_LUMA_MODEL;
    int bits = coefficient_category(values[0]);
    int model = use_context ?
        context_dc_model(plane_class, *previous_dc_category) : base_dc_model;
    if (bits > 16 || !token_symbol(tokens, model, (uint8_t) bits) ||
        !token_bits(tokens, coefficient_amplitude(values[0], bits), bits))
        return 0;
    *previous_dc_category = bits;

    int next_position = 1;
    int previous_ac_category = 0;
    for (int position = 1; position < length; position++) {
        int value = values[position];
        if (value == 0) continue;
        int run = position - next_position;
        while (run > 15) {
            model = use_context ? directional_context_ac_model(
                coefficients, block, blocks_x, plane_class,
                packed_offset + next_position, next_position,
                previous_ac_category) : base_ac_model;
            if (!token_symbol(tokens, model, 0xf0u)) return 0;
            next_position += 16;
            previous_ac_category = 0;
            run -= 16;
        }
        bits = coefficient_category(value);
        model = use_context ? directional_context_ac_model(
            coefficients, block, blocks_x, plane_class,
            packed_offset + next_position, next_position,
            previous_ac_category) : base_ac_model;
        if (bits < 1 || bits > 15 ||
            !token_symbol(tokens, model, (uint8_t)((run << 4) | bits)) ||
            !token_bits(tokens, coefficient_amplitude(value, bits), bits))
            return 0;
        next_position = position + 1;
        previous_ac_category = bits;
    }
    if (next_position < length) {
        model = use_context ? directional_context_ac_model(
            coefficients, block, blocks_x, plane_class,
            packed_offset + next_position, next_position,
            previous_ac_category) : base_ac_model;
        if (!token_symbol(tokens, model, 0)) return 0;
    }
    return 1;
}

static int tokenize_directional_coefficient_plane(
    const N148CoeffPlane *coefficients, const uint8_t *splits,
    int blocks_x, int plane_class, int use_context, TokenStream *tokens) {
    if (!coefficients || !coefficients->coefficients || !splits ||
        blocks_x <= 0 || !tokens) return 0;
    int previous_dc_category = 0;
    for (long block = 0; block < coefficients->count; block++) {
        int parts = splits[block] ? N148_INTRA_MODE_SLOTS_PER_BLOCK : 1;
        int length = splits[block] ? 16 : 64;
        for (int part = 0; part < parts; part++) {
            if (!tokenize_directional_coefficient_unit(
                    coefficients, block, blocks_x, plane_class, use_context,
                    part * 16, length, &previous_dc_category, tokens))
                return 0;
        }
    }
    return tokens->symbols.valid && tokens->model_indexes.valid &&
        tokens->amplitudes.valid &&
        tokens->symbols.size == tokens->model_indexes.size;
}

static int large_transform_ac_model(int plane_class, int local_position,
                             int previous_category) {
    int active = previous_category >= 3;
    return CONTEXT_DC_MODELS +
        ((plane_class * CONTEXT_BANDS + context_band(local_position)) *
         CONTEXT_ACTIVITY_BUCKETS) + active;
}

static int tokenize_large_transform_coefficient_unit(
    const short *values, int length, int plane_class, int use_context,
    int *previous_dc_category, TokenStream *tokens) {
    if (!values || (length != 16 * 16 && length != 32 * 32)) return 0;
    int base_dc_model = plane_class ? BASE_DC_CHROMA_MODEL : BASE_DC_LUMA_MODEL;
    int base_ac_model = plane_class ? BASE_AC_CHROMA_MODEL : BASE_AC_LUMA_MODEL;
    int bits = coefficient_category(values[0]);
    int model = use_context ?
        context_dc_model(plane_class, *previous_dc_category) : base_dc_model;
    if (bits > 16 || !token_symbol(tokens, model, (uint8_t) bits) ||
        !token_bits(tokens, coefficient_amplitude(values[0], bits), bits))
        return 0;
    *previous_dc_category = bits;
    int next_position = 1;
    int previous_ac_category = 0;
    for (int position = 1; position < length; position++) {
        int value = values[position];
        if (value == 0) continue;
        int run = position - next_position;
        while (run > 15) {
            model = use_context ? large_transform_ac_model(
                plane_class, next_position, previous_ac_category) :
                base_ac_model;
            if (!token_symbol(tokens, model, 0xf0u)) return 0;
            next_position += 16;
            previous_ac_category = 0;
            run -= 16;
        }
        bits = coefficient_category(value);
        model = use_context ? large_transform_ac_model(
            plane_class, next_position, previous_ac_category) :
            base_ac_model;
        if (bits < 1 || bits > 15 ||
            !token_symbol(tokens, model, (uint8_t)((run << 4) | bits)) ||
            !token_bits(tokens, coefficient_amplitude(value, bits), bits))
            return 0;
        next_position = position + 1;
        previous_ac_category = bits;
    }
    if (next_position < length) {
        model = use_context ? large_transform_ac_model(
            plane_class, next_position, previous_ac_category) :
            base_ac_model;
        if (!token_symbol(tokens, model, 0)) return 0;
    }
    return 1;
}

static int tokenize_variable_luma_coefficient_plane(
    const N148CoeffPlane *coefficients, const uint8_t *splits,
    int blocks_x, int blocks_y, int use_context,
    const N148TransformMap *transform_map, TokenStream *tokens) {
    if (!coefficients || !coefficients->coefficients || !splits ||
        blocks_x <= 0 || blocks_y <= 0 || !tokens ||
        coefficients->count != (long) blocks_x * blocks_y ||
        !n148_luma_transform_map_validate_extended(transform_map, 1))
        return 0;
    int previous_dc_category = 0;
    for (int macro_y = 0; macro_y < transform_map->rows[0]; macro_y++) {
        for (int macro_x = 0; macro_x < transform_map->columns[0];
             macro_x++) {
            size_t transform_index = (size_t) macro_y *
                (size_t) transform_map->columns[0] + (size_t) macro_x;
            int first_x = macro_x * 2;
            int first_y = macro_y * 2;
            if (n148_luma_transform_dct32_member(
                    transform_map, macro_x, macro_y)) {
                if (!n148_luma_transform_dct32_origin(
                        transform_map, macro_x, macro_y)) continue;
                short sequence[32 * 32];
                for (int cell = 0; cell < 16; cell++) {
                    int block_x = first_x + (cell & 3);
                    int block_y = first_y + (cell >> 2);
                    if (block_x >= blocks_x || block_y >= blocks_y)
                        return 0;
                    long block = (long) block_y * blocks_x + block_x;
                    if (splits[block]) return 0;
                    memcpy(sequence + cell * 64,
                           coefficients->coefficients + block * 64,
                           64 * sizeof(*sequence));
                }
                if (!tokenize_large_transform_coefficient_unit(
                        sequence, 32 * 32, 0, use_context,
                        &previous_dc_category, tokens)) return 0;
                continue;
            }
            if (transform_map->strategies[transform_index] ==
                N148_TRANSFORM_DCT16) {
                short sequence[16 * 16];
                for (int cell = 0; cell < 4; cell++) {
                    int block_x = first_x + (cell & 1);
                    int block_y = first_y + (cell >> 1);
                    if (block_x >= blocks_x || block_y >= blocks_y)
                        return 0;
                    long block = (long) block_y * blocks_x + block_x;
                    if (splits[block]) return 0;
                    memcpy(sequence + cell * 64,
                           coefficients->coefficients + block * 64,
                           64 * sizeof(*sequence));
                }
                if (!tokenize_large_transform_coefficient_unit(
                        sequence, 16 * 16, 0, use_context,
                        &previous_dc_category, tokens)) return 0;
                continue;
            }
            for (int cell_y = 0; cell_y < 2; cell_y++) {
                int block_y = first_y + cell_y;
                if (block_y >= blocks_y) continue;
                for (int cell_x = 0; cell_x < 2; cell_x++) {
                    int block_x = first_x + cell_x;
                    if (block_x >= blocks_x) continue;
                    long block = (long) block_y * blocks_x + block_x;
                    int parts = splits[block] ?
                        N148_INTRA_MODE_SLOTS_PER_BLOCK : 1;
                    int length = splits[block] ? 16 : 64;
                    for (int part = 0; part < parts; part++)
                        if (!tokenize_directional_coefficient_unit(
                                coefficients, block, blocks_x, 0,
                                use_context, part * 16, length,
                                &previous_dc_category, tokens)) return 0;
                }
            }
        }
    }
    return tokens->symbols.valid && tokens->model_indexes.valid &&
        tokens->amplitudes.valid &&
        tokens->symbols.size == tokens->model_indexes.size;
}

static int rich_position_bucket(int position) {
    if (position <= 3) return position - 1;
    if (position < 15) return 3;
    return 4;
}

static int rich_prediction_class(int mode) {
    return n148_intra_base_mode(mode) == N148_DIRECTIONAL_INTRA_DC ? 0 : 1;
}

static int rich_luma_dc_model(int size_class, int prediction_mode,
                                 int previous_category) {
    int prediction_class = rich_prediction_class(prediction_mode);
    return (size_class * RICH_PREDICTION_CLASSES + prediction_class) *
        CONTEXT_DC_BUCKETS + context_dc_bucket(previous_category);
}

static int rich_activity_bucket(const N148CoeffPlane *coefficients,
                                   long block, int blocks_x,
                                   int packed_position,
                                   int previous_magnitude) {
    int magnitude_sum = previous_magnitude;
    if (coefficients && packed_position >= 0 && packed_position < 64) {
        if (block % blocks_x != 0) {
            int value = coefficients->coefficients[
                (block - 1) * 64 + packed_position];
            magnitude_sum += value < 0 ? -value : value;
        }
        if (block >= blocks_x) {
            int value = coefficients->coefficients[
                (block - blocks_x) * 64 + packed_position];
            magnitude_sum += value < 0 ? -value : value;
        }
    }
    if (magnitude_sum == 0) return 0;
    return magnitude_sum <= 3 ? 1 : 2;
}

static int rich_luma_ac_model(int size_class, int prediction_mode,
                                 int position, int activity_bucket) {
    int prediction_class = rich_prediction_class(prediction_mode);
    return RICH_LUMA_DC_MODELS +
        ((((size_class * RICH_PREDICTION_CLASSES + prediction_class) *
            RICH_POSITION_BUCKETS) +
           rich_position_bucket(position)) *
          RICH_ACTIVITY_BUCKETS) + activity_bucket;
}

static int rich_chroma_dc_model(int previous_category) {
    return RICH_LUMA_DC_MODELS + RICH_LUMA_AC_MODELS +
        context_dc_bucket(previous_category);
}

static int rich_chroma_ac_model(const N148CoeffPlane *coefficients,
                                   long block, int blocks_x,
                                   int packed_position, int local_position,
                                   int previous_category) {
    int active = previous_category >= 3 || neighbor_is_active(
        coefficients, block, blocks_x, packed_position);
    return RICH_LUMA_DC_MODELS + RICH_LUMA_AC_MODELS +
        RICH_CHROMA_DC_MODELS +
        context_band(local_position) * CONTEXT_ACTIVITY_BUCKETS + active;
}

static int tokenize_rich_coefficient_unit(
    const N148CoeffPlane *coefficients, long block, int blocks_x,
    int plane_class, int packed_offset, int length, int size_class,
    int prediction_mode, int *previous_dc_category, TokenStream *tokens) {
    const short *values = coefficients->coefficients + block * 64 +
        packed_offset;
    int bits = coefficient_category(values[0]);
    int model = plane_class ?
        rich_chroma_dc_model(*previous_dc_category) :
        rich_luma_dc_model(
            size_class, prediction_mode, *previous_dc_category);
    if (bits > 16 || !token_symbol(tokens, model, (uint8_t) bits) ||
        !token_bits(tokens, coefficient_amplitude(values[0], bits), bits))
        return 0;
    *previous_dc_category = bits;

    int next_position = 1;
    int previous_ac_category = 0;
    int previous_magnitude = 0;
    for (int position = 1; position < length; position++) {
        int value = values[position];
        if (value == 0) continue;
        int run = position - next_position;
        while (run > 15) {
            if (plane_class) {
                model = rich_chroma_ac_model(
                    coefficients, block, blocks_x,
                    packed_offset + next_position, next_position,
                    previous_ac_category);
            } else {
                int activity = rich_activity_bucket(
                    coefficients, block, blocks_x,
                    packed_offset + next_position, previous_magnitude);
                model = rich_luma_ac_model(
                    size_class, prediction_mode, next_position, activity);
            }
            if (!token_symbol(tokens, model, 0xf0u)) return 0;
            next_position += 16;
            previous_ac_category = 0;
            previous_magnitude = 0;
            run -= 16;
        }
        bits = coefficient_category(value);
        if (plane_class) {
            model = rich_chroma_ac_model(
                coefficients, block, blocks_x,
                packed_offset + next_position, next_position,
                previous_ac_category);
        } else {
            int activity = rich_activity_bucket(
                coefficients, block, blocks_x,
                packed_offset + next_position, previous_magnitude);
            model = rich_luma_ac_model(
                size_class, prediction_mode, next_position, activity);
        }
        if (bits < 1 || bits > 15 ||
            !token_symbol(tokens, model, (uint8_t)((run << 4) | bits)) ||
            !token_bits(tokens, coefficient_amplitude(value, bits), bits))
            return 0;
        next_position = position + 1;
        previous_ac_category = bits;
        previous_magnitude = value < 0 ? -value : value;
    }
    if (next_position < length) {
        if (plane_class) {
            model = rich_chroma_ac_model(
                coefficients, block, blocks_x,
                packed_offset + next_position, next_position,
                previous_ac_category);
        } else {
            int activity = rich_activity_bucket(
                coefficients, block, blocks_x,
                packed_offset + next_position, previous_magnitude);
            model = rich_luma_ac_model(
                size_class, prediction_mode, next_position, activity);
        }
        if (!token_symbol(tokens, model, 0)) return 0;
    }
    return 1;
}

static int tokenize_rich_large_coefficient_unit(
    const short *values, int length, int size_class, int prediction_mode,
    int *previous_dc_category, TokenStream *tokens) {
    if (!values || (length != 16 * 16 && length != 32 * 32)) return 0;
    int bits = coefficient_category(values[0]);
    int model = rich_luma_dc_model(
        size_class, prediction_mode, *previous_dc_category);
    if (bits > 16 || !token_symbol(tokens, model, (uint8_t) bits) ||
        !token_bits(tokens, coefficient_amplitude(values[0], bits), bits))
        return 0;
    *previous_dc_category = bits;
    int next_position = 1;
    int previous_magnitude = 0;
    for (int position = 1; position < length; position++) {
        int value = values[position];
        if (value == 0) continue;
        int run = position - next_position;
        while (run > 15) {
            int activity = previous_magnitude == 0 ? 0 :
                (previous_magnitude <= 3 ? 1 : 2);
            model = rich_luma_ac_model(
                size_class, prediction_mode, next_position, activity);
            if (!token_symbol(tokens, model, 0xf0u)) return 0;
            next_position += 16;
            previous_magnitude = 0;
            run -= 16;
        }
        bits = coefficient_category(value);
        int activity = previous_magnitude == 0 ? 0 :
            (previous_magnitude <= 3 ? 1 : 2);
        model = rich_luma_ac_model(
            size_class, prediction_mode, next_position, activity);
        if (bits < 1 || bits > 15 ||
            !token_symbol(tokens, model, (uint8_t)((run << 4) | bits)) ||
            !token_bits(tokens, coefficient_amplitude(value, bits), bits))
            return 0;
        next_position = position + 1;
        previous_magnitude = value < 0 ? -value : value;
    }
    if (next_position < length) {
        int activity = previous_magnitude == 0 ? 0 :
            (previous_magnitude <= 3 ? 1 : 2);
        model = rich_luma_ac_model(
            size_class, prediction_mode, next_position, activity);
        if (!token_symbol(tokens, model, 0)) return 0;
    }
    return 1;
}

static int tokenize_rich_coefficient_plane(
    const N148CoeffPlane *coefficients, const uint8_t *splits,
    const uint8_t *modes, int blocks_x, int plane_class,
    TokenStream *tokens) {
    if (!coefficients || !coefficients->coefficients || !splits || !modes ||
        blocks_x <= 0 || !tokens) return 0;
    int previous_dc_category = 0;
    for (long block = 0; block < coefficients->count; block++) {
        int parts = splits[block] ? N148_INTRA_MODE_SLOTS_PER_BLOCK : 1;
        int length = splits[block] ? 16 : 64;
        int size_class = splits[block] ? 0 : 1;
        for (int part = 0; part < parts; part++) {
            int mode = modes[block * N148_INTRA_MODE_SLOTS_PER_BLOCK + part];
            if (!tokenize_rich_coefficient_unit(
                    coefficients, block, blocks_x, plane_class,
                    part * 16, length, size_class, mode,
                    &previous_dc_category, tokens)) return 0;
        }
    }
    return tokens->symbols.valid && tokens->model_indexes.valid &&
        tokens->amplitudes.valid &&
        tokens->symbols.size == tokens->model_indexes.size;
}

static int tokenize_rich_luma_coefficient_plane(
    const N148CoeffPlane *coefficients, const uint8_t *splits,
    const uint8_t *modes, int blocks_x, int blocks_y,
    const N148TransformMap *transform_map, TokenStream *tokens) {
    if (!coefficients || !coefficients->coefficients || !splits || !modes ||
        blocks_x <= 0 || blocks_y <= 0 || !tokens ||
        coefficients->count != (long) blocks_x * blocks_y ||
        !n148_luma_transform_map_validate_extended(transform_map, 1))
        return 0;
    int previous_dc_category = 0;
    for (int macro_y = 0; macro_y < transform_map->rows[0]; macro_y++) {
        for (int macro_x = 0; macro_x < transform_map->columns[0];
             macro_x++) {
            size_t transform_index = (size_t) macro_y *
                (size_t) transform_map->columns[0] + (size_t) macro_x;
            int first_x = macro_x * 2;
            int first_y = macro_y * 2;
            long first_block = (long) first_y * blocks_x + first_x;
            int mode = modes[first_block * N148_INTRA_MODE_SLOTS_PER_BLOCK];
            if (n148_luma_transform_dct32_member(
                    transform_map, macro_x, macro_y)) {
                if (!n148_luma_transform_dct32_origin(
                        transform_map, macro_x, macro_y)) continue;
                short sequence[32 * 32];
                for (int cell = 0; cell < 16; cell++) {
                    int block_x = first_x + (cell & 3);
                    int block_y = first_y + (cell >> 2);
                    if (block_x >= blocks_x || block_y >= blocks_y)
                        return 0;
                    long block = (long) block_y * blocks_x + block_x;
                    if (splits[block]) return 0;
                    memcpy(sequence + cell * 64,
                           coefficients->coefficients + block * 64,
                           64 * sizeof(*sequence));
                }
                if (!tokenize_rich_large_coefficient_unit(
                        sequence, 32 * 32, 2, mode,
                        &previous_dc_category, tokens)) return 0;
                continue;
            }
            if (transform_map->strategies[transform_index] ==
                N148_TRANSFORM_DCT16) {
                short sequence[16 * 16];
                for (int cell = 0; cell < 4; cell++) {
                    int block_x = first_x + (cell & 1);
                    int block_y = first_y + (cell >> 1);
                    if (block_x >= blocks_x || block_y >= blocks_y)
                        return 0;
                    long block = (long) block_y * blocks_x + block_x;
                    if (splits[block]) return 0;
                    memcpy(sequence + cell * 64,
                           coefficients->coefficients + block * 64,
                           64 * sizeof(*sequence));
                }
                if (!tokenize_rich_large_coefficient_unit(
                        sequence, 16 * 16, 2, mode,
                        &previous_dc_category, tokens)) return 0;
                continue;
            }
            for (int cell_y = 0; cell_y < 2; cell_y++) {
                int block_y = first_y + cell_y;
                if (block_y >= blocks_y) continue;
                for (int cell_x = 0; cell_x < 2; cell_x++) {
                    int block_x = first_x + cell_x;
                    if (block_x >= blocks_x) continue;
                    long block = (long) block_y * blocks_x + block_x;
                    int parts = splits[block] ?
                        N148_INTRA_MODE_SLOTS_PER_BLOCK : 1;
                    int length = splits[block] ? 16 : 64;
                    int size_class = splits[block] ? 0 : 1;
                    for (int part = 0; part < parts; part++) {
                        mode = modes[block *
                            N148_INTRA_MODE_SLOTS_PER_BLOCK + part];
                        if (!tokenize_rich_coefficient_unit(
                                coefficients, block, blocks_x, 0,
                                part * 16, length, size_class, mode,
                                &previous_dc_category, tokens)) return 0;
                    }
                }
            }
        }
    }
    return tokens->symbols.valid && tokens->model_indexes.valid &&
        tokens->amplitudes.valid &&
        tokens->symbols.size == tokens->model_indexes.size;
}

/* Prediction modes are spatially correlated. Contexts distinguish the first
   block, agreement with one available neighbor, and disagreement between two
   available neighbors. Luma and chroma keep separate models. */
static int prediction_mode_context(const uint8_t *modes, long block,
                                   int blocks_x) {
    int has_left = block % blocks_x != 0;
    int has_top = block >= blocks_x;
    if (!has_left && !has_top) return 0;
    int left = has_left ? modes[block - 1] : -1;
    int top = has_top ? modes[block - blocks_x] : -1;
    if (has_left && has_top && left != top) return N148_INTRA_MODE_COUNT + 1;
    return 1 + (has_left ? left : top);
}

static int prediction_mode_model(int coefficient_model_count,
                                 int plane_class, const uint8_t *modes,
                                 long block, int blocks_x) {
    return coefficient_model_count + plane_class * BLOCK_INTRA_MODE_CONTEXTS +
        prediction_mode_context(modes, block, blocks_x);
}

static int tokenize_prediction_plane(const uint8_t *modes, long count,
                                     int blocks_x, int plane_class,
                                     int coefficient_model_count,
                                     TokenStream *tokens) {
    if (!modes || count <= 0 || blocks_x <= 0) return 0;
    for (long block = 0; block < count; block++) {
        int mode = modes[block];
        int model = prediction_mode_model(
            coefficient_model_count, plane_class, modes, block, blocks_x);
        if (mode < 0 || mode >= N148_INTRA_MODE_COUNT ||
            !token_symbol(tokens, model, (uint8_t) mode)) return 0;
    }
    return 1;
}

static long directional_mode_index(int block_x, int block_y, int part,
                          int blocks_x) {
    return ((long) block_y * blocks_x + block_x) *
        N148_INTRA_MODE_SLOTS_PER_BLOCK + part;
}

static int directional_virtual_mode(const uint8_t *modes, int virtual_x,
                           int virtual_y, int blocks_x) {
    int block_x = virtual_x / 2;
    int block_y = virtual_y / 2;
    int part = (virtual_y & 1) * 2 + (virtual_x & 1);
    return modes[directional_mode_index(block_x, block_y, part, blocks_x)];
}

static int directional_reference_prediction(const uint8_t *modes, long block,
                                   int part, int blocks_x,
                                   int base_mode) {
    int block_x = (int)(block % blocks_x);
    int block_y = (int)(block / blocks_x);
    int virtual_x = block_x * 2 + (part & 1);
    int virtual_y = block_y * 2 + (part >> 1);
    int has_left = virtual_x > 0;
    int has_top = virtual_y > 0;
    int left = has_left ?
        directional_virtual_mode(modes, virtual_x - 1, virtual_y, blocks_x) : 0;
    int top = has_top ?
        directional_virtual_mode(modes, virtual_x, virtual_y - 1, blocks_x) : 0;
    int left_matches = has_left &&
        n148_intra_base_mode(left) == base_mode;
    int top_matches = has_top &&
        n148_intra_base_mode(top) == base_mode;
    if (left_matches && top_matches) {
        int left_reference = n148_intra_reference_index(left);
        int top_reference = n148_intra_reference_index(top);
        return left_reference == top_reference ? left_reference : 0;
    }
    if (left_matches) return n148_intra_reference_index(left);
    if (top_matches) return n148_intra_reference_index(top);
    return 0;
}

static int directional_mode_signal_symbol(const uint8_t *modes, long block, int part,
                                 int blocks_x, int mode,
                                 int allowed_modes) {
    if (allowed_modes <= N148_DIRECTIONAL_INTRA_MODE_COUNT) return mode;
    int base_mode = n148_intra_base_mode(mode);
    int reference = n148_intra_reference_index(mode);
    int prediction = directional_reference_prediction(
        modes, block, part, blocks_x, base_mode);
    int residual = (reference + N148_INTRA_REFERENCE_COUNT - prediction) %
        N148_INTRA_REFERENCE_COUNT;
    return base_mode + N148_DIRECTIONAL_INTRA_MODE_COUNT * residual;
}

static int directional_mode_from_signal(const uint8_t *modes, long block, int part,
                               int blocks_x, int symbol,
                               int allowed_modes) {
    if (allowed_modes <= N148_DIRECTIONAL_INTRA_MODE_COUNT) return symbol;
    int base_mode = n148_intra_base_mode(symbol);
    int residual = n148_intra_reference_index(symbol);
    int prediction = directional_reference_prediction(
        modes, block, part, blocks_x, base_mode);
    int reference = (prediction + residual) %
        N148_INTRA_REFERENCE_COUNT;
    return base_mode + N148_DIRECTIONAL_INTRA_MODE_COUNT * reference;
}

/* Directional intra represents every 8x8 cell as a 2x2 virtual mode grid. An unsplit cell
   repeats its one mode in all four positions, which lets the same causal
   context code both 8x8 and 4x4 prediction without an ambiguous grammar. */
static int directional_prediction_mode_context(const uint8_t *modes, long block,
                                      int part, int blocks_x) {
    int block_x = (int)(block % blocks_x);
    int block_y = (int)(block / blocks_x);
    int virtual_x = block_x * 2 + (part & 1);
    int virtual_y = block_y * 2 + (part >> 1);
    int has_left = virtual_x > 0;
    int has_top = virtual_y > 0;
    if (!has_left && !has_top) return 0;
    int left = has_left ? n148_intra_base_mode(
        directional_virtual_mode(modes, virtual_x - 1, virtual_y, blocks_x)) : -1;
    int top = has_top ? n148_intra_base_mode(
        directional_virtual_mode(modes, virtual_x, virtual_y - 1, blocks_x)) : -1;
    if (has_left && has_top && left != top)
        return N148_DIRECTIONAL_INTRA_MODE_COUNT + 1;
    return 1 + (has_left ? left : top);
}

static int directional_prediction_mode_model(int coefficient_model_count,
                                    int plane_class, const uint8_t *modes,
                                    long block, int part, int blocks_x) {
    return coefficient_model_count + plane_class * DIRECTIONAL_MODE_CONTEXTS +
        directional_prediction_mode_context(modes, block, part, blocks_x);
}

static int tokenize_directional_prediction_plane(
    const uint8_t *modes, long block_count, int blocks_x, int plane_class,
    int coefficient_model_count, int allowed_modes, const uint8_t *splits,
    TokenStream *tokens) {
    if (!modes || block_count <= 0 || blocks_x <= 0 ||
        allowed_modes < 1 ||
        allowed_modes > N148_PACKED_INTRA_MODE_COUNT ||
        !splits)
        return 0;
    for (long block = 0; block < block_count; block++) {
        int parts = splits[block] ? N148_INTRA_MODE_SLOTS_PER_BLOCK : 1;
        int mode_limit = allowed_modes;
        for (int part = 0; part < parts; part++) {
            long index = block * N148_INTRA_MODE_SLOTS_PER_BLOCK + part;
            int mode = modes[index];
            int model = directional_prediction_mode_model(
                coefficient_model_count, plane_class, modes, block, part,
                blocks_x);
            int symbol = directional_mode_signal_symbol(
                modes, block, part, blocks_x, mode, allowed_modes);
            if (mode < 0 || mode >= mode_limit ||
                (splits[block] &&
                 n148_intra_reference_index(mode) != 0) ||
                symbol < 0 || symbol >= allowed_modes ||
                !token_symbol(tokens, model, (uint8_t) symbol)) return 0;
        }
    }
    return 1;
}

static int tokenize_variable_luma_prediction_plane(
    const uint8_t *modes, long block_count, int blocks_x, int blocks_y,
    int coefficient_model_count, int allowed_modes, const uint8_t *splits,
    const N148TransformMap *transform_map, TokenStream *tokens) {
    if (!modes || block_count != (long) blocks_x * blocks_y ||
        blocks_x <= 0 || blocks_y <= 0 || !splits || !tokens ||
        allowed_modes < 1 ||
        allowed_modes > N148_PACKED_INTRA_MODE_COUNT ||
        !n148_luma_transform_map_validate_extended(transform_map, 1))
        return 0;
    for (int macro_y = 0; macro_y < transform_map->rows[0]; macro_y++) {
        for (int macro_x = 0; macro_x < transform_map->columns[0];
             macro_x++) {
            size_t transform_index = (size_t) macro_y *
                (size_t) transform_map->columns[0] + (size_t) macro_x;
            int first_x = macro_x * 2;
            int first_y = macro_y * 2;
            if (n148_luma_transform_dct32_member(
                    transform_map, macro_x, macro_y)) {
                if (!n148_luma_transform_dct32_origin(
                        transform_map, macro_x, macro_y)) continue;
                long first_block = (long) first_y * blocks_x + first_x;
                int mode = modes[first_block *
                    N148_INTRA_MODE_SLOTS_PER_BLOCK];
                if (mode < 0 || mode >= allowed_modes) return 0;
                for (int cell = 0; cell < 16; cell++) {
                    int block_x = first_x + (cell & 3);
                    int block_y = first_y + (cell >> 2);
                    long block = (long) block_y * blocks_x + block_x;
                    if (splits[block]) return 0;
                    for (int part = 0;
                         part < N148_INTRA_MODE_SLOTS_PER_BLOCK; part++)
                        if (modes[block * N148_INTRA_MODE_SLOTS_PER_BLOCK +
                                  part] != mode) return 0;
                }
                int model = directional_prediction_mode_model(
                    coefficient_model_count, 0, modes, first_block, 0,
                    blocks_x);
                int symbol = directional_mode_signal_symbol(
                    modes, first_block, 0, blocks_x, mode, allowed_modes);
                if (symbol < 0 || symbol >= allowed_modes ||
                    !token_symbol(tokens, model, (uint8_t) symbol)) return 0;
                continue;
            }
            if (transform_map->strategies[transform_index] ==
                N148_TRANSFORM_DCT16) {
                long first_block = (long) first_y * blocks_x + first_x;
                int mode = modes[first_block *
                    N148_INTRA_MODE_SLOTS_PER_BLOCK];
                if (mode < 0 || mode >= allowed_modes) return 0;
                for (int cell = 0; cell < 4; cell++) {
                    int block_x = first_x + (cell & 1);
                    int block_y = first_y + (cell >> 1);
                    if (block_x >= blocks_x || block_y >= blocks_y)
                        return 0;
                    long block = (long) block_y * blocks_x + block_x;
                    if (splits[block]) return 0;
                    for (int part = 0;
                         part < N148_INTRA_MODE_SLOTS_PER_BLOCK; part++)
                        if (modes[block *
                                  N148_INTRA_MODE_SLOTS_PER_BLOCK + part] != mode)
                            return 0;
                }
                int model = directional_prediction_mode_model(
                    coefficient_model_count, 0, modes, first_block, 0,
                    blocks_x);
                int symbol = directional_mode_signal_symbol(
                    modes, first_block, 0, blocks_x, mode, allowed_modes);
                if (symbol < 0 || symbol >= allowed_modes ||
                    !token_symbol(tokens, model, (uint8_t) symbol)) return 0;
                continue;
            }
            for (int cell_y = 0; cell_y < 2; cell_y++) {
                int block_y = first_y + cell_y;
                if (block_y >= blocks_y) continue;
                for (int cell_x = 0; cell_x < 2; cell_x++) {
                    int block_x = first_x + cell_x;
                    if (block_x >= blocks_x) continue;
                    long block = (long) block_y * blocks_x + block_x;
                    int parts = splits[block] ?
                        N148_INTRA_MODE_SLOTS_PER_BLOCK : 1;
                    for (int part = 0; part < parts; part++) {
                        int mode = modes[block *
                            N148_INTRA_MODE_SLOTS_PER_BLOCK + part];
                        int model = directional_prediction_mode_model(
                            coefficient_model_count, 0, modes, block, part,
                            blocks_x);
                        int symbol = directional_mode_signal_symbol(
                            modes, block, part, blocks_x, mode,
                            allowed_modes);
                        if (mode < 0 || mode >= allowed_modes ||
                            (splits[block] &&
                             n148_intra_reference_index(mode) != 0) ||
                            symbol < 0 || symbol >= allowed_modes ||
                            !token_symbol(tokens, model, (uint8_t) symbol))
                            return 0;
                    }
                }
            }
        }
    }
    return 1;
}

static int tokenize_partition_map(const N148PartitionMap *map,
                                     int model, TokenStream *tokens) {
    if (!map || !map->split || model < 0 ||
        !n148_partition_map_validate(map)) return 0;
    for (size_t index = 0; index < map->count; index++) {
        uint8_t split = map->split[index];
        uint8_t prediction = n148_partition_map_predict(map, index);
        if (split > 1 || prediction > 1 ||
            !token_symbol(tokens, model, split ^ prediction)) return 0;
    }
    return 1;
}

static int tokenize_variable_luma_partition_map(
    const N148PartitionMap *map, const N148TransformMap *transform_map,
    int model, TokenStream *tokens) {
    if (!map || !map->split || !transform_map || model < 0 || !tokens ||
        !n148_partition_map_validate(map) ||
        !n148_luma_transform_map_validate_extended(transform_map, 1) ||
        map->blocks_x[0] != transform_map->blocks_x[0] ||
        map->blocks_y[0] != transform_map->blocks_y[0]) return 0;
    for (size_t index = 0; index < map->count; index++) {
        if (index < map->plane_offsets[1]) {
            size_t local = index;
            int block_x = (int)(local % (size_t) map->blocks_x[0]);
            int block_y = (int)(local / (size_t) map->blocks_x[0]);
            size_t transform_index = (size_t)(block_y / 2) *
                (size_t) transform_map->columns[0] +
                (size_t)(block_x / 2);
            if (n148_luma_transform_dct32_member(
                    transform_map, block_x / 2, block_y / 2) ||
                transform_map->strategies[transform_index] ==
                    N148_TRANSFORM_DCT16) {
                if (map->split[index]) return 0;
                continue;
            }
        }
        uint8_t split = map->split[index];
        uint8_t prediction = n148_partition_map_predict(map, index);
        if (split > 1 || prediction > 1 ||
            !token_symbol(tokens, model, split ^ prediction)) return 0;
    }
    return 1;
}

static int tokenize_segmentation_map(const N148SegmentationMap *map,
                                        int model, TokenStream *tokens) {
    if (!map || !map->levels || model < 0 ||
        !n148_segmentation_map_validate(map)) return 0;
    for (size_t index = 0; index < map->count; index++) {
        uint8_t level = map->levels[index];
        uint8_t prediction = n148_segmentation_map_predict(map, index);
        if (level >= N148_SEGMENT_COUNT || prediction >= N148_SEGMENT_COUNT)
            return 0;
        uint8_t delta = (uint8_t)(
            (level + N148_SEGMENT_COUNT - prediction) &
            (N148_SEGMENT_COUNT - 1));
        if (!token_symbol(tokens, model, delta)) return 0;
    }
    return 1;
}

static int tokenize_adaptive_map(const N148AdaptiveMap *map, int model,
                                 TokenStream *tokens) {
    if (!map || !map->levels || map->count == 0 || model < 0) return 0;
    for (size_t index = 0; index < map->count; index++) {
        uint8_t level = map->levels[index];
        uint8_t prediction = n148_adaptive_map_predict(map, index);
        if (level >= N148_AQ_LEVEL_COUNT ||
            prediction >= N148_AQ_LEVEL_COUNT) return 0;
        uint8_t delta = (uint8_t)((level + N148_AQ_LEVEL_COUNT - prediction) &
                                  (N148_AQ_LEVEL_COUNT - 1));
        if (!token_symbol(tokens, model, delta)) return 0;
    }
    return 1;
}

static int tokenize_transform_map(const N148TransformMap *map, int model,
                                  TokenStream *tokens) {
    if (!map || !map->strategies || map->count == 0 || model < 0 ||
        !n148_transform_map_validate(map)) return 0;
    for (size_t index = 0; index < map->count; index++) {
        uint8_t strategy = map->strategies[index];
        uint8_t prediction = n148_transform_map_predict(map, index);
        if (strategy >= N148_TRANSFORM_STRATEGY_COUNT ||
            prediction >= N148_TRANSFORM_STRATEGY_COUNT) return 0;
        uint8_t delta = (uint8_t)(
            (strategy + N148_TRANSFORM_STRATEGY_COUNT - prediction) %
            N148_TRANSFORM_STRATEGY_COUNT);
        if (!token_symbol(tokens, model, delta)) return 0;
    }
    return 1;
}

static int tokenize_luma_transform_map(
    const N148TransformMap *map, int model, int dct32,
    TokenStream *tokens) {
    if (!map || !map->strategies || model < 0 || !tokens ||
        !n148_luma_transform_map_validate_extended(map, dct32)) return 0;
    for (size_t index = 0; index < map->plane_offsets[1]; index++) {
        uint8_t strategy = map->strategies[index];
        uint8_t prediction = n148_transform_map_predict(map, index);
        if ((strategy != N148_TRANSFORM_DCT8 &&
             strategy != N148_TRANSFORM_DCT16 &&
             !(dct32 && strategy == N148_TRANSFORM_DCT4)) ||
            prediction >= N148_TRANSFORM_STRATEGY_COUNT) return 0;
        uint8_t delta = (uint8_t)(
            (strategy + N148_TRANSFORM_STRATEGY_COUNT - prediction) %
            N148_TRANSFORM_STRATEGY_COUNT);
        if (!token_symbol(tokens, model, delta)) return 0;
    }
    return 1;
}

static void token_stream_release(TokenStream *tokens) {
    writer_release(&tokens->symbols);
    writer_release(&tokens->model_indexes);
    writer_release(&tokens->amplitudes);
    tokens->amplitude_bits = 0;
}

int n148_trace_base_contexts(const N148CoeffPlane coefficients[3],
                           int width, int height, int chroma,
                           uint32_t features,
                           N148ContextTrace *trace) {
    if (!coefficients || !trace || width <= 0 || height <= 0 ||
        chroma < CHROMA_444 || chroma > CHROMA_420 ||
        (features & ~N148_FORMAT_2_SUPPORTED_FEATURES)) return 0;
    TokenStream tokens;
    memset(&tokens, 0, sizeof(tokens));
    writer_init(&tokens.symbols);
    writer_init(&tokens.model_indexes);
    writer_init(&tokens.amplitudes);
    int chroma_width, chroma_height;
    chroma_dimensions(chroma, width, height, &chroma_width, &chroma_height);
    int widths[3] = {width, chroma_width, chroma_width};
    int heights[3] = {height, chroma_height, chroma_height};
    int success = 1;
    for (int plane = 0; plane < 3 && success; plane++) {
        int blocks_x = widths[plane] / 8 + (widths[plane] % 8 != 0);
        int blocks_y = heights[plane] / 8 + (heights[plane] % 8 != 0);
        if ((size_t) blocks_x > SIZE_MAX / (size_t) blocks_y) {
            success = 0;
            break;
        }
        size_t expected_blocks = (size_t) blocks_x * (size_t) blocks_y;
        if (!coefficients[plane].coefficients ||
            !coefficients[plane].nonzero_masks ||
            expected_blocks > LONG_MAX ||
            coefficients[plane].count != (long) expected_blocks ||
            !tokenize_plane(&coefficients[plane], blocks_x,
                            plane == 0 ? 0 : 1,
                            (features & N148_FEATURE_CONTEXT) != 0,
                            (features & N148_FEATURE_INTRA) != 0,
                            &tokens)) success = 0;
    }
    context_trace_init(trace);
    if (success && tokens.model_indexes.size <= UINT32_MAX) {
        for (size_t index = 0; index < tokens.model_indexes.size; index++) {
            if (!context_trace_add(trace, tokens.model_indexes.data[index])) {
                success = 0;
                break;
            }
        }
    } else {
        success = 0;
    }
    token_stream_release(&tokens);
    if (!success) memset(trace, 0, sizeof(*trace));
    return success;
}

static int models_from_tokens(const TokenStream *tokens,
                              N148RansModel models[MAX_MODEL_COUNT],
                              int model_count) {
    uint32_t counts[MAX_MODEL_COUNT][N148_RANS_ALPHABET_SIZE] = {{0}};
    if (model_count <= 0 || model_count > MAX_MODEL_COUNT) return 0;
    if (tokens->symbols.size != tokens->model_indexes.size ||
        tokens->symbols.size > UINT32_MAX) return 0;
    for (size_t index = 0; index < tokens->symbols.size; index++) {
        int model = tokens->model_indexes.data[index];
        int symbol = tokens->symbols.data[index];
        if (model < 0 || model >= model_count ||
            counts[model][symbol] == UINT32_MAX) return 0;
        counts[model][symbol]++;
    }
    for (int model = 0; model < model_count; model++) {
        /* Some contexts can be unreachable in a small image. A one-symbol
           placeholder keeps the table layout fixed without affecting bits. */
        if (counts[model][0] == 0) {
            int empty = 1;
            for (int symbol = 1; symbol < N148_RANS_ALPHABET_SIZE; symbol++)
                empty &= counts[model][symbol] == 0;
            if (empty) counts[model][0] = 1;
        }
        if (!n148_rans_build_model(counts[model], &models[model])) return 0;
    }
    return 1;
}

/* Rich contexts inherit a compact image-specific parent model. Only the
   22 legacy parent distributions are signalled; adaptation then specializes
   each child context independently as symbols arrive. */
static int rich_parent_model(int child_model) {
    if (child_model < 0 || child_model >= RICH_CONTEXT_MODEL_COUNT)
        return -1;
    if (child_model < RICH_LUMA_DC_MODELS)
        return child_model % CONTEXT_DC_BUCKETS;
    child_model -= RICH_LUMA_DC_MODELS;
    if (child_model < RICH_LUMA_AC_MODELS) {
        int activity = child_model % RICH_ACTIVITY_BUCKETS;
        int context = child_model / RICH_ACTIVITY_BUCKETS;
        int position_bucket = context % RICH_POSITION_BUCKETS;
        int band = position_bucket <= 2 ? 0 :
            (position_bucket == 3 ? 1 : 2);
        int active = activity == RICH_ACTIVITY_BUCKETS - 1;
        return CONTEXT_DC_MODELS +
            band * CONTEXT_ACTIVITY_BUCKETS + active;
    }
    child_model -= RICH_LUMA_AC_MODELS;
    if (child_model < RICH_CHROMA_DC_MODELS)
        return CONTEXT_DC_BUCKETS + child_model;
    child_model -= RICH_CHROMA_DC_MODELS;
    return CONTEXT_DC_MODELS +
        CONTEXT_BANDS * CONTEXT_ACTIVITY_BUCKETS + child_model;
}

static int count_table_is_empty(
    const uint32_t counts[N148_RANS_ALPHABET_SIZE]) {
    for (int symbol = 0; symbol < N148_RANS_ALPHABET_SIZE; symbol++)
        if (counts[symbol]) return 0;
    return 1;
}

static int models_from_rich_tokens(
    const TokenStream *tokens,
    N148RansModel models[MAX_MODEL_COUNT], int model_count) {
    uint32_t counts[MAX_MODEL_COUNT][N148_RANS_ALPHABET_SIZE] = {{0}};
    N148RansModel parents[CONTEXT_MODEL_COUNT];
    if (!tokens || model_count <= RICH_CONTEXT_MODEL_COUNT ||
        model_count > MAX_MODEL_COUNT ||
        tokens->symbols.size != tokens->model_indexes.size ||
        tokens->symbols.size > UINT32_MAX) return 0;
    for (size_t index = 0; index < tokens->symbols.size; index++) {
        int logical = tokens->model_indexes.data[index];
        if (logical < 0 || logical >= model_count) return 0;
        int stored = logical < RICH_CONTEXT_MODEL_COUNT ?
            rich_parent_model(logical) :
            CONTEXT_MODEL_COUNT + logical -
                RICH_CONTEXT_MODEL_COUNT;
        int symbol = tokens->symbols.data[index];
        if (stored < 0 || stored >= MAX_MODEL_COUNT ||
            counts[stored][symbol] == UINT32_MAX) return 0;
        counts[stored][symbol]++;
    }
    for (int parent = 0; parent < CONTEXT_MODEL_COUNT; parent++) {
        if (count_table_is_empty(counts[parent])) counts[parent][0] = 1;
        if (!n148_rans_build_model(counts[parent], &parents[parent]))
            return 0;
    }
    for (int child = 0; child < RICH_CONTEXT_MODEL_COUNT; child++) {
        int parent = rich_parent_model(child);
        if (parent < 0) return 0;
        models[child] = parents[parent];
    }
    for (int logical = RICH_CONTEXT_MODEL_COUNT;
         logical < model_count; logical++) {
        int stored = CONTEXT_MODEL_COUNT + logical -
            RICH_CONTEXT_MODEL_COUNT;
        if (count_table_is_empty(counts[stored])) counts[stored][0] = 1;
        if (!n148_rans_build_model(counts[stored], &models[logical]))
            return 0;
    }
    return 1;
}

static int select_rich_adaptive_models(
    const TokenStream *tokens, const N148RansModel *models,
    uint8_t mask[RICH_ADAPTIVE_MASK_SIZE]) {
    if (!tokens || !models || !mask ||
        tokens->symbols.size != tokens->model_indexes.size) return 0;
    N148RansAdaptiveModel adaptive[RICH_ADAPTIVE_MODEL_COUNT];
    long double static_log[RICH_ADAPTIVE_MODEL_COUNT] = {0};
    long double adaptive_log[RICH_ADAPTIVE_MODEL_COUNT] = {0};
    uint32_t event_count[RICH_ADAPTIVE_MODEL_COUNT] = {0};
    memset(mask, 0, RICH_ADAPTIVE_MASK_SIZE);
    for (int model = 0; model < RICH_ADAPTIVE_MODEL_COUNT; model++) {
        if (!n148_rans_adaptive_model_init(&adaptive[model], &models[model]))
            return 0;
    }
    for (size_t index = 0; index < tokens->symbols.size; index++) {
        unsigned int model = tokens->model_indexes.data[index];
        if (model >= RICH_ADAPTIVE_MODEL_COUNT) continue;
        uint8_t symbol = tokens->symbols.data[index];
        uint16_t fixed_frequency = models[model].frequency[symbol];
        uint16_t moving_frequency = adaptive[model].frequency[symbol];
        if (!fixed_frequency || !moving_frequency ||
            event_count[model] == UINT32_MAX) return 0;
        static_log[model] += logl((long double) fixed_frequency);
        adaptive_log[model] += logl((long double) moving_frequency);
        event_count[model]++;
        if (!n148_rans_adaptive_model_update(
                &adaptive[model], symbol,
                N148_ENTROPY_ADAPT_RATE_SHIFT)) return 0;
    }
    const long double one_bit = logl(2.0L);
    for (int model = 0; model < RICH_ADAPTIVE_MODEL_COUNT; model++) {
        /* One bit of hysteresis avoids selecting a context on arithmetic
           noise that the interleaved byte-rANS state cannot realize. */
        if (event_count[model] > 1 &&
            adaptive_log[model] > static_log[model] + one_bit)
            mask[model >> 3] |= (uint8_t)(1u << (model & 7));
    }
    return 1;
}

static int write_model(ByteWriter *writer, const N148RansModel *model) {
    if (model->used_symbols == 0) return 0;
    uint8_t symbols[N148_RANS_ALPHABET_SIZE];
    int symbol_count = 0;
    for (int symbol = 0; symbol < N148_RANS_ALPHABET_SIZE; symbol++) {
        if (model->frequency[symbol]) symbols[symbol_count++] = (uint8_t) symbol;
    }
    if (symbol_count != model->used_symbols ||
        !writer_u8(writer, symbol_count == 256 ? 0 : (uint8_t) symbol_count) ||
        !writer_u8(writer, symbols[0])) return 0;

    PackedWriter packed;
    packed_writer_init(&packed, writer);
    for (int index = 1; index < symbol_count; index++) {
        int delta = symbols[index] - symbols[index - 1];
        if (delta <= 15) {
            if (!packed_writer_bits(&packed, (uint32_t)(delta - 1), 4)) return 0;
        } else if (!packed_writer_bits(&packed, 15, 4) ||
                   !packed_writer_bits(&packed, symbols[index], 8)) {
            return 0;
        }
    }
    for (int index = 0; index < symbol_count - 1; index++)
        if (!writer_varuint(writer, model->frequency[symbols[index]])) return 0;
    return 1;
}

static int read_model(ByteReader *reader, N148RansModel *model) {
    memset(model, 0, sizeof(*model));
    uint16_t used_code = reader_u8(reader);
    uint16_t used = used_code ? used_code : 256;
    uint8_t symbols[N148_RANS_ALPHABET_SIZE];
    symbols[0] = reader_u8(reader);
    if (!reader->valid) return 0;
    PackedReader packed;
    packed_reader_init(&packed, reader);
    for (uint16_t index = 1; index < used; index++) {
        uint32_t delta_code = packed_reader_bits(&packed, 4);
        uint32_t symbol = delta_code < 15 ?
            (uint32_t) symbols[index - 1] + delta_code + 1u :
            packed_reader_bits(&packed, 8);
        if (!packed.valid || symbol <= symbols[index - 1] || symbol > 255 ||
            (delta_code == 15 && symbol <= symbols[index - 1] + 15u))
            return 0;
        symbols[index] = (uint8_t) symbol;
    }
    if (!packed_reader_finish(&packed)) return 0;

    uint32_t remaining = N148_RANS_TOTAL;
    for (uint16_t index = 0; index < used; index++) {
        uint32_t frequency;
        uint32_t symbols_after = (uint32_t) used - index - 1;
        if (symbols_after == 0) {
            frequency = remaining;
        } else {
            frequency = reader_varuint(reader);
            if (!reader->valid || frequency == 0 ||
                frequency > remaining - symbols_after) return 0;
        }
        model->frequency[symbols[index]] = (uint16_t) frequency;
        remaining -= frequency;
    }
    return remaining == 0 && n148_rans_prepare_model(model);
}

static int write_rich_models(ByteWriter *writer,
                                const N148RansModel *models,
                                int model_count,
                                const uint8_t adaptive_mask[
                                    RICH_ADAPTIVE_MASK_SIZE]) {
    if (!writer || !models || !adaptive_mask ||
        model_count <= RICH_CONTEXT_MODEL_COUNT ||
        model_count > MAX_MODEL_COUNT ||
        !writer_u8(writer, 2u) || !writer_u8(writer, ENTROPY_CODER_RANS) ||
        !writer_u8(writer, (uint8_t) model_count) ||
        !writer_u8(writer, N148_RANS_SCALE_BITS) ||
        !writer_u8(writer, CONTEXT_MODEL_COUNT) ||
        !writer_u8(writer, RICH_ADAPTIVE_MASK_SIZE) ||
        !writer_bytes(writer, adaptive_mask,
                      RICH_ADAPTIVE_MASK_SIZE)) return 0;
    for (int parent = 0; parent < CONTEXT_MODEL_COUNT; parent++) {
        int representative = -1;
        for (int child = 0; child < RICH_CONTEXT_MODEL_COUNT; child++) {
            if (rich_parent_model(child) == parent) {
                representative = child;
                break;
            }
        }
        /* A compact child layout may intentionally omit one legacy band.
           Such a parent is never consulted after parsing; serialize the
           deterministic model-zero placeholder to keep the grammar fixed. */
        if (representative < 0) representative = 0;
        if (!write_model(writer, &models[representative])) return 0;
    }
    for (int model = RICH_CONTEXT_MODEL_COUNT;
         model < model_count; model++) {
        if (!write_model(writer, &models[model])) return 0;
    }
    return 1;
}

static int parse_rich_models(
    const uint8_t *metadata, size_t metadata_size,
    N148RansModel models[MAX_MODEL_COUNT], int expected_model_count,
    uint8_t adaptive_mask[RICH_ADAPTIVE_MASK_SIZE],
    size_t *bytes_consumed) {
    if (!metadata || !models || !adaptive_mask || !bytes_consumed ||
        expected_model_count <= RICH_CONTEXT_MODEL_COUNT ||
        expected_model_count > MAX_MODEL_COUNT) return 0;
    ByteReader reader;
    reader_init(&reader, metadata, metadata_size);
    if (reader_u8(&reader) != 2u ||
        reader_u8(&reader) != ENTROPY_CODER_RANS ||
        reader_u8(&reader) != expected_model_count ||
        reader_u8(&reader) != N148_RANS_SCALE_BITS ||
        reader_u8(&reader) != CONTEXT_MODEL_COUNT ||
        reader_u8(&reader) != RICH_ADAPTIVE_MASK_SIZE) return 0;
    const uint8_t *stored_mask = reader_bytes(
        &reader, RICH_ADAPTIVE_MASK_SIZE);
    if (!stored_mask) return 0;
    memcpy(adaptive_mask, stored_mask, RICH_ADAPTIVE_MASK_SIZE);
    unsigned int tail_bits = RICH_ADAPTIVE_MODEL_COUNT & 7;
    if (tail_bits &&
        (adaptive_mask[RICH_ADAPTIVE_MASK_SIZE - 1] >> tail_bits) != 0)
        return 0;
    N148RansModel parents[CONTEXT_MODEL_COUNT];
    for (int parent = 0; parent < CONTEXT_MODEL_COUNT; parent++)
        if (!read_model(&reader, &parents[parent])) return 0;
    for (int child = 0; child < RICH_CONTEXT_MODEL_COUNT; child++) {
        int parent = rich_parent_model(child);
        if (parent < 0) return 0;
        models[child] = parents[parent];
    }
    for (int model = RICH_CONTEXT_MODEL_COUNT;
         model < expected_model_count; model++)
        if (!read_model(&reader, &models[model])) return 0;
    if (!reader.valid) return 0;
    *bytes_consumed = reader.position;
    return 1;
}

static int encode_rans(Plane *y, Plane *cb, Plane *cr, int quality,
                       uint32_t features, int effort,
                       N148EncodedPayload *output) {
    N148CoeffPlane coefficients[3] = {{0}};
    TokenStream tokens;
    N148RansModel *models = NULL;
    N148AdaptiveMap adaptive_map = {0};
    N148TransformMap transform_map = {0};
    uint8_t *rans_stream = NULL;
    uint8_t *prediction_modes = NULL;
    size_t rans_size = 0;
    size_t prediction_mode_count = 0;
    ByteWriter metadata, payload;
    writer_init(&metadata);
    writer_init(&payload);
    memset(&tokens, 0, sizeof(tokens));
    writer_init(&tokens.symbols);
    writer_init(&tokens.model_indexes);
    writer_init(&tokens.amplitudes);
    int success = 0;
    int use_context = (features & N148_FEATURE_CONTEXT) != 0;
    int use_intra = (features & N148_FEATURE_INTRA) != 0;
    int use_perceptual =
        (features & N148_FEATURE_PERCEPTUAL_COLOR) != 0;
    int use_adaptive =
        (features & N148_FEATURE_ADAPTIVE_QUANT) != 0;
    int use_transform =
        (features & N148_FEATURE_VARIABLE_TRANSFORM) != 0;
    int use_rdo = (features & N148_FEATURE_RDO) != 0;
    int use_loop_filter =
        (features & N148_FEATURE_LOOP_FILTER) != 0;
    int coefficient_model_count = use_context ?
        CONTEXT_MODEL_COUNT : BASE_COEFFICIENT_MODEL_COUNT;
    int model_count = coefficient_model_count +
        (use_intra ? BLOCK_INTRA_MODELS : 0) +
        (use_adaptive ? ADAPTIVE_MAP_MODEL_COUNT : 0) +
        (use_transform ? TRANSFORM_MAP_MODEL_COUNT : 0);
    int y_blocks_x = y->width / 8 + (y->width % 8 != 0);
    int cb_blocks_x = cb->width / 8 + (cb->width % 8 != 0);
    int cr_blocks_x = cr->width / 8 + (cr->width % 8 != 0);

    /* The model bank alone exceeds the default 1 MiB Windows stack. */
    models = (N148RansModel *) malloc(MAX_MODEL_COUNT * sizeof(*models));
    if (!models) goto cleanup;
    if (use_adaptive && !n148_adaptive_map_build(y, &adaptive_map))
        goto cleanup;
    if (use_transform &&
        !n148_transform_map_build(y, cb, cr, &transform_map)) goto cleanup;
    if (use_intra) {
        if (!n148_intra_quantize_planes(y, cb, cr, quality, use_perceptual,
                                        use_adaptive ? &adaptive_map : NULL,
                                        use_transform ? &transform_map : NULL,
                                        use_rdo ? effort : 0,
                                        use_loop_filter,
                                        coefficients,
                                        &prediction_modes,
                                        &prediction_mode_count)) goto cleanup;
    } else if (!n148_quantize_planes_ex(y, cb, cr, quality, use_perceptual,
                                        coefficients)) {
        goto cleanup;
    }
    if (!tokenize_plane(&coefficients[0], y_blocks_x, 0, use_context,
                        use_intra,
                        &tokens) ||
        !tokenize_plane(&coefficients[1], cb_blocks_x, 1, use_context,
                        use_intra,
                        &tokens) ||
        !tokenize_plane(&coefficients[2], cr_blocks_x, 1, use_context,
                        use_intra,
                        &tokens) ||
        (use_intra &&
         (!tokenize_prediction_plane(
              prediction_modes, coefficients[0].count, y_blocks_x, 0,
              coefficient_model_count, &tokens) ||
          !tokenize_prediction_plane(
              prediction_modes + coefficients[0].count,
              coefficients[1].count, cb_blocks_x, 1,
              coefficient_model_count, &tokens) ||
          !tokenize_prediction_plane(
              prediction_modes + coefficients[0].count +
                  coefficients[1].count,
              coefficients[2].count, cr_blocks_x, 1,
              coefficient_model_count, &tokens))) ||
        (use_adaptive && !tokenize_adaptive_map(
            &adaptive_map, coefficient_model_count + BLOCK_INTRA_MODELS,
            &tokens)) ||
        (use_transform && !tokenize_transform_map(
            &transform_map, coefficient_model_count + BLOCK_INTRA_MODELS +
                (use_adaptive ? ADAPTIVE_MAP_MODEL_COUNT : 0),
            &tokens)) ||
        !models_from_tokens(&tokens, models, model_count) ||
        !n148_rans_encode_mixed(tokens.symbols.data,
                                tokens.model_indexes.data,
                                tokens.symbols.size, models,
                                (size_t) model_count,
                                &rans_stream, &rans_size)) goto cleanup;

    if (!writer_u8(&metadata, ENTROPY_METADATA_REVISION_BASE) ||
        !writer_u8(&metadata, ENTROPY_CODER_RANS) ||
        !writer_u8(&metadata, (uint8_t) model_count) ||
        !writer_u8(&metadata, N148_RANS_SCALE_BITS)) goto cleanup;
    for (int model = 0; model < model_count; model++)
        if (!write_model(&metadata, &models[model])) goto cleanup;

    uint8_t payload_version = use_transform ? PAYLOAD_REVISION_VARIABLE_TRANSFORM :
        (use_adaptive ? PAYLOAD_REVISION_ADAPTIVE_QUANT :
        (use_intra ? PAYLOAD_REVISION_INTRA :
                     PAYLOAD_REVISION_ENTROPY));
    if (!writer_u8(&payload, payload_version) ||
        !writer_u8(&payload, PLANE_COUNT) ||
        !writer_u8(&payload, use_intra ? INTRA_MODE_CODER_RANS : 0) ||
        !writer_u8(&payload,
                   (use_adaptive ? ADAPTIVE_MAP_CODER_RANS : 0) |
                   (use_transform ? TRANSFORM_MAP_CODER_RANS : 0)))
        goto cleanup;
    if (tokens.symbols.size > UINT32_MAX || rans_size > UINT32_MAX ||
        tokens.amplitude_bits > UINT32_MAX ||
        prediction_mode_count > UINT32_MAX ||
        transform_map.count > UINT32_MAX ||
        tokens.amplitudes.size != (tokens.amplitude_bits + 7u) / 8u ||
        !writer_u32(&payload, (uint32_t) tokens.symbols.size) ||
        !writer_u32(&payload, (uint32_t) rans_size) ||
        !writer_u32(&payload, (uint32_t) tokens.amplitude_bits) ||
        (use_intra && !writer_u32(
            &payload, (uint32_t) prediction_mode_count)) ||
        (use_adaptive && !writer_u32(
            &payload, (uint32_t) adaptive_map.count)) ||
        (use_transform && !writer_u32(
            &payload, (uint32_t) transform_map.count)) ||
        !writer_bytes(&payload, rans_stream, rans_size) ||
        !writer_bytes(&payload, tokens.amplitudes.data,
                      tokens.amplitudes.size)) goto cleanup;
    output->metadata = writer_detach(&metadata, &output->metadata_size);
    output->payload = writer_detach(&payload, &output->payload_size);
    if ((!output->metadata && output->metadata_size) ||
        (!output->payload && output->payload_size)) goto cleanup;
    success = 1;

cleanup:
    if (!success) n148_encoded_payload_release(output);
    writer_release(&metadata);
    writer_release(&payload);
    free(models);
    free(rans_stream);
    free(prediction_modes);
    n148_adaptive_map_release(&adaptive_map);
    n148_transform_map_release(&transform_map);
    for (int plane = 0; plane < 3; plane++) {
        n148_free_coeff_plane(&coefficients[plane]);
    }
    token_stream_release(&tokens);
    return success;
}

static int write_huffman_metadata(ByteWriter *metadata,
                                  const HuffSpec specs[HUFFMAN_TABLE_COUNT]) {
    if (!writer_u8(metadata, ENTROPY_METADATA_REVISION_BASE) ||
        !writer_u8(metadata, ENTROPY_CODER_HUFFMAN) ||
        !writer_u8(metadata, HUFFMAN_TABLE_COUNT) ||
        !writer_u8(metadata, 0)) return 0;
    for (int table = 0; table < HUFFMAN_TABLE_COUNT; table++) {
        if (!huffman_spec_is_valid(&specs[table])) return 0;
        for (int length = 1; length <= 16; length++)
            if (!writer_u8(metadata, (uint8_t) specs[table].bits[length]))
                return 0;
        if (!writer_bytes(metadata, specs[table].values,
                          (size_t) specs[table].value_count)) return 0;
    }
    return 1;
}

static int encode_huffman(Plane *y, Plane *cb, Plane *cr, int quality,
                          N148EncodedPayload *output) {
    HuffSpec specs[HUFFMAN_TABLE_COUNT];
    EncodeStats stats;
    unsigned char *payload = NULL;
    ByteWriter metadata;
    writer_init(&metadata);
    int success = 0;
    if (!encode_image(y, cb, cr, quality, 1, specs, &payload, &stats) ||
        stats.data_size <= 0 || !write_huffman_metadata(&metadata, specs)) {
        goto cleanup;
    }
    output->metadata = writer_detach(&metadata, &output->metadata_size);
    output->payload = payload;
    output->payload_size = (size_t) stats.data_size;
    payload = NULL;
    success = 1;
cleanup:
    free(payload);
    writer_release(&metadata);
    if (!success) n148_encoded_payload_release(output);
    return success;
}

int n148_encode_format_2(Plane *y, Plane *cb, Plane *cr, int quality,
                   uint32_t features, int effort, N148EncodedPayload *output) {
    if (!y || !cb || !cr || !output || quality < 1 || quality > 100 ||
        effort < 0 || effort > 9 ||
        (features & ~N148_FORMAT_2_SUPPORTED_FEATURES) ||
        ((features & (N148_FEATURE_CONTEXT | N148_FEATURE_INTRA |
                      N148_FEATURE_PERCEPTUAL_COLOR |
                      N148_FEATURE_ADAPTIVE_QUANT |
                      N148_FEATURE_VARIABLE_TRANSFORM |
                      N148_FEATURE_RDO |
                      N148_FEATURE_LOOP_FILTER)) &&
         !(features & N148_FEATURE_RANS)) ||
        ((features & N148_FEATURE_ADAPTIVE_QUANT) &&
         !(features & N148_FEATURE_INTRA)) ||
        ((features & N148_FEATURE_VARIABLE_TRANSFORM) &&
         !(features & N148_FEATURE_INTRA)) ||
        ((features & N148_FEATURE_RDO) &&
         !(features & N148_FEATURE_INTRA)) ||
        ((features & N148_FEATURE_LOOP_FILTER) &&
         !(features & N148_FEATURE_INTRA))) return 0;
    memset(output, 0, sizeof(*output));
    if (features & N148_FEATURE_RANS)
        return encode_rans(y, cb, cr, quality, features, effort, output);
    return encode_huffman(y, cb, cr, quality, output);
}

int n148_format_3_features_valid(uint32_t features) {
    if (features & ~N148_FORMAT_3_SUPPORTED_FEATURES) return 0;
    if (!(features & N148_FEATURE_RANS) ||
        !(features & N148_FEATURE_INTRA)) return 0;
    if ((features & (N148_FEATURE_CONTEXT | N148_FEATURE_RDO |
                     N148_FEATURE_LOOP_FILTER |
                     N148_FEATURE_DIRECTIONAL_INTRA |
                     N148_FEATURE_INTRA_4X4 |
                     N148_FEATURE_CONTEXTUAL_RDO |
                     N148_FEATURE_PERCEPTUAL_TRELLIS)) &&
        !(features & N148_FEATURE_RANS)) return 0;
    if ((features & (N148_FEATURE_RDO | N148_FEATURE_LOOP_FILTER |
                     N148_FEATURE_DIRECTIONAL_INTRA |
                     N148_FEATURE_INTRA_4X4 |
                     N148_FEATURE_CONTEXTUAL_RDO |
                     N148_FEATURE_PERCEPTUAL_TRELLIS)) &&
        !(features & N148_FEATURE_INTRA)) return 0;
    if ((features & N148_FEATURE_CONTEXTUAL_RDO) &&
        (!(features & N148_FEATURE_RDO) ||
         !(features & N148_FEATURE_CONTEXT))) return 0;
    if ((features & N148_FEATURE_PERCEPTUAL_TRELLIS) &&
        !(features & N148_FEATURE_CONTEXTUAL_RDO)) return 0;
    return 1;
}

void n148_predictive_preparation_release(N148PredictivePreparation *prepared) {
    if (!prepared) return;
    free(prepared->prediction_modes);
    n148_partition_map_release(&prepared->partition_map);
    n148_segmentation_map_release(&prepared->segmentation_map);
    n148_transform_map_release(&prepared->transform_map);
    for (int plane = 0; plane < 3; plane++)
        n148_free_coeff_plane(&prepared->coefficients[plane]);
    memset(prepared, 0, sizeof(*prepared));
}

int n148_predictive_encode_cached(Plane *y, Plane *cb, Plane *cr, int quality,
                                  int chroma_quality, uint32_t features,
                                  int effort, int joint_chroma,
                                  int calibrated_chroma, int segmented,
                                  int adaptive_filter, int calibrated_luma,
                                  int variable_luma,
                                  int perceptual_luma_trellis,
                                  int quant_adaptive_filter, int dct32,
                                  uint32_t entropy_tools,
                                  N148EncodedPayload *output,
                                  N148PredictivePreparation *prepared) {
    N148CoeffPlane coefficients[3] = {{0}};
    TokenStream tokens;
    N148RansModel *models = NULL;
    N148PartitionMap partition_map = {0};
    N148SegmentationMap segmentation_map = {0};
    N148TransformMap transform_map = {0};
    uint8_t *rans_stream = NULL;
    uint8_t *prediction_modes = NULL;
    uint8_t adaptive_mask[RICH_ADAPTIVE_MASK_SIZE] = {0};
    size_t rans_size = 0;
    size_t prediction_mode_count = 0;
    ByteWriter metadata, payload;
    writer_init(&metadata);
    writer_init(&payload);
    memset(&tokens, 0, sizeof(tokens));
    writer_init(&tokens.symbols);
    writer_init(&tokens.model_indexes);
    writer_init(&tokens.amplitudes);
    int success = 0;
    int use_context = (features & N148_FEATURE_CONTEXT) != 0;
    int use_directional =
        (features & N148_FEATURE_DIRECTIONAL_INTRA) != 0;
    int use_split = (features & N148_FEATURE_INTRA_4X4) != 0;
    int use_contextual_rdo =
        (features & N148_FEATURE_CONTEXTUAL_RDO) != 0;
    int use_perceptual_trellis =
        (features & N148_FEATURE_PERCEPTUAL_TRELLIS) != 0;
    int trellis_policy = use_perceptual_trellis ?
        (perceptual_luma_trellis ? N148_TRELLIS_PERCEPTUAL_LUMA : N148_TRELLIS_LEGACY) :
        N148_TRELLIS_OFF;
    int use_rdo = (features & N148_FEATURE_RDO) != 0;
    int use_loop_filter =
        (features & N148_FEATURE_LOOP_FILTER) != 0;
    int adaptive_entropy =
        (entropy_tools & N148_ENTROPY_ADAPTIVE) != 0;
    int rich_context =
        (entropy_tools & N148_ENTROPY_RICH_CONTEXT) != 0;
    int multiple_references =
        (entropy_tools & N148_ENTROPY_MULTIPLE_REFERENCES) != 0;
    int loop_filter_policy = use_loop_filter ?
        (quant_adaptive_filter ? N148_LOOP_FILTER_QUANT_ADAPTIVE_LUMA :
                                 N148_LOOP_FILTER_LEGACY) :
        N148_LOOP_FILTER_OFF;
    int coefficient_model_count = rich_context ?
        RICH_CONTEXT_MODEL_COUNT : use_context ?
        CONTEXT_MODEL_COUNT : BASE_COEFFICIENT_MODEL_COUNT;
    int model_count = coefficient_model_count + DIRECTIONAL_MODELS +
        (use_split ? PARTITION_MODEL_COUNT : 0) +
        (segmented ? SEGMENTATION_MODEL_COUNT : 0) +
        (variable_luma ? LUMA_TRANSFORM_MODEL_COUNT : 0);
    int y_blocks_x = y->width / 8 + (y->width % 8 != 0);
    int y_blocks_y = y->height / 8 + (y->height % 8 != 0);
    int cb_blocks_x = cb->width / 8 + (cb->width % 8 != 0);
    int cr_blocks_x = cr->width / 8 + (cr->width % 8 != 0);
    int chroma = CHROMA_444;
    if (cb->width < y->width)
        chroma = cb->height < y->height ? CHROMA_420 : CHROMA_422;

    if ((adaptive_filter != 0 && adaptive_filter != 1) ||
        (calibrated_luma != 0 && calibrated_luma != 1) ||
        (variable_luma != 0 && variable_luma != 1) ||
        (perceptual_luma_trellis != 0 && perceptual_luma_trellis != 1) ||
        (quant_adaptive_filter != 0 && quant_adaptive_filter != 1) ||
        (dct32 != 0 && dct32 != 1) ||
        (entropy_tools & ~(N148_ENTROPY_ADAPTIVE |
                           N148_ENTROPY_RICH_CONTEXT |
                           N148_ENTROPY_MULTIPLE_REFERENCES)) ||
        (adaptive_entropy && !(features & N148_FEATURE_RANS)) ||
        (rich_context && (!use_context || !adaptive_entropy)) ||
        (multiple_references && (!use_directional ||
                                 !use_contextual_rdo)) ||
        (dct32 && !variable_luma) ||
        (quant_adaptive_filter && (!use_loop_filter || !calibrated_luma)) ||
        (variable_luma && (!use_contextual_rdo || !use_split)) ||
        (adaptive_filter && !segmented)) goto cleanup;
    models = (N148RansModel *) malloc(MAX_MODEL_COUNT * sizeof(*models));
    if (!models) goto cleanup;
    if (prepared && prepared->valid) {
        memcpy(coefficients, prepared->coefficients, sizeof(coefficients));
        partition_map = prepared->partition_map;
        segmentation_map = prepared->segmentation_map;
        transform_map = prepared->transform_map;
        prediction_modes = prepared->prediction_modes;
        prediction_mode_count = prepared->prediction_mode_count;
    } else {
        if (segmented) {
            int built = n148_fidelity_detail_reconstruction() ?
                n148_segmentation_map_build_detail(y, &segmentation_map) :
                n148_fidelity_structural_quant() ?
                n148_segmentation_map_build_structural(y, &segmentation_map) :
                n148_segmentation_map_build(y, &segmentation_map);
            if (!built) goto cleanup;
            segmentation_map.adaptive_filter = (uint8_t) adaptive_filter;
        }
        if (!n148_partition_map_allocate(y->width, y->height, chroma,
                                        &partition_map) ||
        (variable_luma && !n148_transform_map_allocate(
            y->width, y->height, chroma, &transform_map)) ||
        !(joint_chroma ? n148_joint_chroma_intra_quantize_planes(
              y, cb, cr, quality, chroma_quality, calibrated_chroma,
              calibrated_luma, use_directional, use_split, use_contextual_rdo,
              use_rdo ? effort : 0,
              trellis_policy, loop_filter_policy,
              &partition_map,
              segmented ? &segmentation_map : NULL,
              variable_luma ? &transform_map : NULL,
              coefficients, &prediction_modes,
              &prediction_mode_count) :
          n148_directional_intra_quantize_planes(
              y, cb, cr, quality, chroma_quality, calibrated_chroma,
              calibrated_luma, use_directional, use_split, use_contextual_rdo,
              use_rdo ? effort : 0,
              trellis_policy, loop_filter_policy,
              &partition_map,
              segmented ? &segmentation_map : NULL,
              variable_luma ? &transform_map : NULL,
              coefficients, &prediction_modes,
              &prediction_mode_count))) goto cleanup;
        if (prepared) {
            memcpy(prepared->coefficients, coefficients, sizeof(coefficients));
            prepared->partition_map = partition_map;
            prepared->segmentation_map = segmentation_map;
            prepared->transform_map = transform_map;
            prepared->prediction_modes = prediction_modes;
            prepared->prediction_mode_count = prediction_mode_count;
            prepared->valid = 1;
        }
    }

    size_t y_modes = (size_t) coefficients[0].count *
        N148_INTRA_MODE_SLOTS_PER_BLOCK;
    size_t cb_modes = (size_t) coefficients[1].count *
        N148_INTRA_MODE_SLOTS_PER_BLOCK;
    int allowed_modes = multiple_references ?
        N148_PACKED_INTRA_MODE_COUNT :
        (use_directional ? N148_DIRECTIONAL_INTRA_MODE_COUNT : 4);
    int chroma_allowed_modes = use_directional ?
        N148_DIRECTIONAL_INTRA_MODE_COUNT : 4;
    int segmentation_model = coefficient_model_count + DIRECTIONAL_MODELS +
        (use_split ? PARTITION_MODEL_COUNT : 0);
    int transform_model = segmentation_model +
        (segmented ? SEGMENTATION_MODEL_COUNT : 0);
    int token_ok =
        (!variable_luma || tokenize_luma_transform_map(
            &transform_map, transform_model, dct32, &tokens)) &&
        (!use_split || (variable_luma ? tokenize_variable_luma_partition_map(
            &partition_map, &transform_map,
            coefficient_model_count + DIRECTIONAL_MODELS, &tokens) :
          tokenize_partition_map(
            &partition_map, coefficient_model_count + DIRECTIONAL_MODELS,
            &tokens))) &&
        (!segmented || tokenize_segmentation_map(
            &segmentation_map, segmentation_model, &tokens));
    if (!token_ok) {
#ifdef N148_RANS_DIAGNOSTICS
        fprintf(stderr, "rich-context token-map pass failed\n");
#endif
        goto cleanup;
    }

#define TOKENIZE_MODERN_MODES() \
    ((variable_luma ? tokenize_variable_luma_prediction_plane( \
          prediction_modes, coefficients[0].count, y_blocks_x, y_blocks_y, \
          coefficient_model_count, allowed_modes, \
          partition_map.split + partition_map.plane_offsets[0], \
          &transform_map, &tokens) : \
      tokenize_directional_prediction_plane( \
          prediction_modes, coefficients[0].count, y_blocks_x, 0, \
          coefficient_model_count, allowed_modes, \
          partition_map.split + partition_map.plane_offsets[0], &tokens)) && \
     tokenize_directional_prediction_plane( \
          prediction_modes + y_modes, coefficients[1].count, cb_blocks_x, \
          1, coefficient_model_count, chroma_allowed_modes, \
          partition_map.split + partition_map.plane_offsets[1], &tokens) && \
     (joint_chroma || tokenize_directional_prediction_plane( \
          prediction_modes + y_modes + cb_modes, coefficients[2].count, \
          cr_blocks_x, 1, coefficient_model_count, chroma_allowed_modes, \
          partition_map.split + partition_map.plane_offsets[2], &tokens)))

    if (rich_context) {
        token_ok = TOKENIZE_MODERN_MODES() &&
            (variable_luma ? tokenize_rich_luma_coefficient_plane(
                &coefficients[0],
                partition_map.split + partition_map.plane_offsets[0],
                prediction_modes, y_blocks_x, y_blocks_y,
                &transform_map, &tokens) :
             tokenize_rich_coefficient_plane(
                &coefficients[0],
                partition_map.split + partition_map.plane_offsets[0],
                prediction_modes, y_blocks_x, 0, &tokens)) &&
            tokenize_rich_coefficient_plane(
                &coefficients[1],
                partition_map.split + partition_map.plane_offsets[1],
                prediction_modes + y_modes, cb_blocks_x, 1, &tokens) &&
            tokenize_rich_coefficient_plane(
                &coefficients[2],
                partition_map.split + partition_map.plane_offsets[2],
                prediction_modes + y_modes + cb_modes,
                cr_blocks_x, 1, &tokens);
    } else {
        token_ok =
            (variable_luma ? tokenize_variable_luma_coefficient_plane(
                &coefficients[0],
                partition_map.split + partition_map.plane_offsets[0],
                y_blocks_x, y_blocks_y, use_context,
                &transform_map, &tokens) :
             tokenize_directional_coefficient_plane(
                &coefficients[0],
                partition_map.split + partition_map.plane_offsets[0],
                y_blocks_x, 0, use_context, &tokens)) &&
            tokenize_directional_coefficient_plane(
                &coefficients[1],
                partition_map.split + partition_map.plane_offsets[1],
                cb_blocks_x, 1, use_context, &tokens) &&
            tokenize_directional_coefficient_plane(
                &coefficients[2],
                partition_map.split + partition_map.plane_offsets[2],
                cr_blocks_x, 1, use_context, &tokens) &&
            TOKENIZE_MODERN_MODES();
    }
#undef TOKENIZE_MODERN_MODES
    if (!token_ok) {
#ifdef N148_RANS_DIAGNOSTICS
        fprintf(stderr, "rich-context coefficient/mode pass failed\n");
#endif
        goto cleanup;
    }
    if (!(rich_context ?
          models_from_rich_tokens(&tokens, models, model_count) :
          models_from_tokens(&tokens, models, model_count))) {
#ifdef N148_RANS_DIAGNOSTICS
        fprintf(stderr, "rich-context model construction failed (%d models)\n",
                model_count);
#endif
        goto cleanup;
    }
    if (rich_context &&
        !select_rich_adaptive_models(&tokens, models, adaptive_mask))
        goto cleanup;
    if (adaptive_entropy) {
        if (!n148_rans_encode_mixed_adaptive(
                tokens.symbols.data, tokens.model_indexes.data,
                tokens.symbols.size, models, (size_t) model_count,
                rich_context ?
                    RICH_LUMA_DC_MODELS + RICH_LUMA_AC_MODELS :
                    (size_t) model_count,
                rich_context ? adaptive_mask : NULL,
                rich_context ? RICH_ADAPTIVE_MODEL_COUNT : 0,
                N148_ENTROPY_ADAPT_RATE_SHIFT,
                &rans_stream, &rans_size, NULL)) goto cleanup;
    } else if (!n148_rans_encode_mixed(
                   tokens.symbols.data, tokens.model_indexes.data,
                   tokens.symbols.size, models, (size_t) model_count,
                   &rans_stream, &rans_size)) goto cleanup;
    if (rich_context) {
        uint8_t *fixed_stream = NULL;
        size_t fixed_size = 0;
        if (!n148_rans_encode_mixed(
                tokens.symbols.data, tokens.model_indexes.data,
                tokens.symbols.size, models, (size_t) model_count,
                &fixed_stream, &fixed_size)) goto cleanup;
        if (fixed_size < rans_size) {
            free(rans_stream);
            rans_stream = fixed_stream;
            rans_size = fixed_size;
            fixed_stream = NULL;
            memset(adaptive_mask, 0, sizeof(adaptive_mask));
        }
        free(fixed_stream);
    }

    if (rich_context) {
        if (!write_rich_models(
                &metadata, models, model_count, adaptive_mask)) {
#ifdef N148_RANS_DIAGNOSTICS
            fprintf(stderr, "rich-context metadata serialization failed\n");
#endif
            goto cleanup;
        }
    } else {
        if (!writer_u8(&metadata, ENTROPY_METADATA_REVISION_BASE) ||
            !writer_u8(&metadata, ENTROPY_CODER_RANS) ||
            !writer_u8(&metadata, (uint8_t) model_count) ||
            !writer_u8(&metadata, N148_RANS_SCALE_BITS)) goto cleanup;
        for (int model = 0; model < model_count; model++)
            if (!write_model(&metadata, &models[model])) goto cleanup;
    }

    size_t stored_prediction_modes = joint_chroma ?
        y_modes + cb_modes : prediction_mode_count;
    uint8_t payload_version = rich_context ?
        PAYLOAD_REVISION_RICH_CONTEXT : variable_luma ?
        PAYLOAD_REVISION_VARIABLE_LUMA : adaptive_filter ?
        (joint_chroma ? PAYLOAD_REVISION_JOINT_ADAPTIVE_FILTER :
                        PAYLOAD_REVISION_ADAPTIVE_FILTER) :
        segmented ?
        (joint_chroma ? PAYLOAD_REVISION_JOINT_SEGMENTATION :
                        PAYLOAD_REVISION_SEGMENTATION) :
        (joint_chroma ? PAYLOAD_REVISION_JOINT_CHROMA :
                        PAYLOAD_REVISION_DIRECTIONAL_INTRA);
    if (!writer_u8(&payload, payload_version) ||
        !writer_u8(&payload, PLANE_COUNT) ||
        !writer_u8(&payload, INTRA_MODE_CODER_RANS) ||
        !writer_u8(&payload, (uint8_t)(
            (use_split ? PARTITION_MAP_CODER_RANS : 0) |
            (segmented ? SEGMENT_MAP_CODER_RANS : 0) |
            (variable_luma ? TRANSFORM_MAP_CODER_RANS : 0))))
        goto cleanup;
    if (tokens.symbols.size > UINT32_MAX || rans_size > UINT32_MAX ||
        tokens.amplitude_bits > UINT32_MAX ||
        stored_prediction_modes > UINT32_MAX ||
        partition_map.count > UINT32_MAX ||
        segmentation_map.count > UINT32_MAX ||
        transform_map.plane_offsets[1] > UINT32_MAX ||
        tokens.amplitudes.size != (tokens.amplitude_bits + 7u) / 8u ||
        !writer_u32(&payload, (uint32_t) tokens.symbols.size) ||
        !writer_u32(&payload, (uint32_t) rans_size) ||
        !writer_u32(&payload, (uint32_t) tokens.amplitude_bits) ||
        !writer_u32(&payload, (uint32_t) stored_prediction_modes) ||
        (use_split && !writer_u32(
            &payload, (uint32_t) partition_map.count)) ||
        (segmented && !writer_u32(
            &payload, (uint32_t) segmentation_map.count)) ||
        (variable_luma && !writer_u32(
            &payload, (uint32_t) transform_map.plane_offsets[1])) ||
        (segmented && (!writer_u8(&payload, segmentation_map.quant_scale[0]) ||
                       !writer_u8(&payload, segmentation_map.quant_scale[1]) ||
                       !writer_u8(&payload, segmentation_map.quant_scale[2]) ||
                       !writer_u8(&payload, segmentation_map.quant_scale[3]))) ||
        !writer_bytes(&payload, rans_stream, rans_size) ||
        !writer_bytes(&payload, tokens.amplitudes.data,
                      tokens.amplitudes.size)) goto cleanup;

    output->metadata = writer_detach(&metadata, &output->metadata_size);
    output->payload = writer_detach(&payload, &output->payload_size);
    if ((!output->metadata && output->metadata_size) ||
        (!output->payload && output->payload_size)) goto cleanup;
    success = 1;

cleanup:
    if (!success) n148_encoded_payload_release(output);
    writer_release(&metadata);
    writer_release(&payload);
    free(models);
    free(rans_stream);
    if (!prepared || !prepared->valid) {
        free(prediction_modes);
        n148_partition_map_release(&partition_map);
        n148_segmentation_map_release(&segmentation_map);
        n148_transform_map_release(&transform_map);
        for (int plane = 0; plane < 3; plane++)
            n148_free_coeff_plane(&coefficients[plane]);
    }
    token_stream_release(&tokens);
    return success;
}

int n148_predictive_encode(Plane *y, Plane *cb, Plane *cr, int quality,
                          int chroma_quality, uint32_t features, int effort,
                          int joint_chroma, int calibrated_chroma,
                          int segmented, int adaptive_filter,
                          int calibrated_luma, int variable_luma,
                          int perceptual_luma_trellis, int quant_adaptive_filter,
                          int dct32, uint32_t entropy_tools,
                          N148EncodedPayload *output) {
    return n148_predictive_encode_cached(
        y, cb, cr, quality, chroma_quality, features, effort, joint_chroma,
        calibrated_chroma, segmented, adaptive_filter, calibrated_luma,
        variable_luma, perceptual_luma_trellis, quant_adaptive_filter, dct32,
        entropy_tools, output, NULL);
}

int n148_encode_format_3(Plane *y, Plane *cb, Plane *cr, int quality,
                   uint32_t features, int effort, N148EncodedPayload *output) {
    if (!y || !cb || !cr || !output || quality < 1 || quality > 100 ||
        effort < 0 || effort > 9 || !n148_format_3_features_valid(features))
        return 0;
    memset(output, 0, sizeof(*output));
    return n148_predictive_encode(y, cb, cr, quality, quality, features, effort,
                                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, output);
}

int n148_joint_chroma_encode(
    Plane *y, Plane *cb, Plane *cr, int quality,
    uint32_t features, int effort, N148EncodedPayload *output) {
    if (!y || !cb || !cr || !output || quality < 1 || quality > 100 ||
        effort < 0 || effort > 9 || !n148_format_3_features_valid(features) ||
        !(features & N148_FEATURE_CONTEXTUAL_RDO)) return 0;
    memset(output, 0, sizeof(*output));
    return n148_predictive_encode(y, cb, cr, quality, quality, features, effort,
                                 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, output);
}

int n148_calibrated_chroma_encode(
    Plane *y, Plane *cb, Plane *cr, int quality, int chroma_quality,
    uint32_t features, int effort, int joint_chroma,
    N148EncodedPayload *output) {
    if (!y || !cb || !cr || !output || quality < 1 || quality > 100 ||
        chroma_quality < 1 || chroma_quality > 100 ||
        effort < 0 || effort > 9 || !n148_format_3_features_valid(features) ||
        (joint_chroma != 0 && joint_chroma != 1) ||
        (joint_chroma &&
         !(features & N148_FEATURE_CONTEXTUAL_RDO))) return 0;
    memset(output, 0, sizeof(*output));
    return n148_predictive_encode(
        y, cb, cr, quality, chroma_quality, features,
        effort, joint_chroma, 1, 0, 0, 0, 0, 0, 0, 0, 0, output);
}

int n148_segmented_encode(
    Plane *y, Plane *cb, Plane *cr, int quality, int chroma_quality,
    uint32_t features, int effort, int joint_chroma,
    N148EncodedPayload *output) {
    if (!y || !cb || !cr || !output || quality < 1 || quality > 100 ||
        chroma_quality < 1 || chroma_quality > 100 ||
        effort < 0 || effort > 9 || !n148_format_3_features_valid(features) ||
        (joint_chroma != 0 && joint_chroma != 1) ||
        !(features & N148_FEATURE_CONTEXTUAL_RDO)) return 0;
    memset(output, 0, sizeof(*output));
    return n148_predictive_encode(
        y, cb, cr, quality, chroma_quality, features,
        effort, joint_chroma, 1, 1, 0, 0, 0, 0, 0, 0, 0, output);
}

int n148_adaptive_filter_encode(
    Plane *y, Plane *cb, Plane *cr, int quality, int chroma_quality,
    uint32_t features, int effort, int joint_chroma,
    N148EncodedPayload *output) {
    if (!y || !cb || !cr || !output || quality < 1 || quality > 100 ||
        chroma_quality < 1 || chroma_quality > 100 ||
        effort < 0 || effort > 9 || !n148_format_3_features_valid(features) ||
        (joint_chroma != 0 && joint_chroma != 1) ||
        !(features & N148_FEATURE_CONTEXTUAL_RDO) ||
        !(features & N148_FEATURE_LOOP_FILTER)) return 0;
    memset(output, 0, sizeof(*output));
    return n148_predictive_encode(
        y, cb, cr, quality, chroma_quality, features,
        effort, joint_chroma, 1, 1, 1, 0, 0, 0, 0, 0, 0, output);
}

static void bit_reader_init(BitReader *reader, const uint8_t *data,
                            size_t byte_count, size_t bit_count) {
    reader->next = data;
    reader->end = data + byte_count;
    reader->cache = 0;
    reader->bits_remaining = bit_count;
    reader->cached_bits = 0;
    reader->valid = bit_count <= SIZE_MAX - 7u &&
        byte_count == (bit_count + 7u) / 8u;
}

#if defined(__GNUC__) || defined(__clang__)
__attribute__((always_inline))
#endif
static inline uint32_t bit_reader_read(BitReader *reader, int count) {
    if (!reader->valid || count < 0 || count > 16 ||
        (size_t) count > reader->bits_remaining) {
        reader->valid = 0;
        return 0;
    }
    if (count == 0) return 0;
    unsigned int available = reader->cached_bits;
    uint64_t cache = reader->cache;
    const uint8_t *next = reader->next;
    if (available < (unsigned int) count) {
        /* Amplitudes are at most 16 bits. Refill four bytes at once whenever
           possible and retain the unused suffix for following coefficients.
           The byte spelling lets compilers select an unaligned load plus a
           byte swap without permitting an out-of-bounds speculative read. */
        if ((size_t)(reader->end - next) >= 4u) {
            uint32_t word = ((uint32_t) next[0] << 24) |
                ((uint32_t) next[1] << 16) |
                ((uint32_t) next[2] << 8) | next[3];
            cache = (cache << 32) | word;
            next += 4;
            available += 32;
        } else {
            do {
                if (next == reader->end) {
                    reader->valid = 0;
                    return 0;
                }
                cache = (cache << 8) | *next++;
                available += 8;
            } while (available < (unsigned int) count);
        }
    }
    available -= (unsigned int) count;
    reader->next = next;
    reader->cache = cache;
    reader->cached_bits = available;
    reader->bits_remaining -= (size_t) count;
    return (uint32_t)(cache >> available) & ((1u << count) - 1u);
}

static inline int decode_amplitude(BitReader *reader, int bits, int *value) {
    if (bits == 0) {
        *value = 0;
        return 1;
    }
    uint32_t amplitude = bit_reader_read(reader, bits);
    if (!reader->valid) return 0;
    /* The top amplitude bit is 0 for a negative coefficient.
       Its subtraction from one produces the same category extension
       without a data-dependent branch. All arithmetic masks are unsigned. */
    uint32_t negative_mask = (amplitude >> (bits - 1)) - 1u;
    *value = (int)amplitude -
        (int)(negative_mask & ((1u << bits) - 1u));
    return 1;
}

/* The format-7 effort-3 profile emits fixed rANS models. Keep its common
   symbol path in the coefficient decoder so it can share state and bounds
   checks with the surrounding loop. Adaptive streams use the general API. */
static inline int decode_rans_payload_symbol(
    N148RansDecoder *decoder, const N148RansModel *model, uint8_t *symbol) {
    if (decoder && decoder->adaptive_models)
        return n148_rans_decode_symbol_with_model(decoder, model, symbol);
    if (!decoder || !model || !symbol || !decoder->valid ||
        model->used_symbols == 0) return 0;
    uint32_t slot = decoder->state & (N148_RANS_TOTAL - 1u);
    uint8_t decoded = model->symbol_for_slot[slot];
    uint32_t pair = model->decode_pair[decoded];
    uint32_t frequency = pair & 0xffffu;
    uint32_t cumulative = pair >> 16;
    /* parse_rans_models/read_rich_models prepare and validate every slot:
       its symbol always has a positive frequency and contains this slot. */
    decoder->state = frequency *
        (decoder->state >> N148_RANS_SCALE_BITS) + slot - cumulative;
    while (decoder->state < N148_RANS_LOWER_BOUND) {
        if (decoder->next == decoder->end) {
            decoder->valid = 0;
            return 0;
        }
        decoder->state = (decoder->state << 8) | *decoder->next++;
    }
    *symbol = decoded;
    return 1;
}

/* When the directional coefficient syntax uses fixed models, keep the rANS
   state local so the compiler does not have to reload it around amplitude-
   reader accesses. Model metadata was validated before this path is selected,
   so the per-symbol adaptive/model checks are unnecessary here. */
typedef struct {
    uint32_t state;
    const uint8_t *next;
    const uint8_t *end;
    uint32_t symbols_remaining;
} FixedRansDecoder;

static inline int decode_context_band(int position) {
    return (position >= 6) + (position >= 15) + (position >= 28);
}

/* Coefficient units are at most 64 entries. Their AC band is selected once
   per symbol; a compact table replaces three comparisons in the fixed path. */
#if CONTEXT_DC_MODELS != 6 || CONTEXT_ACTIVITY_BUCKETS != 2
#error fixed_ac_model_base must match the context model layout
#endif
static const uint8_t fixed_ac_model_base[64] = {
    6, 6, 6, 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10,
    10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
};

static void prepare_fixed_ac_models(
    const N148RansModel *models, int plane_class,
    const N148RansModel *ac_models[64][2]) {
    for (int position = 1; position < 64; position++) {
        int base = fixed_ac_model_base[position] +
            plane_class * CONTEXT_AC_MODELS / 2;
        ac_models[position][0] = &models[base];
        ac_models[position][1] = &models[base + 1];
    }
}

static inline int decode_fixed_rans_payload_symbol(
    FixedRansDecoder *decoder, const N148RansModel *model, uint8_t *symbol) {
    if (decoder->symbols_remaining == 0) return 0;
    uint32_t slot = decoder->state & (N148_RANS_TOTAL - 1u);
    uint8_t decoded = model->symbol_for_slot[slot];
    uint32_t pair = model->decode_pair[decoded];
    uint32_t frequency = pair & 0xffffu;
    uint32_t cumulative = pair >> 16;
    decoder->state = frequency *
        (decoder->state >> N148_RANS_SCALE_BITS) + slot - cumulative;
    /* A normalized state is at least 2^23. With a 12-bit slot and positive
       frequency, the updated state is at least 2^11, so at most two input
       bytes can be needed for renormalization. */
    if (decoder->state < N148_RANS_LOWER_BOUND) {
        if (decoder->next == decoder->end) return 0;
        decoder->state = (decoder->state << 8) | *decoder->next++;
        if (decoder->state < N148_RANS_LOWER_BOUND) {
            if (decoder->next == decoder->end) return 0;
            decoder->state = (decoder->state << 8) | *decoder->next++;
        }
    }
    decoder->symbols_remaining--;
    *symbol = decoded;
    return 1;
}

static void fixed_rans_begin(const N148RansDecoder *source,
                             uint32_t symbols_remaining,
                             FixedRansDecoder *fixed) {
    fixed->state = source->state;
    fixed->next = source->next;
    fixed->end = source->end;
    fixed->symbols_remaining = symbols_remaining;
}

static void fixed_rans_commit(const FixedRansDecoder *fixed,
                              N148RansDecoder *destination) {
    destination->state = fixed->state;
    destination->next = fixed->next;
}

static int parse_rans_models(const uint8_t *metadata, size_t metadata_size,
                             N148RansModel models[MAX_MODEL_COUNT],
                             int expected_model_count,
                             size_t *bytes_consumed) {
    ByteReader reader;
    reader_init(&reader, metadata, metadata_size);
    if (reader_u8(&reader) != ENTROPY_METADATA_REVISION_BASE ||
        reader_u8(&reader) != ENTROPY_CODER_RANS ||
        reader_u8(&reader) != expected_model_count ||
        reader_u8(&reader) != N148_RANS_SCALE_BITS) return 0;
    for (int model = 0; model < expected_model_count; model++)
        if (!read_model(&reader, &models[model])) return 0;
    if (!reader.valid || !bytes_consumed) return 0;
    *bytes_consumed = reader.position;
    return 1;
}

static int allocate_coefficients(int width, int height,
                                 N148CoeffPlane *coefficients) {
    size_t blocks_x = (size_t)(width / 8 + (width % 8 != 0));
    size_t blocks_y = (size_t)(height / 8 + (height % 8 != 0));
    if (blocks_y != 0 && blocks_x > SIZE_MAX / blocks_y) return 0;
    size_t count = blocks_x * blocks_y;
    if (count == 0 || count > LONG_MAX ||
        count > SIZE_MAX / (64 * sizeof(short)) ||
        count > SIZE_MAX / sizeof(*coefficients->nonzero_masks))
        return 0;
    size_t coefficient_bytes = count * 64 * sizeof(short);
    size_t mask_bytes = count * sizeof(*coefficients->nonzero_masks);
    if (coefficient_bytes > SIZE_MAX - mask_bytes) return 0;
    coefficients->coefficients = (short *) calloc(
        1, coefficient_bytes + mask_bytes);
    if (!coefficients->coefficients) return 0;
    coefficients->nonzero_masks = (unsigned long long *)
        ((uint8_t *) coefficients->coefficients + coefficient_bytes);
    coefficients->count = (long) count;
    return 1;
}

static int decode_rans_plane(N148RansDecoder *decoder, BitReader *bits,
                             const N148RansModel *models,
                             int blocks_x, int plane_class, int use_context,
                             int absolute_dc,
                             uint32_t symbol_count, uint32_t *decoded_symbols,
                             N148CoeffPlane *coefficients,
                             N148ContextTrace *trace) {
    int previous_dc = 0;
    int previous_dc_category = 0;
    int base_dc_model = plane_class ? BASE_DC_CHROMA_MODEL : BASE_DC_LUMA_MODEL;
    int base_ac_model = plane_class ? BASE_AC_CHROMA_MODEL : BASE_AC_LUMA_MODEL;
    for (long block = 0; block < coefficients->count; block++) {
        short *values = coefficients->coefficients + block * 64;
        uint8_t category;
        int difference;
        int model = use_context ?
            context_dc_model(plane_class, previous_dc_category) :
            base_dc_model;
        if (*decoded_symbols >= symbol_count ||
            !context_trace_add(trace, model) ||
            !decode_rans_payload_symbol(
                decoder, &models[model], &category) ||
            category > 16 ||
            !decode_amplitude(bits, category, &difference)) return 0;
        (*decoded_symbols)++;
        int dc = absolute_dc ? difference : previous_dc + difference;
        if (dc < SHRT_MIN || dc > SHRT_MAX) return 0;
        values[0] = (short) dc;
        if (dc != 0) coefficients->nonzero_masks[block] |= 1ull;
        previous_dc = dc;
        previous_dc_category = category;

        int position = 1;
        int previous_ac_category = 0;
        while (position < 64) {
            uint8_t symbol;
            model = use_context ? context_ac_model(
                coefficients, block, blocks_x, plane_class,
                position, previous_ac_category) : base_ac_model;
            if (*decoded_symbols >= symbol_count ||
                !context_trace_add(trace, model) ||
                !decode_rans_payload_symbol(
                    decoder, &models[model], &symbol)) return 0;
            (*decoded_symbols)++;
            if (symbol == 0) break;
            if (symbol == 0xf0u) {
                position += 16;
                if (position > 64) return 0;
                previous_ac_category = 0;
                continue;
            }
            int run = symbol >> 4;
            int coefficient_bits = symbol & 15;
            if (coefficient_bits == 0) return 0;
            position += run;
            if (position >= 64) return 0;
            int value;
            if (!decode_amplitude(bits, coefficient_bits, &value) ||
                value < SHRT_MIN || value > SHRT_MAX) return 0;
            values[position] = (short) value;
            coefficients->nonzero_masks[block] |= 1ull << position;
            position++;
            previous_ac_category = coefficient_bits;
        }
    }
    return 1;
}

static int decode_directional_coefficient_unit(
    N148RansDecoder *decoder, BitReader *bits,
    const N148RansModel *models, int plane_class,
    int use_context, uint32_t symbol_count, uint32_t *decoded_symbols,
    N148CoeffPlane *coefficients, long block, const short *left_values,
    const short *top_values, int packed_offset, int length,
    int *previous_dc_category) {
    short *values = coefficients->coefficients + block * 64 + packed_offset;
    int base_dc_model = plane_class ? BASE_DC_CHROMA_MODEL : BASE_DC_LUMA_MODEL;
    int base_ac_model = plane_class ? BASE_AC_CHROMA_MODEL : BASE_AC_LUMA_MODEL;
    int model = use_context ?
        context_dc_model(plane_class, *previous_dc_category) : base_dc_model;
    uint8_t category;
    int value;
    if (*decoded_symbols >= symbol_count ||
        !decode_rans_payload_symbol(
            decoder, &models[model], &category) ||
        category > 16 || !decode_amplitude(bits, category, &value) ||
        value < SHRT_MIN || value > SHRT_MAX) return 0;
    values[0] = (short) value;
    if (value != 0)
        coefficients->nonzero_masks[block] |= 1ull << packed_offset;
    *previous_dc_category = category;
    (*decoded_symbols)++;

    int position = 1;
    int previous_ac_category = 0;
    while (position < length) {
        if (use_context) {
            int packed_position = packed_offset + position;
            int active = previous_ac_category >= 3 ||
                (left_values &&
                 (left_values[packed_position] <= -4 ||
                  left_values[packed_position] >= 4)) ||
                (top_values &&
                 (top_values[packed_position] <= -4 ||
                  top_values[packed_position] >= 4));
            model = CONTEXT_DC_MODELS +
                ((plane_class * CONTEXT_BANDS + decode_context_band(position)) *
                 CONTEXT_ACTIVITY_BUCKETS) + active;
        } else {
            model = base_ac_model;
        }
        uint8_t symbol;
        if (*decoded_symbols >= symbol_count ||
            !decode_rans_payload_symbol(
                decoder, &models[model], &symbol)) return 0;
        (*decoded_symbols)++;
        if (symbol == 0) break;
        if (symbol == 0xf0u) {
            position += 16;
            if (position > length) return 0;
            previous_ac_category = 0;
            continue;
        }
        int run = symbol >> 4;
        int coefficient_bits = symbol & 15;
        if (coefficient_bits == 0) return 0;
        position += run;
        if (position >= length ||
            !decode_amplitude(bits, coefficient_bits, &value) ||
            value < SHRT_MIN || value > SHRT_MAX) return 0;
        values[position] = (short) value;
        coefficients->nonzero_masks[block] |=
            1ull << (packed_offset + position);
        position++;
        previous_ac_category = coefficient_bits;
    }
    return 1;
}

static int decode_fixed_directional_coefficient_unit(
    FixedRansDecoder *decoder, BitReader *bits,
    const N148RansModel *models, int plane_class, int use_context,
    const N148RansModel *ac_models[64][2],
    N148CoeffPlane *coefficients, long block, uint64_t left_activity,
    uint64_t top_activity, uint64_t *block_activity,
    int packed_offset, int length,
    int *previous_dc_category) {
    short *values = coefficients->coefficients + block * 64 + packed_offset;
    int base_dc_model = plane_class ? BASE_DC_CHROMA_MODEL : BASE_DC_LUMA_MODEL;
    int base_ac_model = plane_class ? BASE_AC_CHROMA_MODEL : BASE_AC_LUMA_MODEL;
    int model = use_context ?
        context_dc_model(plane_class, *previous_dc_category) : base_dc_model;
    uint8_t category;
    int value;
    if (!decode_fixed_rans_payload_symbol(
            decoder, &models[model], &category) ||
        category > 16 || !decode_amplitude(bits, category, &value) ||
        value < SHRT_MIN || value > SHRT_MAX) return 0;
    values[0] = (short) value;
    if (value != 0)
        coefficients->nonzero_masks[block] |= 1ull << packed_offset;
    if (category >= 3)
        *block_activity |= 1ull << packed_offset;
    *previous_dc_category = category;

    int position = 1;
    int previous_ac_category = 0;
    while (position < length) {
        const N148RansModel *ac_model;
        if (use_context) {
            int packed_position = packed_offset + position;
            int active = previous_ac_category >= 3 ||
                (((left_activity | top_activity) >> packed_position) & 1u);
            ac_model = ac_models[position][active];
        } else {
            ac_model = &models[base_ac_model];
        }
        uint8_t symbol;
        if (!decode_fixed_rans_payload_symbol(
                decoder, ac_model, &symbol)) return 0;
        if (symbol == 0) break;
        if (symbol == 0xf0u) {
            position += 16;
            if (position > length) return 0;
            previous_ac_category = 0;
            continue;
        }
        int run = symbol >> 4;
        int coefficient_bits = symbol & 15;
        if (coefficient_bits == 0) return 0;
        position += run;
        if (position >= length ||
            !decode_amplitude(bits, coefficient_bits, &value) ||
            value < SHRT_MIN || value > SHRT_MAX) return 0;
        values[position] = (short) value;
        coefficients->nonzero_masks[block] |=
            1ull << (packed_offset + position);
        if (coefficient_bits >= 3)
            *block_activity |= 1ull << (packed_offset + position);
        position++;
        previous_ac_category = coefficient_bits;
    }
    return 1;
}

static int decode_directional_coefficient_plane(
    N148RansDecoder *decoder, BitReader *bits,
    const N148RansModel *models, const uint8_t *splits, int blocks_x,
    int plane_class, int use_context, uint32_t symbol_count,
    uint32_t *decoded_symbols, N148CoeffPlane *coefficients,
    FixedRansDecoder *fixed) {
    if (!decoder || !bits || !models || !splits || blocks_x <= 0 ||
        !decoded_symbols || !coefficients || !coefficients->coefficients)
        return 0;
    /* A coefficient has magnitude >= 4 exactly when its amplitude category
       is at least three. Cache that fact for the two causal neighbors so the
       fixed-model decoder does not reload and compare both coefficients at
       every context decision. */
    uint64_t *activity_masks = NULL;
    const N148RansModel *fixed_ac_models[64][2];
    if (fixed && use_context) {
        activity_masks = (uint64_t *) malloc(
            (size_t) coefficients->count * sizeof(*activity_masks));
        if (!activity_masks) return 0;
        prepare_fixed_ac_models(models, plane_class, fixed_ac_models);
    }
    int previous_dc_category = 0;
    int block_x = 0;
    for (long block = 0; block < coefficients->count; block++) {
        const short *left_values = block_x ?
            coefficients->coefficients + (block - 1) * 64 : NULL;
        const short *top_values = block >= blocks_x ?
            coefficients->coefficients + (block - blocks_x) * 64 : NULL;
        int parts = splits[block] ? N148_INTRA_MODE_SLOTS_PER_BLOCK : 1;
        int length = splits[block] ? 16 : 64;
        uint64_t block_activity = 0;
        uint64_t left_activity = activity_masks && block_x ?
            activity_masks[block - 1] : 0;
        uint64_t top_activity = activity_masks && block >= blocks_x ?
            activity_masks[block - blocks_x] : 0;
        for (int part = 0; part < parts; part++) {
            int success = fixed ?
                decode_fixed_directional_coefficient_unit(
                    fixed, bits, models, plane_class, use_context,
                    fixed_ac_models,
                    coefficients, block, left_activity, top_activity,
                    &block_activity,
                    part * 16, length,
                    &previous_dc_category) :
                decode_directional_coefficient_unit(
                    decoder, bits, models, plane_class, use_context,
                    symbol_count, decoded_symbols, coefficients, block,
                    left_values, top_values, part * 16, length,
                    &previous_dc_category);
            if (!success) {
                free(activity_masks);
                return 0;
            }
        }
        if (activity_masks) activity_masks[block] = block_activity;
        if (++block_x == blocks_x) block_x = 0;
    }
    free(activity_masks);
    return 1;
}

static int decode_large_transform_coefficient_unit(
    N148RansDecoder *decoder, BitReader *bits,
    const N148RansModel *models, int use_context,
    uint32_t symbol_count, uint32_t *decoded_symbols,
    int *previous_dc_category, short *values,
    unsigned long long masks[16], int length) {
    if (!values || (length != 16 * 16 && length != 32 * 32)) return 0;
    int model = use_context ?
        context_dc_model(0, *previous_dc_category) : BASE_DC_LUMA_MODEL;
    uint8_t category;
    int value;
    if (*decoded_symbols >= symbol_count ||
        !decode_rans_payload_symbol(
            decoder, &models[model], &category) ||
        category > 16 || !decode_amplitude(bits, category, &value) ||
        value < SHRT_MIN || value > SHRT_MAX) return 0;
    values[0] = (short) value;
    if (value != 0) masks[0] |= 1ull;
    *previous_dc_category = category;
    (*decoded_symbols)++;
    int position = 1;
    int previous_ac_category = 0;
    while (position < length) {
        model = use_context ? CONTEXT_DC_MODELS +
            decode_context_band(position) * CONTEXT_ACTIVITY_BUCKETS +
            (previous_ac_category >= 3) : BASE_AC_LUMA_MODEL;
        uint8_t symbol;
        if (*decoded_symbols >= symbol_count ||
            !decode_rans_payload_symbol(
                decoder, &models[model], &symbol)) return 0;
        (*decoded_symbols)++;
        if (symbol == 0) break;
        if (symbol == 0xf0u) {
            position += 16;
            if (position > length) return 0;
            previous_ac_category = 0;
            continue;
        }
        int run = symbol >> 4;
        int coefficient_bits = symbol & 15;
        if (coefficient_bits == 0) return 0;
        position += run;
        if (position >= length ||
            !decode_amplitude(bits, coefficient_bits, &value) ||
            value < SHRT_MIN || value > SHRT_MAX) return 0;
        values[position] = (short) value;
        masks[position >> 6] |= 1ull << (position & 63);
        position++;
        previous_ac_category = coefficient_bits;
    }
    return 1;
}

static int decode_fixed_large_transform_coefficient_unit(
    FixedRansDecoder *decoder, BitReader *bits,
    const N148RansModel *models, int use_context,
    int *previous_dc_category, short *values,
    unsigned long long masks[16], int length) {
    if (!values || (length != 16 * 16 && length != 32 * 32)) return 0;
    int model = use_context ?
        context_dc_model(0, *previous_dc_category) : BASE_DC_LUMA_MODEL;
    uint8_t category;
    int value;
    if (!decode_fixed_rans_payload_symbol(
            decoder, &models[model], &category) ||
        category > 16 || !decode_amplitude(bits, category, &value) ||
        value < SHRT_MIN || value > SHRT_MAX) return 0;
    values[0] = (short) value;
    if (value != 0) masks[0] |= 1ull;
    *previous_dc_category = category;
    int position = 1;
    int previous_ac_category = 0;
    while (position < length) {
        model = use_context ? CONTEXT_DC_MODELS +
            decode_context_band(position) * CONTEXT_ACTIVITY_BUCKETS +
            (previous_ac_category >= 3) : BASE_AC_LUMA_MODEL;
        uint8_t symbol;
        if (!decode_fixed_rans_payload_symbol(
                decoder, &models[model], &symbol)) return 0;
        if (symbol == 0) break;
        if (symbol == 0xf0u) {
            position += 16;
            if (position > length) return 0;
            previous_ac_category = 0;
            continue;
        }
        int run = symbol >> 4;
        int coefficient_bits = symbol & 15;
        if (coefficient_bits == 0) return 0;
        position += run;
        if (position >= length ||
            !decode_amplitude(bits, coefficient_bits, &value) ||
            value < SHRT_MIN || value > SHRT_MAX) return 0;
        values[position] = (short) value;
        masks[position >> 6] |= 1ull << (position & 63);
        position++;
        previous_ac_category = coefficient_bits;
    }
    return 1;
}

static uint64_t coefficient_activity_mask(const short values[64],
                                          uint64_t nonzero_mask) {
    uint64_t activity = 0;
    while (nonzero_mask) {
        int position = 0;
#if defined(__GNUC__) || defined(__clang__)
        position = __builtin_ctzll(nonzero_mask);
#else
        uint64_t probe = nonzero_mask;
        while (!(probe & 1u)) { position++; probe >>= 1; }
#endif
        int value = values[position];
        if (value <= -4 || value >= 4)
            activity |= 1ull << position;
        nonzero_mask &= nonzero_mask - 1;
    }
    return activity;
}

static int decode_variable_luma_coefficient_plane(
    N148RansDecoder *decoder, BitReader *bits,
    const N148RansModel *models, const uint8_t *splits,
    int blocks_x, int blocks_y, int use_context, uint32_t symbol_count,
    uint32_t *decoded_symbols, const N148TransformMap *transform_map,
    N148CoeffPlane *coefficients, FixedRansDecoder *fixed, int dct32) {
    if (!decoder || !bits || !models || !splits || blocks_x <= 0 ||
        blocks_y <= 0 || !decoded_symbols || !coefficients ||
        !coefficients->coefficients ||
        coefficients->count != (long) blocks_x * blocks_y ||
        !n148_luma_transform_map_validate_extended(transform_map, dct32))
        return 0;
    uint64_t *activity_masks = NULL;
    const N148RansModel *fixed_ac_models[64][2];
    if (fixed && use_context) {
        activity_masks = (uint64_t *) malloc(
            (size_t) coefficients->count * sizeof(*activity_masks));
        if (!activity_masks) return 0;
        prepare_fixed_ac_models(models, 0, fixed_ac_models);
    }
    int previous_dc_category = 0;
    for (int macro_y = 0; macro_y < transform_map->rows[0]; macro_y++) {
        for (int macro_x = 0; macro_x < transform_map->columns[0];
             macro_x++) {
            size_t transform_index = (size_t) macro_y *
                (size_t) transform_map->columns[0] + (size_t) macro_x;
            int first_x = macro_x * 2;
            int first_y = macro_y * 2;
            if (dct32 && n148_luma_transform_dct32_member(
                    transform_map, macro_x, macro_y)) {
                if (!n148_luma_transform_dct32_origin(
                        transform_map, macro_x, macro_y)) continue;
                short sequence[32 * 32] = {0};
                unsigned long long masks[16] = {0};
                int success = fixed ?
                    decode_fixed_large_transform_coefficient_unit(
                        fixed, bits, models, use_context,
                        &previous_dc_category, sequence, masks,
                        32 * 32) :
                    decode_large_transform_coefficient_unit(
                        decoder, bits, models, use_context, symbol_count,
                        decoded_symbols, &previous_dc_category, sequence, masks,
                        32 * 32);
                if (!success) goto failure;
                for (int cell = 0; cell < 16; cell++) {
                    int block_x = first_x + (cell & 3);
                    int block_y = first_y + (cell >> 2);
                    if (block_x >= blocks_x || block_y >= blocks_y)
                        goto failure;
                    long block = (long) block_y * blocks_x + block_x;
                    if (splits[block]) goto failure;
                    memcpy(coefficients->coefficients + block * 64,
                           sequence + cell * 64,
                           64 * sizeof(*sequence));
                    coefficients->nonzero_masks[block] = masks[cell];
                    if (activity_masks)
                        activity_masks[block] = coefficient_activity_mask(
                            sequence + cell * 64, masks[cell]);
                }
                continue;
            }
            if (transform_map->strategies[transform_index] ==
                N148_TRANSFORM_DCT16) {
                short sequence[16 * 16] = {0};
                unsigned long long masks[16] = {0};
                int success = fixed ?
                    decode_fixed_large_transform_coefficient_unit(
                        fixed, bits, models, use_context,
                        &previous_dc_category, sequence, masks,
                        16 * 16) :
                    decode_large_transform_coefficient_unit(
                        decoder, bits, models, use_context, symbol_count,
                        decoded_symbols, &previous_dc_category, sequence, masks,
                        16 * 16);
                if (!success) goto failure;
                for (int cell = 0; cell < 4; cell++) {
                    int block_x = first_x + (cell & 1);
                    int block_y = first_y + (cell >> 1);
                    if (block_x >= blocks_x || block_y >= blocks_y)
                        goto failure;
                    long block = (long) block_y * blocks_x + block_x;
                    if (splits[block]) goto failure;
                    memcpy(coefficients->coefficients + block * 64,
                           sequence + cell * 64,
                           64 * sizeof(*sequence));
                    coefficients->nonzero_masks[block] = masks[cell];
                    if (activity_masks)
                        activity_masks[block] = coefficient_activity_mask(
                            sequence + cell * 64, masks[cell]);
                }
                continue;
            }
            for (int cell_y = 0; cell_y < 2; cell_y++) {
                int block_y = first_y + cell_y;
                if (block_y >= blocks_y) continue;
                for (int cell_x = 0; cell_x < 2; cell_x++) {
                    int block_x = first_x + cell_x;
                    if (block_x >= blocks_x) continue;
                    long block = (long) block_y * blocks_x + block_x;
                    int parts = splits[block] ?
                        N148_INTRA_MODE_SLOTS_PER_BLOCK : 1;
                    int length = splits[block] ? 16 : 64;
                    const short *left_values = block_x ?
                        coefficients->coefficients + (block - 1) * 64 : NULL;
                    const short *top_values = block_y ?
                        coefficients->coefficients +
                            (block - blocks_x) * 64 : NULL;
                    uint64_t block_activity = 0;
                    uint64_t left_activity = activity_masks && block_x ?
                        activity_masks[block - 1] : 0;
                    uint64_t top_activity = activity_masks && block_y ?
                        activity_masks[block - blocks_x] : 0;
                    for (int part = 0; part < parts; part++) {
                        int success = fixed ?
                            decode_fixed_directional_coefficient_unit(
                                fixed, bits, models, 0, use_context,
                                fixed_ac_models,
                                coefficients, block, left_activity,
                                top_activity, &block_activity,
                                part * 16,
                                length, &previous_dc_category) :
                            decode_directional_coefficient_unit(
                                decoder, bits, models, 0, use_context,
                                symbol_count, decoded_symbols, coefficients,
                                block, left_values, top_values, part * 16,
                                length, &previous_dc_category);
                        if (!success) goto failure;
                    }
                    if (activity_masks)
                        activity_masks[block] = block_activity;
                }
            }
        }
    }
    free(activity_masks);
    return 1;
failure:
    free(activity_masks);
    return 0;
}

static int decode_rich_coefficient_unit(
    N148RansDecoder *decoder, BitReader *bits,
    const N148RansModel *models, int blocks_x, int plane_class,
    uint32_t symbol_count, uint32_t *decoded_symbols,
    N148CoeffPlane *coefficients, long block, int packed_offset, int length,
    int size_class, int prediction_mode, int *previous_dc_category) {
    short *values = coefficients->coefficients + block * 64 + packed_offset;
    const short *left = block % blocks_x ?
        coefficients->coefficients + (block - 1) * 64 + packed_offset : NULL;
    const short *above = block >= blocks_x ?
        coefficients->coefficients + (block - blocks_x) * 64 +
            packed_offset : NULL;
    int luma_ac_base = RICH_LUMA_DC_MODELS +
        (size_class * RICH_PREDICTION_CLASSES +
         rich_prediction_class(prediction_mode)) *
            RICH_POSITION_BUCKETS * RICH_ACTIVITY_BUCKETS;
    int chroma_ac_base = RICH_LUMA_DC_MODELS + RICH_LUMA_AC_MODELS +
        RICH_CHROMA_DC_MODELS;
    int model = plane_class ?
        rich_chroma_dc_model(*previous_dc_category) :
        rich_luma_dc_model(
            size_class, prediction_mode, *previous_dc_category);
    uint8_t category;
    int value;
    if (*decoded_symbols >= symbol_count ||
        !decode_rans_payload_symbol(
            decoder, &models[model], &category) ||
        category > 16 || !decode_amplitude(bits, category, &value) ||
        value < SHRT_MIN || value > SHRT_MAX) return 0;
    values[0] = (short) value;
    if (value != 0)
        coefficients->nonzero_masks[block] |= 1ull << packed_offset;
    *previous_dc_category = category;
    (*decoded_symbols)++;

    int position = 1;
    int previous_ac_category = 0;
    int previous_magnitude = 0;
    while (position < length) {
        if (plane_class) {
            int active = previous_ac_category >= 3;
            if (!active && left) {
                int neighbor = left[position];
                active = neighbor <= -4 || neighbor >= 4;
            }
            if (!active && above) {
                int neighbor = above[position];
                active = neighbor <= -4 || neighbor >= 4;
            }
            model = chroma_ac_base +
                decode_context_band(position) * CONTEXT_ACTIVITY_BUCKETS + active;
        } else {
            int magnitude_sum = previous_magnitude;
            if (left) {
                int neighbor = left[position];
                magnitude_sum += neighbor < 0 ? -neighbor : neighbor;
            }
            if (above) {
                int neighbor = above[position];
                magnitude_sum += neighbor < 0 ? -neighbor : neighbor;
            }
            int activity = magnitude_sum == 0 ? 0 :
                (magnitude_sum <= 3 ? 1 : 2);
            model = luma_ac_base +
                rich_position_bucket(position) * RICH_ACTIVITY_BUCKETS +
                activity;
        }
        uint8_t symbol;
        if (*decoded_symbols >= symbol_count ||
            !decode_rans_payload_symbol(
                decoder, &models[model], &symbol)) return 0;
        (*decoded_symbols)++;
        if (symbol == 0) break;
        if (symbol == 0xf0u) {
            position += 16;
            if (position > length) return 0;
            previous_ac_category = 0;
            previous_magnitude = 0;
            continue;
        }
        int run = symbol >> 4;
        int coefficient_bits = symbol & 15;
        if (coefficient_bits == 0) return 0;
        position += run;
        if (position >= length ||
            !decode_amplitude(bits, coefficient_bits, &value) ||
            value < SHRT_MIN || value > SHRT_MAX) return 0;
        values[position] = (short) value;
        coefficients->nonzero_masks[block] |=
            1ull << (packed_offset + position);
        position++;
        previous_ac_category = coefficient_bits;
        previous_magnitude = value < 0 ? -value : value;
    }
    return 1;
}

static int decode_rich_coefficient_plane(
    N148RansDecoder *decoder, BitReader *bits,
    const N148RansModel *models, const uint8_t *splits,
    const uint8_t *modes, int blocks_x, int plane_class,
    uint32_t symbol_count, uint32_t *decoded_symbols,
    N148CoeffPlane *coefficients) {
    if (!decoder || !bits || !models || !splits || !modes ||
        blocks_x <= 0 || !decoded_symbols || !coefficients ||
        !coefficients->coefficients) return 0;
    int previous_dc_category = 0;
    for (long block = 0; block < coefficients->count; block++) {
        int parts = splits[block] ? N148_INTRA_MODE_SLOTS_PER_BLOCK : 1;
        int length = splits[block] ? 16 : 64;
        int size_class = splits[block] ? 0 : 1;
        for (int part = 0; part < parts; part++) {
            int mode = modes[block * N148_INTRA_MODE_SLOTS_PER_BLOCK + part];
            if (!decode_rich_coefficient_unit(
                    decoder, bits, models, blocks_x, plane_class,
                    symbol_count, decoded_symbols, coefficients, block,
                    part * 16, length, size_class, mode,
                    &previous_dc_category)) return 0;
        }
    }
    return 1;
}

static int decode_rich_large_coefficient_unit(
    N148RansDecoder *decoder, BitReader *bits,
    const N148RansModel *models, uint32_t symbol_count,
    uint32_t *decoded_symbols, int size_class, int prediction_mode,
    int *previous_dc_category, short *values,
    unsigned long long masks[16], int length) {
    if (!values || (length != 16 * 16 && length != 32 * 32)) return 0;
    int model = rich_luma_dc_model(
        size_class, prediction_mode, *previous_dc_category);
    uint8_t category;
    int value;
    if (*decoded_symbols >= symbol_count ||
        !decode_rans_payload_symbol(
            decoder, &models[model], &category) ||
        category > 16 || !decode_amplitude(bits, category, &value) ||
        value < SHRT_MIN || value > SHRT_MAX) return 0;
    values[0] = (short) value;
    if (value != 0) masks[0] |= 1ull;
    *previous_dc_category = category;
    (*decoded_symbols)++;
    int position = 1;
    int previous_magnitude = 0;
    while (position < length) {
        int activity = previous_magnitude == 0 ? 0 :
            (previous_magnitude <= 3 ? 1 : 2);
        model = rich_luma_ac_model(
            size_class, prediction_mode, position, activity);
        uint8_t symbol;
        if (*decoded_symbols >= symbol_count ||
            !decode_rans_payload_symbol(
                decoder, &models[model], &symbol)) return 0;
        (*decoded_symbols)++;
        if (symbol == 0) break;
        if (symbol == 0xf0u) {
            position += 16;
            if (position > length) return 0;
            previous_magnitude = 0;
            continue;
        }
        int run = symbol >> 4;
        int coefficient_bits = symbol & 15;
        if (coefficient_bits == 0) return 0;
        position += run;
        if (position >= length ||
            !decode_amplitude(bits, coefficient_bits, &value) ||
            value < SHRT_MIN || value > SHRT_MAX) return 0;
        values[position] = (short) value;
        masks[position >> 6] |= 1ull << (position & 63);
        position++;
        previous_magnitude = value < 0 ? -value : value;
    }
    return 1;
}

static int decode_rich_luma_coefficient_plane(
    N148RansDecoder *decoder, BitReader *bits,
    const N148RansModel *models, const uint8_t *splits,
    const uint8_t *modes, int blocks_x, int blocks_y,
    uint32_t symbol_count, uint32_t *decoded_symbols,
    const N148TransformMap *transform_map,
    N148CoeffPlane *coefficients) {
    if (!decoder || !bits || !models || !splits || !modes ||
        blocks_x <= 0 || blocks_y <= 0 || !decoded_symbols ||
        !coefficients || !coefficients->coefficients ||
        coefficients->count != (long) blocks_x * blocks_y ||
        !n148_luma_transform_map_validate_extended(transform_map, 1))
        return 0;
    int previous_dc_category = 0;
    for (int macro_y = 0; macro_y < transform_map->rows[0]; macro_y++) {
        for (int macro_x = 0; macro_x < transform_map->columns[0];
             macro_x++) {
            size_t transform_index = (size_t) macro_y *
                (size_t) transform_map->columns[0] + (size_t) macro_x;
            int first_x = macro_x * 2;
            int first_y = macro_y * 2;
            long first_block = (long) first_y * blocks_x + first_x;
            int mode = modes[first_block * N148_INTRA_MODE_SLOTS_PER_BLOCK];
            if (n148_luma_transform_dct32_member(
                    transform_map, macro_x, macro_y)) {
                if (!n148_luma_transform_dct32_origin(
                        transform_map, macro_x, macro_y)) continue;
                short sequence[32 * 32] = {0};
                unsigned long long masks[16] = {0};
                if (!decode_rich_large_coefficient_unit(
                        decoder, bits, models, symbol_count, decoded_symbols,
                        2, mode, &previous_dc_category, sequence, masks,
                        32 * 32))
                    return 0;
                for (int cell = 0; cell < 16; cell++) {
                    int block_x = first_x + (cell & 3);
                    int block_y = first_y + (cell >> 2);
                    if (block_x >= blocks_x || block_y >= blocks_y)
                        return 0;
                    long block = (long) block_y * blocks_x + block_x;
                    if (splits[block]) return 0;
                    memcpy(coefficients->coefficients + block * 64,
                           sequence + cell * 64,
                           64 * sizeof(*sequence));
                    coefficients->nonzero_masks[block] = masks[cell];
                }
                continue;
            }
            if (transform_map->strategies[transform_index] ==
                N148_TRANSFORM_DCT16) {
                short sequence[16 * 16] = {0};
                unsigned long long masks[16] = {0};
                if (!decode_rich_large_coefficient_unit(
                        decoder, bits, models, symbol_count, decoded_symbols,
                        2, mode, &previous_dc_category, sequence, masks,
                        16 * 16))
                    return 0;
                for (int cell = 0; cell < 4; cell++) {
                    int block_x = first_x + (cell & 1);
                    int block_y = first_y + (cell >> 1);
                    if (block_x >= blocks_x || block_y >= blocks_y)
                        return 0;
                    long block = (long) block_y * blocks_x + block_x;
                    if (splits[block]) return 0;
                    memcpy(coefficients->coefficients + block * 64,
                           sequence + cell * 64,
                           64 * sizeof(*sequence));
                    coefficients->nonzero_masks[block] = masks[cell];
                }
                continue;
            }
            for (int cell_y = 0; cell_y < 2; cell_y++) {
                int block_y = first_y + cell_y;
                if (block_y >= blocks_y) continue;
                for (int cell_x = 0; cell_x < 2; cell_x++) {
                    int block_x = first_x + cell_x;
                    if (block_x >= blocks_x) continue;
                    long block = (long) block_y * blocks_x + block_x;
                    int parts = splits[block] ?
                        N148_INTRA_MODE_SLOTS_PER_BLOCK : 1;
                    int length = splits[block] ? 16 : 64;
                    int size_class = splits[block] ? 0 : 1;
                    for (int part = 0; part < parts; part++) {
                        mode = modes[block *
                            N148_INTRA_MODE_SLOTS_PER_BLOCK + part];
                        if (!decode_rich_coefficient_unit(
                                decoder, bits, models, blocks_x, 0,
                                symbol_count, decoded_symbols, coefficients,
                                block, part * 16, length, size_class, mode,
                                &previous_dc_category)) return 0;
                    }
                }
            }
        }
    }
    return 1;
}

static int decode_prediction_plane(N148RansDecoder *decoder,
                                   const N148RansModel *models,
                                   uint8_t *modes, long count,
                                   int blocks_x, int plane_class,
                                   int coefficient_model_count,
                                   uint32_t symbol_count,
                                   uint32_t *decoded_symbols) {
    if (!decoder || !models || !modes || count <= 0 || blocks_x <= 0 ||
        !decoded_symbols) return 0;
    for (long block = 0; block < count; block++) {
        int model = prediction_mode_model(
            coefficient_model_count, plane_class, modes, block, blocks_x);
        uint8_t mode;
        if (*decoded_symbols >= symbol_count ||
            !decode_rans_payload_symbol(
                decoder, &models[model], &mode) ||
            mode >= N148_INTRA_MODE_COUNT) return 0;
        modes[block] = mode;
        (*decoded_symbols)++;
    }
    return 1;
}

static int decode_directional_prediction_plane(
    N148RansDecoder *decoder, const N148RansModel *models, uint8_t *modes,
    long block_count, int blocks_x, int plane_class,
    int coefficient_model_count, int allowed_modes, const uint8_t *splits,
    uint32_t symbol_count, uint32_t *decoded_symbols) {
    if (!decoder || !models || !modes || block_count <= 0 || blocks_x <= 0 ||
        allowed_modes < 1 ||
        allowed_modes > N148_PACKED_INTRA_MODE_COUNT ||
        !splits || !decoded_symbols) return 0;
    for (long block = 0; block < block_count; block++) {
        int parts = splits[block] ? N148_INTRA_MODE_SLOTS_PER_BLOCK : 1;
        int mode_limit = allowed_modes;
        for (int part = 0; part < parts; part++) {
            int model = directional_prediction_mode_model(
                coefficient_model_count, plane_class, modes, block, part,
                blocks_x);
            uint8_t symbol;
            if (*decoded_symbols >= symbol_count ||
                !decode_rans_payload_symbol(
                    decoder, &models[model], &symbol) ||
                symbol >= mode_limit) return 0;
            int mode = directional_mode_from_signal(
                modes, block, part, blocks_x, symbol, allowed_modes);
            if (mode < 0 || mode >= mode_limit ||
                (splits[block] &&
                 n148_intra_reference_index(mode) != 0)) return 0;
            modes[block * N148_INTRA_MODE_SLOTS_PER_BLOCK + part] =
                (uint8_t) mode;
            (*decoded_symbols)++;
        }
        if (!splits[block]) {
            uint8_t mode = modes[block * N148_INTRA_MODE_SLOTS_PER_BLOCK];
            for (int part = 1; part < N148_INTRA_MODE_SLOTS_PER_BLOCK; part++)
                modes[block * N148_INTRA_MODE_SLOTS_PER_BLOCK + part] = mode;
        }
    }
    return 1;
}

static int decode_variable_luma_prediction_plane(
    N148RansDecoder *decoder, const N148RansModel *models, uint8_t *modes,
    long block_count, int blocks_x, int blocks_y,
    int coefficient_model_count, int allowed_modes, const uint8_t *splits,
    uint32_t symbol_count, uint32_t *decoded_symbols,
    const N148TransformMap *transform_map, int dct32) {
    if (!decoder || !models || !modes ||
        block_count != (long) blocks_x * blocks_y || blocks_x <= 0 ||
        blocks_y <= 0 || allowed_modes < 1 ||
        allowed_modes > N148_PACKED_INTRA_MODE_COUNT || !splits ||
        !decoded_symbols ||
        !n148_luma_transform_map_validate_extended(transform_map, dct32))
        return 0;
    for (int macro_y = 0; macro_y < transform_map->rows[0]; macro_y++) {
        for (int macro_x = 0; macro_x < transform_map->columns[0];
             macro_x++) {
            size_t transform_index = (size_t) macro_y *
                (size_t) transform_map->columns[0] + (size_t) macro_x;
            int first_x = macro_x * 2;
            int first_y = macro_y * 2;
            if (dct32 && n148_luma_transform_dct32_member(
                    transform_map, macro_x, macro_y)) {
                if (!n148_luma_transform_dct32_origin(
                        transform_map, macro_x, macro_y)) continue;
                long first_block = (long) first_y * blocks_x + first_x;
                int model = directional_prediction_mode_model(
                    coefficient_model_count, 0, modes, first_block, 0,
                    blocks_x);
                uint8_t symbol;
                if (*decoded_symbols >= symbol_count ||
                    !decode_rans_payload_symbol(
                        decoder, &models[model], &symbol) ||
                    symbol >= allowed_modes) return 0;
                int mode = directional_mode_from_signal(
                    modes, first_block, 0, blocks_x, symbol,
                    allowed_modes);
                if (mode < 0 || mode >= allowed_modes) return 0;
                (*decoded_symbols)++;
                for (int cell = 0; cell < 16; cell++) {
                    int block_x = first_x + (cell & 3);
                    int block_y = first_y + (cell >> 2);
                    long block = (long) block_y * blocks_x + block_x;
                    if (splits[block]) return 0;
                    for (int part = 0;
                         part < N148_INTRA_MODE_SLOTS_PER_BLOCK; part++)
                        modes[block * N148_INTRA_MODE_SLOTS_PER_BLOCK + part] =
                            (uint8_t) mode;
                }
                continue;
            }
            if (transform_map->strategies[transform_index] ==
                N148_TRANSFORM_DCT16) {
                long first_block = (long) first_y * blocks_x + first_x;
                int model = directional_prediction_mode_model(
                    coefficient_model_count, 0, modes, first_block, 0,
                    blocks_x);
                uint8_t symbol;
                if (*decoded_symbols >= symbol_count ||
                    !decode_rans_payload_symbol(
                        decoder, &models[model], &symbol) ||
                    symbol >= allowed_modes) return 0;
                int mode = directional_mode_from_signal(
                    modes, first_block, 0, blocks_x, symbol,
                    allowed_modes);
                if (mode < 0 || mode >= allowed_modes) return 0;
                (*decoded_symbols)++;
                for (int cell = 0; cell < 4; cell++) {
                    int block_x = first_x + (cell & 1);
                    int block_y = first_y + (cell >> 1);
                    if (block_x >= blocks_x || block_y >= blocks_y)
                        return 0;
                    long block = (long) block_y * blocks_x + block_x;
                    if (splits[block]) return 0;
                    for (int part = 0;
                         part < N148_INTRA_MODE_SLOTS_PER_BLOCK; part++)
                        modes[block * N148_INTRA_MODE_SLOTS_PER_BLOCK + part] =
                            (uint8_t) mode;
                }
                continue;
            }
            for (int cell_y = 0; cell_y < 2; cell_y++) {
                int block_y = first_y + cell_y;
                if (block_y >= blocks_y) continue;
                for (int cell_x = 0; cell_x < 2; cell_x++) {
                    int block_x = first_x + cell_x;
                    if (block_x >= blocks_x) continue;
                    long block = (long) block_y * blocks_x + block_x;
                    int parts = splits[block] ?
                        N148_INTRA_MODE_SLOTS_PER_BLOCK : 1;
                    for (int part = 0; part < parts; part++) {
                        int model = directional_prediction_mode_model(
                            coefficient_model_count, 0, modes, block, part,
                            blocks_x);
                        uint8_t symbol;
                        if (*decoded_symbols >= symbol_count ||
                            !decode_rans_payload_symbol(
                                decoder, &models[model], &symbol) ||
                            symbol >= allowed_modes) return 0;
                        int mode = directional_mode_from_signal(
                            modes, block, part, blocks_x, symbol,
                            allowed_modes);
                        if (mode < 0 || mode >= allowed_modes ||
                            (splits[block] &&
                             n148_intra_reference_index(mode) != 0))
                            return 0;
                        modes[block * N148_INTRA_MODE_SLOTS_PER_BLOCK + part] =
                            (uint8_t) mode;
                        (*decoded_symbols)++;
                    }
                    if (!splits[block]) {
                        uint8_t mode = modes[block *
                            N148_INTRA_MODE_SLOTS_PER_BLOCK];
                        for (int part = 1;
                             part < N148_INTRA_MODE_SLOTS_PER_BLOCK; part++)
                            modes[block *
                                N148_INTRA_MODE_SLOTS_PER_BLOCK + part] = mode;
                    }
                }
            }
        }
    }
    return 1;
}

static int decode_partition_map(
    N148RansDecoder *decoder, const N148RansModel *models, int model,
    uint32_t symbol_count, uint32_t *decoded_symbols,
    N148PartitionMap *map) {
    if (!decoder || !models || model < 0 || !decoded_symbols || !map ||
        !map->split || map->count == 0) return 0;
    for (size_t index = 0; index < map->count; index++) {
        uint8_t delta;
        uint8_t prediction = n148_partition_map_predict(map, index);
        if (*decoded_symbols >= symbol_count || prediction > 1 ||
            !decode_rans_payload_symbol(
                decoder, &models[model], &delta) || delta > 1) return 0;
        map->split[index] = delta ^ prediction;
        (*decoded_symbols)++;
    }
    return n148_partition_map_validate(map);
}

static int decode_variable_luma_partition_map(
    N148RansDecoder *decoder, const N148RansModel *models, int model,
    uint32_t symbol_count, uint32_t *decoded_symbols,
    const N148TransformMap *transform_map, N148PartitionMap *map,
    int dct32) {
    if (!decoder || !models || model < 0 || !decoded_symbols || !map ||
        !map->split || !transform_map ||
        !n148_luma_transform_map_validate_extended(transform_map, dct32) ||
        map->blocks_x[0] != transform_map->blocks_x[0] ||
        map->blocks_y[0] != transform_map->blocks_y[0]) return 0;
    for (int plane = 0; plane < 3; plane++) {
        int blocks_x = map->blocks_x[plane];
        int blocks_y = map->blocks_y[plane];
        size_t index = map->plane_offsets[plane];
        for (int row = 0; row < blocks_y; row++) {
            for (int column = 0; column < blocks_x; column++, index++) {
                if (plane == 0) {
                    int macro_x = column >> 1;
                    int macro_y = row >> 1;
                    size_t transform_index = (size_t) macro_y *
                        (size_t) transform_map->columns[0] +
                        (size_t) macro_x;
                    if ((dct32 && n148_luma_transform_dct32_member(
                            transform_map, macro_x, macro_y)) ||
                        transform_map->strategies[transform_index] ==
                            N148_TRANSFORM_DCT16) {
                        map->split[index] = 0;
                        continue;
                    }
                }
                uint8_t delta;
                uint8_t prediction = column ? map->split[index - 1] :
                    row ? map->split[index - (size_t) blocks_x] : 0;
                if (*decoded_symbols >= symbol_count || prediction > 1 ||
                    !decode_rans_payload_symbol(
                        decoder, &models[model], &delta) || delta > 1)
                    return 0;
                map->split[index] = delta ^ prediction;
                (*decoded_symbols)++;
            }
        }
    }
    return n148_partition_map_validate(map);
}

static int decode_segmentation_map(
    N148RansDecoder *decoder, const N148RansModel *models, int model,
    int width, int height, uint32_t symbol_count,
    uint32_t *decoded_symbols, N148SegmentationMap *map) {
    if (!decoder || !models || model < 0 || !decoded_symbols || !map ||
        !n148_segmentation_map_allocate(width, height, map)) return 0;
    for (size_t index = 0; index < map->count; index++) {
        uint8_t delta;
        uint8_t prediction = n148_segmentation_map_predict(map, index);
        if (*decoded_symbols >= symbol_count ||
            prediction >= N148_SEGMENT_COUNT ||
            !decode_rans_payload_symbol(
                decoder, &models[model], &delta) ||
            delta >= N148_SEGMENT_COUNT) return 0;
        map->levels[index] = (uint8_t)(
            (prediction + delta) & (N148_SEGMENT_COUNT - 1));
        (*decoded_symbols)++;
    }
    return n148_segmentation_map_validate(map);
}

static int decode_adaptive_map(N148RansDecoder *decoder,
                               const N148RansModel *models, int model,
                               int width, int height, uint32_t symbol_count,
                               uint32_t *decoded_symbols,
                               N148AdaptiveMap *map) {
    if (!decoder || !models || !decoded_symbols || !map || model < 0 ||
        !n148_adaptive_map_allocate(width, height, map)) return 0;
    for (size_t index = 0; index < map->count; index++) {
        uint8_t delta;
        uint8_t prediction = n148_adaptive_map_predict(map, index);
        if (*decoded_symbols >= symbol_count ||
            !decode_rans_payload_symbol(
                decoder, &models[model], &delta) ||
            delta >= N148_AQ_LEVEL_COUNT ||
            prediction >= N148_AQ_LEVEL_COUNT) return 0;
        map->levels[index] = (uint8_t)(
            (prediction + delta) & (N148_AQ_LEVEL_COUNT - 1));
        (*decoded_symbols)++;
    }
    return 1;
}

static int decode_transform_map(N148RansDecoder *decoder,
                                const N148RansModel *models, int model,
                                uint32_t symbol_count,
                                uint32_t *decoded_symbols,
                                N148TransformMap *map) {
    if (!decoder || !models || !decoded_symbols || !map || model < 0 ||
        !map->strategies || map->count == 0) return 0;
    for (size_t index = 0; index < map->count; index++) {
        uint8_t delta;
        uint8_t prediction = n148_transform_map_predict(map, index);
        if (*decoded_symbols >= symbol_count ||
            !decode_rans_payload_symbol(
                decoder, &models[model], &delta) ||
            delta >= N148_TRANSFORM_STRATEGY_COUNT ||
            prediction >= N148_TRANSFORM_STRATEGY_COUNT) return 0;
        map->strategies[index] = (uint8_t)(
            (prediction + delta) % N148_TRANSFORM_STRATEGY_COUNT);
        (*decoded_symbols)++;
    }
    return n148_transform_map_validate(map);
}

static int decode_luma_transform_map(
    N148RansDecoder *decoder, const N148RansModel *models, int model,
    uint32_t symbol_count, uint32_t *decoded_symbols,
    int dct32, N148TransformMap *map) {
    if (!decoder || !models || !decoded_symbols || !map || model < 0 ||
        !map->strategies || map->plane_offsets[1] == 0) return 0;
    for (size_t index = 0; index < map->plane_offsets[1]; index++) {
        uint8_t delta;
        uint8_t prediction = n148_transform_map_predict(map, index);
        if (*decoded_symbols >= symbol_count ||
            !decode_rans_payload_symbol(
                decoder, &models[model], &delta) ||
            delta >= N148_TRANSFORM_STRATEGY_COUNT ||
            prediction >= N148_TRANSFORM_STRATEGY_COUNT) return 0;
        map->strategies[index] = (uint8_t)(
            (prediction + delta) % N148_TRANSFORM_STRATEGY_COUNT);
        (*decoded_symbols)++;
    }
    return n148_luma_transform_map_validate_extended(map, dct32);
}

int n148_decode_format_2_coefficients(const uint8_t *metadata, size_t metadata_size,
                                const uint8_t *payload_data, size_t payload_size,
                                int width, int height, int chroma,
                                uint32_t features,
                                N148CoeffPlane coefficients[3],
                                N148ContextTrace *trace,
                                N148PredictionModes *prediction,
                                N148AdaptiveMap *adaptive_map,
                                N148TransformMap *transform_map) {
    uint8_t *decoded_modes = NULL;
    N148AdaptiveMap decoded_adaptive = {0};
    N148TransformMap decoded_transform = {0};
    if (!metadata || !payload_data || !coefficients || width <= 0 ||
        height <= 0 || !(features & N148_FEATURE_RANS) ||
        chroma < CHROMA_444 || chroma > CHROMA_420 ||
        (features & ~N148_FORMAT_2_SUPPORTED_FEATURES) ||
        ((features & (N148_FEATURE_CONTEXT | N148_FEATURE_INTRA |
                      N148_FEATURE_PERCEPTUAL_COLOR |
                      N148_FEATURE_ADAPTIVE_QUANT |
                      N148_FEATURE_VARIABLE_TRANSFORM |
                      N148_FEATURE_RDO |
                      N148_FEATURE_LOOP_FILTER)) &&
         !(features & N148_FEATURE_RANS)) ||
        ((features & N148_FEATURE_ADAPTIVE_QUANT) &&
         !(features & N148_FEATURE_INTRA)) ||
        ((features & N148_FEATURE_VARIABLE_TRANSFORM) &&
         !(features & N148_FEATURE_INTRA)) ||
        ((features & N148_FEATURE_RDO) &&
         !(features & N148_FEATURE_INTRA)) ||
        ((features & N148_FEATURE_LOOP_FILTER) &&
         !(features & N148_FEATURE_INTRA)))
        return 0;
    memset(coefficients, 0, 3 * sizeof(*coefficients));
    if (prediction) memset(prediction, 0, sizeof(*prediction));
    if (adaptive_map) memset(adaptive_map, 0, sizeof(*adaptive_map));
    if (transform_map) memset(transform_map, 0, sizeof(*transform_map));
    context_trace_init(trace);
    int use_context = (features & N148_FEATURE_CONTEXT) != 0;
    int use_intra = (features & N148_FEATURE_INTRA) != 0;
    int use_adaptive =
        (features & N148_FEATURE_ADAPTIVE_QUANT) != 0;
    int use_transform =
        (features & N148_FEATURE_VARIABLE_TRANSFORM) != 0;
    int coefficient_model_count = use_context ?
        CONTEXT_MODEL_COUNT : BASE_COEFFICIENT_MODEL_COUNT;
    int model_count = coefficient_model_count +
        (use_intra ? BLOCK_INTRA_MODELS : 0) +
        (use_adaptive ? ADAPTIVE_MAP_MODEL_COUNT : 0) +
        (use_transform ? TRANSFORM_MAP_MODEL_COUNT : 0);
    N148RansModel *models = (N148RansModel *) malloc(
        MAX_MODEL_COUNT * sizeof(*models));
    if (!models) return 0;
    size_t metadata_consumed = 0;
    if (!parse_rans_models(metadata, metadata_size, models, model_count,
                           &metadata_consumed) ||
        metadata_consumed != metadata_size)
        goto failure;

    int chroma_width, chroma_height;
    chroma_dimensions(chroma, width, height, &chroma_width, &chroma_height);
    if (!allocate_coefficients(width, height, &coefficients[0]) ||
        !allocate_coefficients(chroma_width, chroma_height, &coefficients[1]) ||
        !allocate_coefficients(chroma_width, chroma_height, &coefficients[2]))
        goto failure;

    ByteReader payload;
    reader_init(&payload, payload_data, payload_size);
    uint8_t payload_version = reader_u8(&payload);
    uint8_t plane_count = reader_u8(&payload);
    uint8_t mode_coder = reader_u8(&payload);
    uint8_t map_coders = reader_u8(&payload);
    uint8_t expected_payload_version = use_transform ?
        PAYLOAD_REVISION_VARIABLE_TRANSFORM : (use_adaptive ?
        PAYLOAD_REVISION_ADAPTIVE_QUANT :
        (use_intra ? PAYLOAD_REVISION_INTRA : PAYLOAD_REVISION_ENTROPY));
    if (payload_version != expected_payload_version ||
        plane_count != PLANE_COUNT ||
        mode_coder != (use_intra ? INTRA_MODE_CODER_RANS : 0) ||
        map_coders != ((use_adaptive ? ADAPTIVE_MAP_CODER_RANS : 0) |
                       (use_transform ? TRANSFORM_MAP_CODER_RANS : 0)))
        goto failure;
    uint32_t symbol_count = reader_u32(&payload);
    uint32_t rans_size = reader_u32(&payload);
    uint32_t amplitude_bits = reader_u32(&payload);
    uint32_t prediction_mode_count = use_intra ? reader_u32(&payload) : 0;
    uint32_t adaptive_map_count = use_adaptive ? reader_u32(&payload) : 0;
    uint32_t transform_map_count = use_transform ? reader_u32(&payload) : 0;
    if (amplitude_bits > UINT32_MAX - 7u) goto failure;
    uint32_t amplitude_size = (amplitude_bits + 7u) / 8u;
    const uint8_t *rans_stream = reader_bytes(&payload, rans_size);
    const uint8_t *amplitudes = reader_bytes(&payload, amplitude_size);
    size_t expected_modes = 0;
    if (use_intra) {
        if (!n148_intra_expected_modes(width, height, chroma,
                                        &expected_modes) ||
            prediction_mode_count != expected_modes) goto failure;
        decoded_modes = (uint8_t *) calloc(expected_modes, 1);
        if (!decoded_modes) goto failure;
    }
    if (use_adaptive) {
        size_t map_columns = (size_t)(width / N148_AQ_REGION_SIZE +
            (width % N148_AQ_REGION_SIZE != 0));
        size_t map_rows = (size_t)(height / N148_AQ_REGION_SIZE +
            (height % N148_AQ_REGION_SIZE != 0));
        if (map_rows == 0 || map_columns > SIZE_MAX / map_rows ||
            map_columns * map_rows != adaptive_map_count) goto failure;
    }
    if (use_transform &&
        (!n148_transform_map_allocate(width, height, chroma,
                                      &decoded_transform) ||
         decoded_transform.count != transform_map_count)) goto failure;
    if (!reader_finished(&payload)) goto failure;

    N148RansDecoder decoder;
    BitReader bits;
    if (!n148_rans_decoder_init_mixed(&decoder, rans_stream, rans_size))
        goto failure;
    bit_reader_init(&bits, amplitudes, amplitude_size, amplitude_bits);
    uint32_t decoded_symbols = 0;
    if (!bits.valid ||
        !decode_rans_plane(&decoder, &bits, models,
                           width / 8 + (width % 8 != 0), 0, use_context,
                           use_intra,
                           symbol_count, &decoded_symbols, &coefficients[0],
                           trace) ||
        !decode_rans_plane(&decoder, &bits, models,
                           chroma_width / 8 + (chroma_width % 8 != 0),
                           1, use_context, use_intra, symbol_count,
                           &decoded_symbols,
                           &coefficients[1], trace) ||
        !decode_rans_plane(&decoder, &bits, models,
                           chroma_width / 8 + (chroma_width % 8 != 0),
                           1, use_context, use_intra, symbol_count,
                           &decoded_symbols,
                           &coefficients[2], trace) ||
        bits.bits_remaining != 0) goto failure;
    if (use_intra) {
        long y_count = coefficients[0].count;
        long cb_count = coefficients[1].count;
        if (!decode_prediction_plane(
                &decoder, models, decoded_modes, y_count,
                width / 8 + (width % 8 != 0), 0,
                coefficient_model_count, symbol_count, &decoded_symbols) ||
            !decode_prediction_plane(
                &decoder, models, decoded_modes + y_count, cb_count,
                chroma_width / 8 + (chroma_width % 8 != 0), 1,
                coefficient_model_count, symbol_count, &decoded_symbols) ||
            !decode_prediction_plane(
                &decoder, models, decoded_modes + y_count + cb_count,
                coefficients[2].count,
                chroma_width / 8 + (chroma_width % 8 != 0), 1,
                coefficient_model_count, symbol_count, &decoded_symbols))
            goto failure;
    }
    if (use_adaptive && !decode_adaptive_map(
            &decoder, models, coefficient_model_count + BLOCK_INTRA_MODELS,
            width, height, symbol_count, &decoded_symbols,
            &decoded_adaptive)) goto failure;
    if (use_transform && !decode_transform_map(
            &decoder, models,
            coefficient_model_count + BLOCK_INTRA_MODELS +
                (use_adaptive ? ADAPTIVE_MAP_MODEL_COUNT : 0),
            symbol_count, &decoded_symbols, &decoded_transform)) goto failure;
    if (decoded_symbols != symbol_count ||
        !n148_rans_decoder_finished(&decoder)) goto failure;
    if (amplitude_bits & 7u) {
        uint8_t padding_mask =
            (uint8_t)((1u << (8u - (amplitude_bits & 7u))) - 1u);
        if (!amplitude_size || amplitudes[amplitude_size - 1] & padding_mask)
            goto failure;
    }
    if (prediction) {
        prediction->values = decoded_modes;
        prediction->count = expected_modes;
        decoded_modes = NULL;
    }
    if (adaptive_map) {
        *adaptive_map = decoded_adaptive;
        memset(&decoded_adaptive, 0, sizeof(decoded_adaptive));
    }
    if (transform_map) {
        *transform_map = decoded_transform;
        memset(&decoded_transform, 0, sizeof(decoded_transform));
    }
    n148_adaptive_map_release(&decoded_adaptive);
    n148_transform_map_release(&decoded_transform);
    free(models);
    free(decoded_modes);
    return 1;

failure:
    free(models);
    free(decoded_modes);
    n148_adaptive_map_release(&decoded_adaptive);
    n148_transform_map_release(&decoded_transform);
    for (int plane = 0; plane < 3; plane++)
        n148_free_coeff_plane(&coefficients[plane]);
    return 0;
}

static int decode_modern_coefficients(
    const uint8_t *metadata, size_t metadata_size,
    const uint8_t *payload_data, size_t payload_size,
    int width, int height, int chroma, uint32_t features, int joint_chroma,
    int segmented, int adaptive_filter, int variable_luma, int dct32,
    uint32_t entropy_tools,
    N148CoeffPlane coefficients[3], N148PredictionModes *prediction,
    N148PartitionMap *partition_map,
    N148SegmentationMap *segmentation_map,
    N148TransformMap *transform_map) {
    uint8_t *decoded_modes = NULL;
    N148PartitionMap decoded_partition = {0};
    N148SegmentationMap decoded_segmentation = {0};
    N148TransformMap decoded_transform = {0};
    if ((entropy_tools & N148_ENTROPY_RICH_CONTEXT) && metadata_size > 0 &&
        metadata && metadata[0] == ENTROPY_METADATA_REVISION_BASE)
        entropy_tools &= N148_ENTROPY_MULTIPLE_REFERENCES;
    if (!metadata || !payload_data || !coefficients || !prediction ||
        !partition_map || !segmentation_map || !transform_map ||
        width <= 0 || height <= 0 ||
        chroma < CHROMA_444 || chroma > CHROMA_420 ||
        (joint_chroma != 0 && joint_chroma != 1) ||
        (segmented != 0 && segmented != 1) ||
        (adaptive_filter != 0 && adaptive_filter != 1) ||
        (variable_luma != 0 && variable_luma != 1) ||
        (dct32 != 0 && dct32 != 1) ||
        (entropy_tools & ~(N148_ENTROPY_ADAPTIVE |
                           N148_ENTROPY_RICH_CONTEXT |
                           N148_ENTROPY_MULTIPLE_REFERENCES)) ||
        ((entropy_tools & N148_ENTROPY_ADAPTIVE) &&
         !(features & N148_FEATURE_RANS)) ||
        (dct32 && !variable_luma) ||
        (adaptive_filter && !segmented) ||
        !n148_format_3_features_valid(features) ||
        (joint_chroma &&
         !(features & N148_FEATURE_CONTEXTUAL_RDO))) return 0;
    memset(coefficients, 0, 3 * sizeof(*coefficients));
    memset(prediction, 0, sizeof(*prediction));
    memset(partition_map, 0, sizeof(*partition_map));
    memset(segmentation_map, 0, sizeof(*segmentation_map));
    memset(transform_map, 0, sizeof(*transform_map));
    int use_context = (features & N148_FEATURE_CONTEXT) != 0;
    int use_directional =
        (features & N148_FEATURE_DIRECTIONAL_INTRA) != 0;
    int use_split = (features & N148_FEATURE_INTRA_4X4) != 0;
    int rich_context =
        (entropy_tools & N148_ENTROPY_RICH_CONTEXT) != 0;
    int multiple_references =
        (entropy_tools & N148_ENTROPY_MULTIPLE_REFERENCES) != 0;
    if (rich_context &&
        (!use_context || !(entropy_tools & N148_ENTROPY_ADAPTIVE))) return 0;
    if (multiple_references && (!use_directional ||
                                !(features & N148_FEATURE_CONTEXTUAL_RDO)))
        return 0;
    int coefficient_model_count = rich_context ?
        RICH_CONTEXT_MODEL_COUNT : use_context ?
        CONTEXT_MODEL_COUNT : BASE_COEFFICIENT_MODEL_COUNT;
    int model_count = coefficient_model_count + DIRECTIONAL_MODELS +
        (use_split ? PARTITION_MODEL_COUNT : 0) +
        (segmented ? SEGMENTATION_MODEL_COUNT : 0) +
        (variable_luma ? LUMA_TRANSFORM_MODEL_COUNT : 0);
    N148RansModel *models = (N148RansModel *) malloc(
        MAX_MODEL_COUNT * sizeof(*models));
    if (!models) return 0;
    uint8_t adaptive_mask[RICH_ADAPTIVE_MASK_SIZE] = {0};
    size_t metadata_consumed = 0;
    if (!(rich_context ? parse_rich_models(
              metadata, metadata_size, models, model_count,
              adaptive_mask,
              &metadata_consumed) :
          parse_rans_models(metadata, metadata_size, models, model_count,
                            &metadata_consumed)) ||
        metadata_consumed != metadata_size) goto failure;

    int chroma_width, chroma_height;
    chroma_dimensions(chroma, width, height, &chroma_width, &chroma_height);
    if (!allocate_coefficients(width, height, &coefficients[0]) ||
        !allocate_coefficients(chroma_width, chroma_height, &coefficients[1]) ||
        !allocate_coefficients(chroma_width, chroma_height, &coefficients[2]) ||
        !n148_partition_map_allocate(width, height, chroma,
                                        &decoded_partition) ||
        (variable_luma && !n148_transform_map_allocate(
            width, height, chroma, &decoded_transform))) goto failure;

    ByteReader payload;
    reader_init(&payload, payload_data, payload_size);
    uint8_t payload_version = reader_u8(&payload);
    uint8_t plane_count = reader_u8(&payload);
    uint8_t mode_coder = reader_u8(&payload);
    uint8_t map_coders = reader_u8(&payload);
    uint8_t expected_payload_version = rich_context ?
        PAYLOAD_REVISION_RICH_CONTEXT : variable_luma ?
        PAYLOAD_REVISION_VARIABLE_LUMA : adaptive_filter ?
        (joint_chroma ? PAYLOAD_REVISION_JOINT_ADAPTIVE_FILTER :
                        PAYLOAD_REVISION_ADAPTIVE_FILTER) :
        segmented ?
        (joint_chroma ? PAYLOAD_REVISION_JOINT_SEGMENTATION :
                        PAYLOAD_REVISION_SEGMENTATION) :
        (joint_chroma ? PAYLOAD_REVISION_JOINT_CHROMA :
                        PAYLOAD_REVISION_DIRECTIONAL_INTRA);
    uint8_t expected_map_coders = (uint8_t)(
        (use_split ? PARTITION_MAP_CODER_RANS : 0) |
        (segmented ? SEGMENT_MAP_CODER_RANS : 0) |
        (variable_luma ? TRANSFORM_MAP_CODER_RANS : 0));
    if (payload_version != expected_payload_version ||
        plane_count != PLANE_COUNT ||
        mode_coder != INTRA_MODE_CODER_RANS ||
        map_coders != expected_map_coders)
        goto failure;
    uint32_t symbol_count = reader_u32(&payload);
    uint32_t rans_size = reader_u32(&payload);
    uint32_t amplitude_bits = reader_u32(&payload);
    uint32_t prediction_mode_count = reader_u32(&payload);
    uint32_t partition_count = use_split ? reader_u32(&payload) : 0;
    uint32_t segmentation_count = segmented ? reader_u32(&payload) : 0;
    uint32_t transform_count = variable_luma ? reader_u32(&payload) : 0;
    uint8_t segmentation_scales[N148_SEGMENT_COUNT] = {100, 100, 100, 100};
    if (segmented) {
        for (int segment = 0; segment < N148_SEGMENT_COUNT; segment++) {
            segmentation_scales[segment] = reader_u8(&payload);
            if (segmentation_scales[segment] < N148_SEGMENT_MIN_SCALE ||
                segmentation_scales[segment] > N148_SEGMENT_MAX_SCALE)
                goto failure;
        }
    }
    if (amplitude_bits > UINT32_MAX - 7u) goto failure;
    uint32_t amplitude_size = (amplitude_bits + 7u) / 8u;
    const uint8_t *rans_stream = reader_bytes(&payload, rans_size);
    const uint8_t *amplitudes = reader_bytes(&payload, amplitude_size);
    size_t expected_modes;
    long y_blocks = coefficients[0].count;
    long cb_blocks = coefficients[1].count;
    int y_blocks_x = width / 8 + (width % 8 != 0);
    int y_blocks_y = height / 8 + (height % 8 != 0);
    size_t y_modes = (size_t) y_blocks * N148_INTRA_MODE_SLOTS_PER_BLOCK;
    size_t cb_modes = (size_t) cb_blocks * N148_INTRA_MODE_SLOTS_PER_BLOCK;
    size_t expected_segmentation_count =
        (size_t)(width / N148_SEGMENT_REGION_SIZE +
                 (width % N148_SEGMENT_REGION_SIZE != 0)) *
        (size_t)(height / N148_SEGMENT_REGION_SIZE +
                 (height % N148_SEGMENT_REGION_SIZE != 0));
    if (!n148_directional_intra_expected_modes(width, height, chroma,
                                       &expected_modes) ||
        (joint_chroma && y_modes > SIZE_MAX - cb_modes) ||
        (joint_chroma ? prediction_mode_count != y_modes + cb_modes :
                        prediction_mode_count != expected_modes) ||
        (use_split && partition_count != decoded_partition.count) ||
        (segmented && segmentation_count != expected_segmentation_count) ||
        (variable_luma &&
         transform_count != decoded_transform.plane_offsets[1]) ||
        !reader_finished(&payload)) goto failure;
    decoded_modes = (uint8_t *) calloc(expected_modes, 1);
    if (!decoded_modes) goto failure;

    N148RansDecoder decoder;
    N148RansAdaptiveModel adaptive_models[MAX_MODEL_COUNT];
    BitReader bits;
    int use_adaptive_decoder = (entropy_tools & N148_ENTROPY_ADAPTIVE) != 0;
    if (rich_context) {
        use_adaptive_decoder = 0;
        for (size_t index = 0; index < RICH_ADAPTIVE_MASK_SIZE; index++)
            use_adaptive_decoder |= adaptive_mask[index] != 0;
    }
    if (use_adaptive_decoder) {
        if (!n148_rans_decoder_init_mixed_adaptive(
                &decoder, rans_stream, rans_size, models, adaptive_models,
                (size_t) model_count,
                rich_context ?
                    RICH_LUMA_DC_MODELS + RICH_LUMA_AC_MODELS :
                    (size_t) model_count,
                rich_context ? adaptive_mask : NULL,
                rich_context ? RICH_ADAPTIVE_MODEL_COUNT : 0,
                N148_ENTROPY_ADAPT_RATE_SHIFT))
            goto failure;
    } else if (!n148_rans_decoder_init_mixed(
                   &decoder, rans_stream, rans_size)) goto failure;
    bit_reader_init(&bits, amplitudes, amplitude_size, amplitude_bits);
    uint32_t decoded_symbols = 0;
    int segmentation_model = coefficient_model_count + DIRECTIONAL_MODELS +
        (use_split ? PARTITION_MODEL_COUNT : 0);
    int transform_model = segmentation_model +
        (segmented ? SEGMENTATION_MODEL_COUNT : 0);
    int allowed_modes = multiple_references ?
        N148_PACKED_INTRA_MODE_COUNT :
        (use_directional ? N148_DIRECTIONAL_INTRA_MODE_COUNT : 4);
    int chroma_allowed_modes = use_directional ?
        N148_DIRECTIONAL_INTRA_MODE_COUNT : 4;
    if (!bits.valid ||
        (variable_luma && !decode_luma_transform_map(
              &decoder, models, transform_model, symbol_count,
              &decoded_symbols, dct32, &decoded_transform)) ||
        (use_split && !(variable_luma ? decode_variable_luma_partition_map(
              &decoder, models, coefficient_model_count + DIRECTIONAL_MODELS,
              symbol_count, &decoded_symbols, &decoded_transform,
              &decoded_partition, dct32) :
          decode_partition_map(
              &decoder, models, coefficient_model_count + DIRECTIONAL_MODELS,
              symbol_count, &decoded_symbols, &decoded_partition))) ||
        (segmented && !decode_segmentation_map(
            &decoder, models, segmentation_model, width, height,
            symbol_count, &decoded_symbols, &decoded_segmentation)))
        goto failure;

#define DECODE_MODERN_MODES() \
    ((variable_luma ? decode_variable_luma_prediction_plane( \
          &decoder, models, decoded_modes, y_blocks, y_blocks_x, y_blocks_y, \
          coefficient_model_count, allowed_modes, \
          decoded_partition.split + decoded_partition.plane_offsets[0], \
          symbol_count, &decoded_symbols, &decoded_transform, dct32) : \
      decode_directional_prediction_plane( \
          &decoder, models, decoded_modes, y_blocks, y_blocks_x, 0, \
          coefficient_model_count, allowed_modes, \
          decoded_partition.split + decoded_partition.plane_offsets[0], \
          symbol_count, &decoded_symbols)) && \
     decode_directional_prediction_plane( \
          &decoder, models, decoded_modes + y_modes, cb_blocks, \
          chroma_width / 8 + (chroma_width % 8 != 0), 1, \
          coefficient_model_count, chroma_allowed_modes, \
          decoded_partition.split + decoded_partition.plane_offsets[1], \
          symbol_count, &decoded_symbols) && \
     (joint_chroma || decode_directional_prediction_plane( \
          &decoder, models, decoded_modes + y_modes + cb_modes, \
          coefficients[2].count, \
          chroma_width / 8 + (chroma_width % 8 != 0), 1, \
          coefficient_model_count, chroma_allowed_modes, \
          decoded_partition.split + decoded_partition.plane_offsets[2], \
          symbol_count, &decoded_symbols)))

    int syntax_ok;
    if (rich_context) {
        syntax_ok = DECODE_MODERN_MODES();
        if (syntax_ok && joint_chroma) {
            if (coefficients[2].count != cb_blocks) goto failure;
            memcpy(decoded_modes + y_modes + cb_modes,
                   decoded_modes + y_modes, cb_modes);
        }
        syntax_ok = syntax_ok &&
            (variable_luma ? decode_rich_luma_coefficient_plane(
                &decoder, &bits, models,
                decoded_partition.split + decoded_partition.plane_offsets[0],
                decoded_modes, y_blocks_x, y_blocks_y, symbol_count,
                &decoded_symbols, &decoded_transform, &coefficients[0]) :
             decode_rich_coefficient_plane(
                &decoder, &bits, models,
                decoded_partition.split + decoded_partition.plane_offsets[0],
                decoded_modes, y_blocks_x, 0, symbol_count,
                &decoded_symbols, &coefficients[0])) &&
            decode_rich_coefficient_plane(
                &decoder, &bits, models,
                decoded_partition.split + decoded_partition.plane_offsets[1],
                decoded_modes + y_modes,
                chroma_width / 8 + (chroma_width % 8 != 0), 1,
                symbol_count, &decoded_symbols, &coefficients[1]) &&
            decode_rich_coefficient_plane(
                &decoder, &bits, models,
                decoded_partition.split + decoded_partition.plane_offsets[2],
                decoded_modes + y_modes + cb_modes,
                chroma_width / 8 + (chroma_width % 8 != 0), 1,
                symbol_count, &decoded_symbols, &coefficients[2]);
    } else {
        FixedRansDecoder fixed_decoder;
        FixedRansDecoder *fixed = NULL;
        if (!decoder.adaptive_models) {
            if (decoded_symbols > symbol_count) goto failure;
            fixed_rans_begin(
                &decoder, symbol_count - decoded_symbols, &fixed_decoder);
            fixed = &fixed_decoder;
        }
        syntax_ok =
            (variable_luma ? decode_variable_luma_coefficient_plane(
                &decoder, &bits, models,
                decoded_partition.split + decoded_partition.plane_offsets[0],
                y_blocks_x, y_blocks_y, use_context, symbol_count,
                &decoded_symbols, &decoded_transform, &coefficients[0], fixed,
                dct32) :
             decode_directional_coefficient_plane(
                &decoder, &bits, models,
                decoded_partition.split + decoded_partition.plane_offsets[0],
                y_blocks_x, 0, use_context, symbol_count,
                &decoded_symbols, &coefficients[0], fixed)) &&
            decode_directional_coefficient_plane(
                &decoder, &bits, models,
                decoded_partition.split + decoded_partition.plane_offsets[1],
                chroma_width / 8 + (chroma_width % 8 != 0), 1, use_context,
                symbol_count, &decoded_symbols, &coefficients[1], fixed) &&
            decode_directional_coefficient_plane(
                &decoder, &bits, models,
                decoded_partition.split + decoded_partition.plane_offsets[2],
                chroma_width / 8 + (chroma_width % 8 != 0), 1, use_context,
                symbol_count, &decoded_symbols, &coefficients[2], fixed);
        if (syntax_ok && fixed) {
            decoded_symbols = symbol_count - fixed->symbols_remaining;
            fixed_rans_commit(fixed, &decoder);
        }
        syntax_ok = syntax_ok && DECODE_MODERN_MODES();
    }
#undef DECODE_MODERN_MODES
    if (!syntax_ok || bits.bits_remaining != 0 ||
        decoded_symbols != symbol_count ||
        !n148_rans_decoder_finished(&decoder)) goto failure;
    if (segmented) {
        memcpy(decoded_segmentation.quant_scale, segmentation_scales,
               sizeof(segmentation_scales));
        if (!n148_segmentation_map_validate(&decoded_segmentation))
            goto failure;
    }
    if (joint_chroma) {
        if (coefficients[2].count != cb_blocks) goto failure;
        memcpy(decoded_modes + y_modes + cb_modes,
               decoded_modes + y_modes, cb_modes);
    }
    if (amplitude_bits & 7u) {
        uint8_t padding_mask =
            (uint8_t)((1u << (8u - (amplitude_bits & 7u))) - 1u);
        if (!amplitude_size || amplitudes[amplitude_size - 1] & padding_mask)
            goto failure;
    }
    prediction->values = decoded_modes;
    prediction->count = expected_modes;
    decoded_modes = NULL;
    *partition_map = decoded_partition;
    memset(&decoded_partition, 0, sizeof(decoded_partition));
    if (segmented) {
        *segmentation_map = decoded_segmentation;
        memset(&decoded_segmentation, 0, sizeof(decoded_segmentation));
    }
    if (variable_luma) {
        *transform_map = decoded_transform;
        memset(&decoded_transform, 0, sizeof(decoded_transform));
    }
    free(models);
    return 1;

failure:
    free(models);
    free(decoded_modes);
    n148_partition_map_release(&decoded_partition);
    n148_segmentation_map_release(&decoded_segmentation);
    n148_transform_map_release(&decoded_transform);
    for (int plane = 0; plane < 3; plane++)
        n148_free_coeff_plane(&coefficients[plane]);
    return 0;
}

static int inspect_modern_syntax_entropy(
    const uint8_t *metadata, size_t metadata_size,
    const uint8_t *payload, size_t payload_size,
    int width, int height, int chroma, uint32_t features, int joint_chroma,
    int segmented, int adaptive_filter, int variable_luma, int dct32,
    uint32_t entropy_tools,
    N148SyntaxInspection *inspection) {
    if (!inspection) return 0;
    memset(inspection, 0, sizeof(*inspection));
    N148CoeffPlane coefficients[3] = {{0}};
    N148PredictionModes prediction = {0};
    N148PartitionMap partition_map = {0};
    N148SegmentationMap segmentation_map = {0};
    N148TransformMap transform_map = {0};
    /* The extended transform-map validator is shared with the codec and is
       selected through the internal fidelity context.  Inspection is also a
       standalone entry point, so establish the syntax context explicitly
       instead of depending on whichever encode/decode happened previously. */
    uint32_t inspection_tools = dct32 ? N148_FIDELITY_DCT32 : 0;
    if (entropy_tools & N148_ENTROPY_MULTIPLE_REFERENCES)
        inspection_tools |= N148_FIDELITY_MULTIPLE_REFERENCES;
    if (!n148_fidelity_tools_set(inspection_tools)) return 0;
    int success = decode_modern_coefficients(
        metadata, metadata_size, payload, payload_size,
        width, height, chroma, features, joint_chroma, segmented,
        adaptive_filter, variable_luma, dct32, entropy_tools,
        coefficients, &prediction,
        &partition_map, &segmentation_map, &transform_map);
    n148_fidelity_tools_set(0);
    if (success) {
        size_t mode_offset = 0;
        for (int plane = 0; plane < 3 && success; plane++) {
            for (long block = 0; block < coefficients[plane].count; block++) {
                size_t map_index = partition_map.plane_offsets[plane] +
                    (size_t) block;
                int split = partition_map.split[map_index];
                int parts = split ? N148_INTRA_MODE_SLOTS_PER_BLOCK : 1;
                inspection->total_blocks++;
                inspection->split_blocks += (uint64_t) split;
                inspection->plane_total_blocks[plane]++;
                inspection->plane_split_blocks[plane] += (uint64_t) split;
                for (int part = 0; part < parts; part++) {
                    uint8_t mode = prediction.values[
                        mode_offset + (size_t) block *
                            N148_INTRA_MODE_SLOTS_PER_BLOCK + (size_t) part];
                    int reference = n148_intra_reference_index(mode);
                    int base_mode = n148_intra_base_mode(mode);
                    if (base_mode >= N148_DIRECTIONAL_INTRA_MODE_COUNT ||
                        reference >= N148_INTRA_REFERENCE_COUNT ||
                        (plane != 0 && reference != 0) ||
                        (split && reference != 0)) {
                        success = 0;
                        break;
                    }
                    inspection->mode_histogram[base_mode]++;
                    inspection->plane_mode_histogram[plane][base_mode]++;
                    if (plane == 0)
                        inspection->luma_reference_histogram[reference]++;
                }
            }
            mode_offset += (size_t) coefficients[plane].count *
                N148_INTRA_MODE_SLOTS_PER_BLOCK;
        }
    }
    for (int plane = 0; plane < 3; plane++)
        n148_free_coeff_plane(&coefficients[plane]);
    n148_prediction_modes_release(&prediction);
    if (success && segmented) {
        inspection->segment_count = segmentation_map.count;
        memcpy(inspection->segment_quant_scale,
               segmentation_map.quant_scale,
               sizeof(inspection->segment_quant_scale));
        for (size_t index = 0; index < segmentation_map.count; index++)
            inspection->segment_histogram[segmentation_map.levels[index]]++;
    }
    n148_segmentation_map_release(&segmentation_map);
    if (success && variable_luma) {
        inspection->luma_transform_regions =
            transform_map.plane_offsets[1];
        for (int macro_y = 0; macro_y < transform_map.rows[0]; macro_y++) {
            for (int macro_x = 0; macro_x < transform_map.columns[0];
                 macro_x++) {
                size_t index = (size_t) macro_y *
                    (size_t) transform_map.columns[0] + (size_t) macro_x;
                if (n148_luma_transform_dct32_member(
                        &transform_map, macro_x, macro_y)) {
                    if (n148_luma_transform_dct32_origin(
                            &transform_map, macro_x, macro_y))
                        inspection->luma_transform_32x32++;
                    continue;
                }
                if (transform_map.strategies[index] ==
                    N148_TRANSFORM_DCT16) {
                    inspection->luma_transform_16x16++;
                    continue;
                }
                for (int cell_y = 0; cell_y < 2; cell_y++) {
                    int block_y = macro_y * 2 + cell_y;
                    if (block_y >= transform_map.blocks_y[0]) continue;
                    for (int cell_x = 0; cell_x < 2; cell_x++) {
                        int block_x = macro_x * 2 + cell_x;
                        if (block_x >= transform_map.blocks_x[0]) continue;
                        size_t block = (size_t) block_y *
                            (size_t) transform_map.blocks_x[0] +
                            (size_t) block_x;
                        if (partition_map.split[block])
                            inspection->luma_transform_4x4 += 4;
                        else
                            inspection->luma_transform_8x8++;
                    }
                }
            }
        }
        for (int macro_y = 0; macro_y + 1 < transform_map.rows[0];
             macro_y += 2) {
            for (int macro_x = 0; macro_x + 1 < transform_map.columns[0];
                 macro_x += 2) {
                int all_dct16 = 1;
                for (int dy = 0; dy < 2; dy++) {
                    for (int dx = 0; dx < 2; dx++) {
                        size_t index = (size_t)(macro_y + dy) *
                            (size_t) transform_map.columns[0] +
                            (size_t)(macro_x + dx);
                        if (transform_map.strategies[index] !=
                            N148_TRANSFORM_DCT16) all_dct16 = 0;
                    }
                }
                inspection->luma_transform_32x32_opportunities +=
                    (uint64_t) all_dct16;
            }
        }
    }
    n148_transform_map_release(&transform_map);
    n148_partition_map_release(&partition_map);
    if (!success) memset(inspection, 0, sizeof(*inspection));
    return success;
}

static int inspect_modern_syntax(
    const uint8_t *metadata, size_t metadata_size,
    const uint8_t *payload, size_t payload_size,
    int width, int height, int chroma, uint32_t features, int joint_chroma,
    int segmented, int adaptive_filter, int variable_luma, int dct32,
    N148SyntaxInspection *inspection) {
    return inspect_modern_syntax_entropy(
        metadata, metadata_size, payload, payload_size,
        width, height, chroma, features, joint_chroma, segmented,
        adaptive_filter, variable_luma, dct32, 0, inspection);
}

int n148_entropy_profile_inspect(
    const uint8_t *metadata, size_t metadata_size,
    const uint8_t *payload, size_t payload_size,
    int width, int height, int chroma, uint32_t features, int joint_chroma,
    int segmented, int adaptive_filter, int variable_luma, int dct32,
    uint32_t entropy_tools, N148SyntaxInspection *inspection) {
    return inspect_modern_syntax_entropy(
        metadata, metadata_size, payload, payload_size,
        width, height, chroma, features, joint_chroma, segmented,
        adaptive_filter, variable_luma, dct32, entropy_tools, inspection);
}

int n148_directional_intra_inspect(const uint8_t *metadata, size_t metadata_size,
                    const uint8_t *payload, size_t payload_size,
                    int width, int height, int chroma, uint32_t features,
                    N148SyntaxInspection *inspection) {
    return inspect_modern_syntax(
        metadata, metadata_size, payload, payload_size,
        width, height, chroma, features, 0, 0, 0, 0, 0, inspection);
}

int n148_joint_chroma_inspect(
    const uint8_t *metadata, size_t metadata_size,
    const uint8_t *payload, size_t payload_size,
    int width, int height, int chroma, uint32_t features,
    N148SyntaxInspection *inspection) {
    return inspect_modern_syntax(
        metadata, metadata_size, payload, payload_size,
        width, height, chroma, features, 1, 0, 0, 0, 0, inspection);
}

int n148_segmented_inspect(
    const uint8_t *metadata, size_t metadata_size,
    const uint8_t *payload, size_t payload_size,
    int width, int height, int chroma, uint32_t features, int joint_chroma,
    N148SyntaxInspection *inspection) {
    return inspect_modern_syntax(
        metadata, metadata_size, payload, payload_size,
        width, height, chroma, features, joint_chroma, 1, 0, 0, 0,
        inspection);
}

int n148_adaptive_filter_inspect(
    const uint8_t *metadata, size_t metadata_size,
    const uint8_t *payload, size_t payload_size,
    int width, int height, int chroma, uint32_t features, int joint_chroma,
    N148SyntaxInspection *inspection) {
    return inspect_modern_syntax(
        metadata, metadata_size, payload, payload_size,
        width, height, chroma, features, joint_chroma, 1, 1, 0, 0,
        inspection);
}

int n148_predictive_inspect(
    const uint8_t *metadata, size_t metadata_size,
    const uint8_t *payload, size_t payload_size,
    int width, int height, int chroma, uint32_t features, int joint_chroma,
    int segmented, int adaptive_filter, int variable_luma, int dct32,
    N148SyntaxInspection *inspection) {
    return inspect_modern_syntax(
        metadata, metadata_size, payload, payload_size,
        width, height, chroma, features, joint_chroma, segmented,
        adaptive_filter, variable_luma, dct32, inspection);
}

static int read_huffman_specs(const uint8_t *metadata, size_t metadata_size,
                              HuffSpec specs[HUFFMAN_TABLE_COUNT]) {
    ByteReader reader;
    reader_init(&reader, metadata, metadata_size);
    if (reader_u8(&reader) != ENTROPY_METADATA_REVISION_BASE ||
        reader_u8(&reader) != ENTROPY_CODER_HUFFMAN ||
        reader_u8(&reader) != HUFFMAN_TABLE_COUNT ||
        reader_u8(&reader) != 0) return 0;
    memset(specs, 0, HUFFMAN_TABLE_COUNT * sizeof(*specs));
    for (int table = 0; table < HUFFMAN_TABLE_COUNT; table++) {
        for (int length = 1; length <= 16; length++) {
            specs[table].bits[length] = reader_u8(&reader);
            specs[table].value_count += specs[table].bits[length];
            if (!reader.valid ||
                specs[table].value_count > HUFFMAN_MAX_SYMBOLS) return 0;
        }
        const uint8_t *values = reader_bytes(
            &reader, (size_t) specs[table].value_count);
        if (!values) return 0;
        memcpy(specs[table].values, values,
               (size_t) specs[table].value_count);
        if (!huffman_spec_is_valid(&specs[table])) return 0;
    }
    return reader_finished(&reader);
}

int n148_decode_format_2(const uint8_t *metadata, size_t metadata_size,
                   const uint8_t *payload, size_t payload_size,
                   int width, int height, int quality, int chroma,
                   uint32_t features,
                   Plane *y, Plane *cb, Plane *cr) {
    if (!y || !cb || !cr) return 0;
    *y = (Plane){0};
    *cb = (Plane){0};
    *cr = (Plane){0};
    if (features & N148_FEATURE_RANS) {
        N148CoeffPlane coefficients[3] = {{0}};
        N148PredictionModes prediction = {0};
        N148AdaptiveMap adaptive_map = {0};
        N148TransformMap transform_map = {0};
        int chroma_width, chroma_height;
        chroma_dimensions(chroma, width, height, &chroma_width, &chroma_height);
        int success = n148_decode_format_2_coefficients(
            metadata, metadata_size, payload, payload_size,
            width, height, chroma, features, coefficients, NULL,
            &prediction, &adaptive_map, &transform_map);
        int use_perceptual =
            (features & N148_FEATURE_PERCEPTUAL_COLOR) != 0;
        if (success && (features & N148_FEATURE_INTRA)) {
            success = n148_intra_reconstruct_planes(
                coefficients, prediction.values, prediction.count,
                width, height, quality, chroma, use_perceptual,
                (features & N148_FEATURE_ADAPTIVE_QUANT) ?
                    &adaptive_map : NULL,
                (features & N148_FEATURE_VARIABLE_TRANSFORM) ?
                    &transform_map : NULL,
                (features & N148_FEATURE_LOOP_FILTER) != 0,
                y, cb, cr);
        } else {
            if (success) success = n148_reconstruct_coeff_plane_ex(
                coefficients[0].coefficients, coefficients[0].count,
                width, height, quality, 0, use_perceptual, y);
            if (success) success = n148_reconstruct_coeff_plane_ex(
                coefficients[1].coefficients, coefficients[1].count,
                chroma_width, chroma_height, quality, 1, use_perceptual, cb);
            if (success) success = n148_reconstruct_coeff_plane_ex(
                coefficients[2].coefficients, coefficients[2].count,
                chroma_width, chroma_height, quality, 1, use_perceptual, cr);
        }
        for (int plane = 0; plane < 3; plane++)
            n148_free_coeff_plane(&coefficients[plane]);
        n148_prediction_modes_release(&prediction);
        n148_adaptive_map_release(&adaptive_map);
        n148_transform_map_release(&transform_map);
        if (!success) {
            free_plane(y); free_plane(cb); free_plane(cr);
        }
        return success;
    }

    HuffSpec specs[HUFFMAN_TABLE_COUNT];
    DecodeStats stats;
    if (!read_huffman_specs(metadata, metadata_size, specs) ||
        payload_size > LONG_MAX ||
        !decode_image((unsigned char *) payload, (long) payload_size,
                      width, height, quality, chroma, specs,
                      y, cb, cr, &stats) ||
        stats.bytes_consumed != (long) payload_size) {
        free_plane(y); free_plane(cb); free_plane(cr);
        return 0;
    }
    return 1;
}

int n148_predictive_decode(
    const uint8_t *metadata, size_t metadata_size,
    const uint8_t *payload, size_t payload_size,
    int width, int height, int quality, int chroma_quality, int chroma,
    uint32_t features, int joint_chroma, int calibrated_chroma, int segmented,
    int adaptive_filter, int calibrated_luma, int variable_luma,
    int quant_adaptive_filter, int dct32, uint32_t entropy_tools,
    Plane *y, Plane *cb, Plane *cr) {
    if (!y || !cb || !cr || quality < 1 || quality > 100 ||
        chroma_quality < 1 || chroma_quality > 100 ||
        (joint_chroma != 0 && joint_chroma != 1) ||
        (calibrated_chroma != 0 && calibrated_chroma != 1) ||
        (calibrated_luma != 0 && calibrated_luma != 1) ||
        (variable_luma != 0 && variable_luma != 1) ||
        (quant_adaptive_filter != 0 && quant_adaptive_filter != 1) ||
        (dct32 != 0 && dct32 != 1) ||
        (dct32 && !variable_luma) ||
        (quant_adaptive_filter &&
         (!(features & N148_FEATURE_LOOP_FILTER) || !calibrated_luma)) ||
        (variable_luma &&
         (!(features & N148_FEATURE_CONTEXTUAL_RDO) ||
          !(features & N148_FEATURE_INTRA_4X4))) ||
        (segmented != 0 && segmented != 1) ||
        (adaptive_filter != 0 && adaptive_filter != 1) ||
        (adaptive_filter && (!segmented ||
         !(features & N148_FEATURE_LOOP_FILTER))) ||
        !n148_format_3_features_valid(features) ||
        (joint_chroma &&
         !(features & N148_FEATURE_CONTEXTUAL_RDO))) return 0;
    *y = (Plane){0};
    *cb = (Plane){0};
    *cr = (Plane){0};
    N148CoeffPlane coefficients[3] = {{0}};
    N148PredictionModes prediction = {0};
    N148PartitionMap partition_map = {0};
    N148SegmentationMap segmentation_map = {0};
    N148TransformMap transform_map = {0};
    int success = decode_modern_coefficients(
        metadata, metadata_size, payload, payload_size,
        width, height, chroma, features, joint_chroma, segmented,
        adaptive_filter, variable_luma, dct32, entropy_tools,
        coefficients, &prediction,
        &partition_map, &segmentation_map, &transform_map);
    if (success && segmented)
        segmentation_map.adaptive_filter = (uint8_t) adaptive_filter;
    if (success) {
        int loop_filter_policy =
            (features & N148_FEATURE_LOOP_FILTER) ?
            (quant_adaptive_filter ? N148_LOOP_FILTER_QUANT_ADAPTIVE_LUMA :
                                     N148_LOOP_FILTER_LEGACY) :
            N148_LOOP_FILTER_OFF;
        success = n148_directional_intra_reconstruct_planes(
            coefficients, prediction.values, prediction.count,
            width, height, quality, chroma_quality, calibrated_chroma,
            calibrated_luma, chroma,
            (features & N148_FEATURE_DIRECTIONAL_INTRA) != 0,
            (features & N148_FEATURE_INTRA_4X4) != 0,
            loop_filter_policy,
            &partition_map, segmented ? &segmentation_map : NULL,
            variable_luma ? &transform_map : NULL,
            y, cb, cr);
    }
    for (int plane = 0; plane < 3; plane++)
        n148_free_coeff_plane(&coefficients[plane]);
    n148_prediction_modes_release(&prediction);
    n148_partition_map_release(&partition_map);
    n148_segmentation_map_release(&segmentation_map);
    n148_transform_map_release(&transform_map);
    if (!success) {
        free_plane(y);
        free_plane(cb);
        free_plane(cr);
    }
    return success;
}

int n148_decode_format_3(const uint8_t *metadata, size_t metadata_size,
                   const uint8_t *payload, size_t payload_size,
                   int width, int height, int quality, int chroma,
                   uint32_t features,
                   Plane *y, Plane *cb, Plane *cr) {
    return n148_predictive_decode(
        metadata, metadata_size, payload, payload_size,
        width, height, quality, quality, chroma, features,
        0, 0, 0, 0, 0, 0, 0, 0, 0,
        y, cb, cr);
}

int n148_joint_chroma_decode(
    const uint8_t *metadata, size_t metadata_size,
    const uint8_t *payload, size_t payload_size,
    int width, int height, int quality, int chroma, uint32_t features,
    Plane *y, Plane *cb, Plane *cr) {
    return n148_predictive_decode(
        metadata, metadata_size, payload, payload_size,
        width, height, quality, quality, chroma, features,
        1, 0, 0, 0, 0, 0, 0, 0, 0,
        y, cb, cr);
}

int n148_calibrated_chroma_decode(
    const uint8_t *metadata, size_t metadata_size,
    const uint8_t *payload, size_t payload_size,
    int width, int height, int quality, int chroma_quality, int chroma,
    uint32_t features, int joint_chroma,
    Plane *y, Plane *cb, Plane *cr) {
    return n148_predictive_decode(
        metadata, metadata_size, payload, payload_size,
        width, height, quality, chroma_quality, chroma, features,
        joint_chroma, 1, 0, 0, 0, 0, 0, 0, 0, y, cb, cr);
}

int n148_segmented_decode(
    const uint8_t *metadata, size_t metadata_size,
    const uint8_t *payload, size_t payload_size,
    int width, int height, int quality, int chroma_quality, int chroma,
    uint32_t features, int joint_chroma,
    Plane *y, Plane *cb, Plane *cr) {
    return n148_predictive_decode(
        metadata, metadata_size, payload, payload_size,
        width, height, quality, chroma_quality, chroma, features,
        joint_chroma, 1, 1, 0, 0, 0, 0, 0, 0, y, cb, cr);
}

int n148_adaptive_filter_decode(
    const uint8_t *metadata, size_t metadata_size,
    const uint8_t *payload, size_t payload_size,
    int width, int height, int quality, int chroma_quality, int chroma,
    uint32_t features, int joint_chroma,
    Plane *y, Plane *cb, Plane *cr) {
    return n148_predictive_decode(
        metadata, metadata_size, payload, payload_size,
        width, height, quality, chroma_quality, chroma, features,
        joint_chroma, 1, 1, 1, 0, 0, 0, 0, 0, y, cb, cr);
}

void n148_encoded_payload_release(N148EncodedPayload *encoded) {
    if (!encoded) return;
    free(encoded->metadata);
    free(encoded->payload);
    memset(encoded, 0, sizeof(*encoded));
}

void n148_prediction_modes_release(N148PredictionModes *prediction) {
    if (!prediction) return;
    free(prediction->values);
    memset(prediction, 0, sizeof(*prediction));
}

Novos na pasta src: a predição

src/intra.h

O intra.h é a interface da predição intra a partir dos vizinhos reconstruídos, do artigo 30, com os modos DC, vertical, horizontal e TM.

O arquivo completo tem 53 linhas:

/*
 * N.148i reconstructed-neighbor intra prediction.
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#ifndef N148_INTRA_H
#define N148_INTRA_H

#include <stddef.h>
#include <stdint.h>

#include "adaptive_quant.h"
#include "encoder.h"
#include "ppm.h"
#include "variable_transform.h"

enum {
    N148_INTRA_DC = 0,
    N148_INTRA_VERTICAL = 1,
    N148_INTRA_HORIZONTAL = 2,
    N148_INTRA_TRUE_MOTION = 3,
    N148_INTRA_MODE_COUNT = 4,
};

/* Quantize prediction residuals in Y, Cb, Cr order. Modes contains one value
   per 8x8 block in the same order and is allocated by this function. */
int n148_intra_quantize_planes(const Plane *y, const Plane *cb,
                               const Plane *cr, int quality,
                               int perceptual_color,
                               const N148AdaptiveMap *adaptive_map,
                               const N148TransformMap *transform_map,
                               int rdo_effort, int loop_filter,
                               N148CoeffPlane coefficients[3],
                               uint8_t **modes, size_t *mode_count);

/* Reconstruct all three planes from residual coefficients and prediction
   modes. The scalar inverse transform is normative for predictor feedback. */
int n148_intra_reconstruct_planes(const N148CoeffPlane coefficients[3],
                                  const uint8_t *modes, size_t mode_count,
                                  int width, int height, int quality,
                                  int chroma, int perceptual_color,
                                  const N148AdaptiveMap *adaptive_map,
                                  const N148TransformMap *transform_map,
                                  int loop_filter,
                                  Plane *y, Plane *cb, Plane *cr);

/* Return the exact number of prediction modes implied by the dimensions. */
int n148_intra_expected_modes(int width, int height, int chroma,
                              size_t *mode_count);

#endif

src/intra.c

O intra.c implementa essa predição, reconstruindo cada bloco exatamente como o decoder vai reconstruir, para que o erro não se acumule de um bloco para o outro.

O arquivo completo tem 1.343 linhas:

/*
 * N.148i reconstructed-neighbor intra prediction.
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 *
 * Prediction is deliberately kept separate from the format-1 transform path. The
 * encoder reconstructs each chosen residual before visiting the next block,
 * exactly mirroring the decoder and preventing prediction drift.
 */

#include "intra.h"

#include <float.h>
#include <limits.h>
#include <math.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#include "adaptive_quant.h"
#include "dct.h"
#include "header.h"
#include "loop_filter.h"
#include "rdo.h"
#include "tables.h"
#include "variable_transform.h"

typedef struct {
    float reciprocal[64];
    float multiplier[64];
    double unit_energy[64];
} IntraQuant;

typedef struct {
    int step[16 * 16];
    int size;
} VariableQuant;

#define N148_RDO_TRELLIS_LAMBDA_SCALE 0.04
#define N148_RDO_MODE_LAMBDA_SCALE 0.25

static int checked_block_count(int width, int height, size_t *count) {
    if (width <= 0 || height <= 0 || !count) return 0;
    size_t blocks_x = (size_t)(width / 8 + (width % 8 != 0));
    size_t blocks_y = (size_t)(height / 8 + (height % 8 != 0));
    if (blocks_y != 0 && blocks_x > SIZE_MAX / blocks_y) return 0;
    *count = blocks_x * blocks_y;
    return *count != 0 && *count <= LONG_MAX;
}

int n148_intra_expected_modes(int width, int height, int chroma,
                              size_t *mode_count) {
    if (!mode_count || chroma < 0 || chroma > 2) return 0;
    int chroma_width, chroma_height;
    chroma_dimensions(chroma, width, height, &chroma_width, &chroma_height);
    size_t luma, chroma_blocks;
    if (!checked_block_count(width, height, &luma) ||
        !checked_block_count(chroma_width, chroma_height, &chroma_blocks) ||
        chroma_blocks > (SIZE_MAX - luma) / 2) return 0;
    *mode_count = luma + chroma_blocks * 2;
    return 1;
}

static void build_quant_from_table(const int table[8][8], IntraQuant *quant) {
    for (int row = 0; row < 8; row++) {
        for (int column = 0; column < 8; column++) {
            int index = row * 8 + column;
            double scale = aan_scale_factor(row, column);
            quant->reciprocal[index] =
                (float)(1.0 / (table[row][column] * scale));
            quant->multiplier[index] =
                (float)(table[row][column] * scale / 64.0);
        }
    }
}

static void build_quant(const int base[8][8], int quality,
                        IntraQuant *quant) {
    int table[8][8];
    scale_table(base, quality, table);
    build_quant_from_table((const int (*)[8]) table, quant);
}

static void prepare_rdo_energy(IntraQuant *quant) {
    for (int position = 0; position < 64; position++) {
        float basis[64] = {0.0f};
        int natural = ZIGZAG[position];
        basis[natural] = quant->multiplier[natural];
        n148_idct_block_scalar(basis, basis);
        double energy = 0.0;
        for (int sample = 0; sample < 64; sample++) {
            double response = basis[sample] - 128.0;
            energy += response * response;
        }
        quant->unit_energy[position] = energy;
    }
}

static int build_adaptive_quants(const int base[8][8], int quality,
                                 IntraQuant quants[N148_AQ_LEVEL_COUNT]) {
    int scaled[8][8], adjusted[8][8];
    scale_table(base, quality, scaled);
    for (int level = 0; level < N148_AQ_LEVEL_COUNT; level++) {
        if (!n148_adaptive_adjust_table(
                (const int (*)[8]) scaled, (uint8_t) level, adjusted))
            return 0;
        build_quant_from_table((const int (*)[8]) adjusted, &quants[level]);
    }
    return 1;
}

static int allocate_coefficients(size_t count, N148CoeffPlane *output) {
    if (!output || count == 0 || count > LONG_MAX ||
        count > SIZE_MAX / (64 * sizeof(short)) ||
        count > SIZE_MAX / sizeof(*output->nonzero_masks)) return 0;
    size_t coefficient_bytes = count * 64 * sizeof(short);
    size_t mask_bytes = count * sizeof(*output->nonzero_masks);
    if (coefficient_bytes > SIZE_MAX - mask_bytes) return 0;
    output->coefficients = (short *) calloc(1, coefficient_bytes + mask_bytes);
    if (!output->coefficients) return 0;
    output->nonzero_masks = (unsigned long long *)
        ((uint8_t *) output->coefficients + coefficient_bytes);
    output->nonzero_counts = NULL;
    output->count = (long) count;
    return 1;
}

static int sample_clamped(const Plane *plane, int x, int y) {
    if (x < 0) x = 0;
    if (y < 0) y = 0;
    if (x >= plane->width) x = plane->width - 1;
    if (y >= plane->height) y = plane->height - 1;
    return plane->data[(long) y * plane->width + x];
}

static uint8_t clamp_byte(int value) {
    if (value < 0) return 0;
    if (value > 255) return 255;
    return (uint8_t) value;
}

static uint8_t prediction_neutral(int plane_index, int perceptual_color) {
    if (!perceptual_color) return 128;
    if (plane_index == 0) return 161;
    if (plane_index == 1) return 94;
    return 115;
}

static void prediction_block(const Plane *reconstructed, int block_x,
                             int block_y, int mode, uint8_t neutral,
                             uint8_t prediction[64]) {
    int x0 = block_x * 8;
    int y0 = block_y * 8;
    int has_top = y0 > 0;
    int has_left = x0 > 0;
    uint8_t top[8], left[8];
    int top_sum = 0;
    int left_sum = 0;

    for (int index = 0; index < 8; index++) {
        top[index] = has_top ? (uint8_t) sample_clamped(
            reconstructed, x0 + index, y0 - 1) : neutral;
        left[index] = has_left ? (uint8_t) sample_clamped(
            reconstructed, x0 - 1, y0 + index) : neutral;
        top_sum += top[index];
        left_sum += left[index];
    }
    int top_left = has_top && has_left ?
        sample_clamped(reconstructed, x0 - 1, y0 - 1) : neutral;
    int dc = neutral;
    if (has_top && has_left) dc = (top_sum + left_sum + 8) / 16;
    else if (has_top) dc = (top_sum + 4) / 8;
    else if (has_left) dc = (left_sum + 4) / 8;

    for (int row = 0; row < 8; row++) {
        for (int column = 0; column < 8; column++) {
            int value;
            switch (mode) {
                case N148_INTRA_DC:
                    value = dc;
                    break;
                case N148_INTRA_VERTICAL:
                    value = top[column];
                    break;
                case N148_INTRA_HORIZONTAL:
                    value = left[row];
                    break;
                case N148_INTRA_TRUE_MOTION:
                    value = left[row] + top[column] - top_left;
                    break;
                default:
                    value = neutral;
                    break;
            }
            prediction[row * 8 + column] = clamp_byte(value);
        }
    }
}

static void hadamard8(int values[8]) {
    for (int span = 1; span < 8; span *= 2) {
        for (int first = 0; first < 8; first += span * 2) {
            for (int offset = 0; offset < span; offset++) {
                int a = values[first + offset];
                int b = values[first + offset + span];
                values[first + offset] = a + b;
                values[first + offset + span] = a - b;
            }
        }
    }
}

/* SATD uses an integer Hadamard transform as a cheap proxy for the number of
   transform bits. Unlike pixel SAD, it penalizes prediction residuals whose
   energy spreads across many frequencies. */
static uint64_t prediction_satd(const Plane *source, int block_x,
                                int block_y,
                                const uint8_t prediction[64]) {
    int transformed[64];
    for (int row = 0; row < 8; row++) {
        for (int column = 0; column < 8; column++) {
            int index = row * 8 + column;
            int original = sample_clamped(source, block_x * 8 + column,
                                          block_y * 8 + row);
            transformed[index] = original - prediction[index];
        }
        hadamard8(transformed + row * 8);
    }
    for (int column = 0; column < 8; column++) {
        int vertical[8];
        for (int row = 0; row < 8; row++)
            vertical[row] = transformed[row * 8 + column];
        hadamard8(vertical);
        for (int row = 0; row < 8; row++)
            transformed[row * 8 + column] = vertical[row];
    }
    uint64_t score = 0;
    for (int index = 0; index < 64; index++) {
        int value = transformed[index];
        score += (uint64_t)(value < 0 ? -value : value);
    }
    return score;
}

static int quantize_residual_details(const Plane *source, int block_x,
                                     int block_y,
                                     const uint8_t prediction[64],
                                     const IntraQuant *quant,
                                     short output[64],
                                     float ideal_levels[64]) {
    float block[64], transformed[64];
    for (int row = 0; row < 8; row++) {
        for (int column = 0; column < 8; column++) {
            int index = row * 8 + column;
            int original = sample_clamped(source, block_x * 8 + column,
                                          block_y * 8 + row);
            block[index] = (float)(original - prediction[index] + 128);
        }
    }
    dct_block_fast(block, transformed);
    for (int position = 0; position < 64; position++) {
        int natural = ZIGZAG[position];
        float ideal = transformed[natural] * quant->reciprocal[natural];
        long value = lrintf(ideal);
        if (value < SHRT_MIN || value > SHRT_MAX) return 0;
        output[position] = (short) value;
        if (ideal_levels) ideal_levels[position] = ideal;
    }
    return 1;
}

static int quantize_residual(const Plane *source, int block_x, int block_y,
                             const uint8_t prediction[64],
                             const IntraQuant *quant, short output[64]) {
    return quantize_residual_details(source, block_x, block_y, prediction,
                                     quant, output, NULL);
}

static int choose_mode(const Plane *source, const Plane *reconstructed,
                       int block_x, int block_y, uint8_t neutral,
                       uint8_t prediction[64]) {
    uint64_t best_satd = UINT64_MAX;
    int best_mode = N148_INTRA_DC;
    uint8_t candidate_prediction[64];
    for (int mode = 0; mode < N148_INTRA_MODE_COUNT; mode++) {
        prediction_block(reconstructed, block_x, block_y, mode, neutral,
                         candidate_prediction);
        uint64_t satd = prediction_satd(source, block_x, block_y,
                                        candidate_prediction);
        if (satd < best_satd) {
            best_satd = satd;
            best_mode = mode;
            memcpy(prediction, candidate_prediction,
                   sizeof(candidate_prediction));
        }
    }
    return best_mode;
}

static void reconstruct_block(const short coefficients[64],
                              const uint8_t prediction[64],
                              const IntraQuant *quant, Plane *output,
                              int block_x, int block_y) {
    float residual[64] = {0};
    for (int position = 0; position < 64; position++) {
        int natural = ZIGZAG[position];
        residual[natural] = coefficients[position] * quant->multiplier[natural];
    }
    n148_idct_block_scalar(residual, residual);
    int max_x = block_x * 8 + 8 <= output->width ?
        8 : output->width - block_x * 8;
    int max_y = block_y * 8 + 8 <= output->height ?
        8 : output->height - block_y * 8;
    for (int row = 0; row < max_y; row++) {
        uint8_t *destination = output->data +
            (long)(block_y * 8 + row) * output->width + block_x * 8;
        for (int column = 0; column < max_x; column++) {
            int index = row * 8 + column;
            float value = prediction[index] + residual[index] - 128.0f;
            if (value < 0.0f) value = 0.0f;
            if (value > 255.0f) value = 255.0f;
            destination[column] = (uint8_t)(value + 0.5f);
        }
    }
}

static uint64_t reconstructed_block_error(
    const Plane *source, int block_x, int block_y,
    const short coefficients[64], const uint8_t prediction[64],
    const IntraQuant *quant) {
    float residual[64] = {0.0f};
    for (int position = 0; position < 64; position++) {
        int natural = ZIGZAG[position];
        residual[natural] = coefficients[position] * quant->multiplier[natural];
    }
    n148_idct_block_scalar(residual, residual);
    int max_x = source->width - block_x * 8;
    int max_y = source->height - block_y * 8;
    if (max_x > 8) max_x = 8;
    if (max_y > 8) max_y = 8;
    uint64_t error = 0;
    for (int row = 0; row < max_y; row++) {
        for (int column = 0; column < max_x; column++) {
            int index = row * 8 + column;
            float value = prediction[index] + residual[index] - 128.0f;
            if (value < 0.0f) value = 0.0f;
            if (value > 255.0f) value = 255.0f;
            int reconstructed = (int)(value + 0.5f);
            int original = source->data[
                (long)(block_y * 8 + row) * source->width + block_x * 8 +
                column];
            int difference = original - reconstructed;
            error += (uint64_t)(difference * difference);
        }
    }
    return error;
}

static double prediction_mode_bits(const uint8_t *modes, long block,
                                   int blocks_x, int candidate) {
    int has_left = block % blocks_x != 0;
    int has_top = block >= blocks_x;
    if (!has_left && !has_top) return 2.0;
    int left = has_left ? modes[block - 1] : -1;
    int top = has_top ? modes[block - blocks_x] : -1;
    if (has_left && has_top && left != top)
        return candidate == left || candidate == top ? 1.25 : 3.0;
    int prediction = has_left ? left : top;
    return candidate == prediction ? 0.5 : 2.75;
}

static int choose_mode_rdo(
    const Plane *source, const Plane *reconstructed, int block_x, int block_y,
    uint8_t neutral, const IntraQuant *quant, const uint8_t *modes,
    long block, int blocks_x, int effort, double lambda,
    uint8_t prediction[64], short coefficients[64]) {
    double best_cost = DBL_MAX;
    int best_mode = -1;
    int first_mode = 0;
    int last_mode = N148_INTRA_MODE_COUNT;
    uint8_t candidate_prediction[64];
    short candidate_coefficients[64];
    float ideal_levels[64];
    float best_ideal_levels[64];
    if (effort >= 3 && effort < 8) {
        first_mode = choose_mode(source, reconstructed, block_x, block_y,
                                 neutral, candidate_prediction);
        last_mode = first_mode + 1;
    }
    for (int mode = first_mode; mode < last_mode; mode++) {
        prediction_block(reconstructed, block_x, block_y, mode, neutral,
                         candidate_prediction);
        if (!quantize_residual_details(
                source, block_x, block_y, candidate_prediction, quant,
                candidate_coefficients, ideal_levels)) return -1;
        if (effort >= 8 && !n148_rdo_refine_coefficients_trusted(
                ideal_levels, quant->unit_energy,
                lambda * N148_RDO_TRELLIS_LAMBDA_SCALE, effort,
                candidate_coefficients, NULL)) return -1;
        uint64_t distortion = reconstructed_block_error(
            source, block_x, block_y, candidate_coefficients,
            candidate_prediction, quant);
        double rate = n148_rdo_estimate_block_bits(candidate_coefficients) +
            prediction_mode_bits(modes, block, blocks_x, mode);
        double cost = distortion +
            lambda * N148_RDO_MODE_LAMBDA_SCALE * rate;
        if (cost < best_cost) {
            best_cost = cost;
            best_mode = mode;
            memcpy(prediction, candidate_prediction,
                   sizeof(candidate_prediction));
            memcpy(coefficients, candidate_coefficients,
                   sizeof(candidate_coefficients));
            memcpy(best_ideal_levels, ideal_levels, sizeof(ideal_levels));
        }
    }
    if (best_mode < 0) return -1;
    if (effort >= 3 && effort < 8 &&
        !n148_rdo_refine_coefficients_trusted(
            best_ideal_levels, quant->unit_energy,
            lambda * N148_RDO_TRELLIS_LAMBDA_SCALE, effort,
            coefficients, NULL)) return -1;
    return best_mode;
}

static unsigned long long coefficient_mask(const short coefficients[64]) {
    unsigned long long mask = 0;
    for (int index = 0; index < 64; index++)
        if (coefficients[index] != 0) mask |= 1ull << index;
    return mask;
}

static int signed_round_division(int64_t value, int divisor, int *result) {
    if (!result || divisor <= 0) return 0;
    int64_t rounded = value >= 0 ?
        (value + divisor / 2) / divisor :
        -((-value + divisor / 2) / divisor);
    if (rounded < INT_MIN || rounded > INT_MAX) return 0;
    *result = (int) rounded;
    return 1;
}

static int build_variable_quant_from_table(const int table[8][8], int size,
                                           VariableQuant *quant) {
    if (!table || !quant || (size != 4 && size != 16)) return 0;
    quant->size = size;
    int denominator = size - 1;
    for (int row = 0; row < size; row++) {
        int source_row = (row * 7 + denominator / 2) / denominator;
        for (int column = 0; column < size; column++) {
            int source_column =
                (column * 7 + denominator / 2) / denominator;
            int value = table[source_row][source_column];
            if (value < 1 || value > 255) return 0;
            quant->step[row * size + column] = value;
        }
    }
    return 1;
}

static int build_variable_quant(const int base[8][8], int quality, int size,
                                VariableQuant *quant) {
    int table[8][8];
    scale_table(base, quality, table);
    return build_variable_quant_from_table((const int (*)[8]) table,
                                           size, quant);
}

static int build_adaptive_variable_quants(
    const int base[8][8], int quality, int size,
    VariableQuant quants[N148_AQ_LEVEL_COUNT]) {
    int scaled[8][8], adjusted[8][8];
    scale_table(base, quality, scaled);
    for (int level = 0; level < N148_AQ_LEVEL_COUNT; level++) {
        if (!n148_adaptive_adjust_table(
                (const int (*)[8]) scaled, (uint8_t) level, adjusted) ||
            !build_variable_quant_from_table(
                (const int (*)[8]) adjusted, size, &quants[level])) return 0;
    }
    return 1;
}

static void prediction_square(const Plane *reconstructed, int x0, int y0,
                              int size, int mode, uint8_t neutral,
                              uint8_t prediction[16 * 16]) {
    int has_top = y0 > 0;
    int has_left = x0 > 0;
    uint8_t top[16], left[16];
    int top_sum = 0;
    int left_sum = 0;
    for (int index = 0; index < size; index++) {
        top[index] = has_top ? (uint8_t) sample_clamped(
            reconstructed, x0 + index, y0 - 1) : neutral;
        left[index] = has_left ? (uint8_t) sample_clamped(
            reconstructed, x0 - 1, y0 + index) : neutral;
        top_sum += top[index];
        left_sum += left[index];
    }
    int top_left = has_top && has_left ?
        sample_clamped(reconstructed, x0 - 1, y0 - 1) : neutral;
    int dc = neutral;
    if (has_top && has_left)
        dc = (top_sum + left_sum + size) / (size * 2);
    else if (has_top) dc = (top_sum + size / 2) / size;
    else if (has_left) dc = (left_sum + size / 2) / size;
    for (int row = 0; row < size; row++) {
        for (int column = 0; column < size; column++) {
            int value;
            switch (mode) {
                case N148_INTRA_DC: value = dc; break;
                case N148_INTRA_VERTICAL: value = top[column]; break;
                case N148_INTRA_HORIZONTAL: value = left[row]; break;
                case N148_INTRA_TRUE_MOTION:
                    value = left[row] + top[column] - top_left;
                    break;
                default: value = neutral; break;
            }
            prediction[row * size + column] = clamp_byte(value);
        }
    }
}

static void hadamard_power_of_two(int *values, int size) {
    for (int span = 1; span < size; span *= 2) {
        for (int first = 0; first < size; first += span * 2) {
            for (int offset = 0; offset < span; offset++) {
                int a = values[first + offset];
                int b = values[first + offset + span];
                values[first + offset] = a + b;
                values[first + offset + span] = a - b;
            }
        }
    }
}

static uint64_t prediction_square_satd(const Plane *source, int x0, int y0,
                                       int size,
                                       const uint8_t *prediction) {
    int transformed[16 * 16];
    for (int row = 0; row < size; row++) {
        for (int column = 0; column < size; column++) {
            transformed[row * size + column] =
                sample_clamped(source, x0 + column, y0 + row) -
                prediction[row * size + column];
        }
        hadamard_power_of_two(transformed + row * size, size);
    }
    for (int column = 0; column < size; column++) {
        int vertical[16];
        for (int row = 0; row < size; row++)
            vertical[row] = transformed[row * size + column];
        hadamard_power_of_two(vertical, size);
        for (int row = 0; row < size; row++)
            transformed[row * size + column] = vertical[row];
    }
    uint64_t score = 0;
    for (int index = 0; index < size * size; index++) {
        int value = transformed[index];
        score += (uint64_t)(value < 0 ? -value : value);
    }
    return score;
}

static int choose_square_mode(const Plane *source,
                              const Plane *reconstructed,
                              int x0, int y0, int size, uint8_t neutral,
                              uint8_t prediction[16 * 16]) {
    uint64_t best_score = UINT64_MAX;
    int best_mode = N148_INTRA_DC;
    uint8_t candidate[16 * 16];
    for (int mode = 0; mode < N148_INTRA_MODE_COUNT; mode++) {
        prediction_square(reconstructed, x0, y0, size, mode, neutral,
                          candidate);
        uint64_t score = prediction_square_satd(
            source, x0, y0, size, candidate);
        if (score < best_score) {
            best_score = score;
            best_mode = mode;
            memcpy(prediction, candidate, (size_t) size * (size_t) size);
        }
    }
    return best_mode;
}

static int quantize_integer_region(const Plane *source, int x0, int y0,
                                   const uint8_t *prediction,
                                   int prediction_stride,
                                   int prediction_x, int prediction_y,
                                   const VariableQuant *quant,
                                   short *output) {
    int size = quant ? quant->size : 0;
    if (!source || !source->data || !prediction || !quant || !output ||
        (size != 4 && size != 16) || prediction_stride < size) return 0;
    int32_t residual[16 * 16], transformed[16 * 16];
    for (int row = 0; row < size; row++) {
        for (int column = 0; column < size; column++) {
            residual[row * size + column] =
                sample_clamped(source, x0 + column, y0 + row) -
                prediction[(prediction_y + row) * prediction_stride +
                           prediction_x + column];
        }
    }
    if (!n148_variable_forward(residual, size, transformed)) return 0;
    for (int position = 0; position < size * size; position++) {
        int natural = n148_variable_zigzag(size, position);
        int value;
        if (natural < 0 || !signed_round_division(
                transformed[natural], quant->step[natural], &value) ||
            value < SHRT_MIN || value > SHRT_MAX) return 0;
        output[position] = (short) value;
    }
    return 1;
}

static int reconstruct_integer_region(const short *coefficients,
                                       const uint8_t *prediction,
                                       int prediction_stride,
                                       int prediction_x, int prediction_y,
                                       const VariableQuant *quant,
                                       Plane *output, int x0, int y0) {
    int size = quant ? quant->size : 0;
    if (!coefficients || !prediction || !quant || !output || !output->data ||
        (size != 4 && size != 16) || prediction_stride < size) return 0;
    int32_t transformed[16 * 16] = {0}, residual[16 * 16];
    for (int position = 0; position < size * size; position++) {
        int natural = n148_variable_zigzag(size, position);
        if (natural < 0) return 0;
        transformed[natural] =
            (int32_t) coefficients[position] * quant->step[natural];
    }
    if (!n148_variable_inverse(transformed, size, residual)) return 0;
    int max_x = output->width - x0;
    int max_y = output->height - y0;
    if (max_x > size) max_x = size;
    if (max_y > size) max_y = size;
    if (max_x <= 0 || max_y <= 0) return 1;
    for (int row = 0; row < max_y; row++) {
        uint8_t *destination = output->data +
            (long)(y0 + row) * output->width + x0;
        for (int column = 0; column < max_x; column++) {
            int value = prediction[(prediction_y + row) * prediction_stride +
                                   prediction_x + column] +
                residual[row * size + column];
            destination[column] = clamp_byte(value);
        }
    }
    return 1;
}

static int quantize_plane(const Plane *source, int quality, int plane_index,
                          int perceptual_color,
                          const N148AdaptiveMap *adaptive_map,
                          int subsample_x, int subsample_y,
                          int rdo_effort, int loop_filter,
                          N148CoeffPlane *coefficients, uint8_t *modes) {
    size_t count;
    if (!source || !source->data || !modes || rdo_effort < 0 ||
        rdo_effort > 9 || (loop_filter != 0 && loop_filter != 1) ||
        !checked_block_count(
            source->width, source->height, &count) ||
        !allocate_coefficients(count, coefficients)) return 0;
    Plane reconstructed = create_plane(source->width, source->height);
    if (!reconstructed.data) {
        n148_free_coeff_plane(coefficients);
        return 0;
    }
    IntraQuant quant;
    const int (*base)[8];
    if (perceptual_color) {
        base = plane_index ? Q_PERCEPTUAL_OPPONENT_BASE :
                              Q_PERCEPTUAL_INTENSITY_BASE;
    } else {
        base = plane_index ? Q_CHROMA_BASE : Q_LUMA_BASE;
    }
    build_quant(base, quality, &quant);
    IntraQuant adaptive_quants[N148_AQ_LEVEL_COUNT];
    if (adaptive_map &&
        !build_adaptive_quants(base, quality, adaptive_quants)) {
        free_plane(&reconstructed);
        n148_free_coeff_plane(coefficients);
        return 0;
    }
    if (rdo_effort >= 3) {
        prepare_rdo_energy(&quant);
        if (adaptive_map) {
            for (int level = 0; level < N148_AQ_LEVEL_COUNT; level++)
                prepare_rdo_energy(&adaptive_quants[level]);
        }
    }
    int blocks_x = source->width / 8 + (source->width % 8 != 0);
    int blocks_y = source->height / 8 + (source->height % 8 != 0);
    int success = 1;
    for (int block_y = 0; block_y < blocks_y && success; block_y++) {
        for (int block_x = 0; block_x < blocks_x; block_x++) {
            long block = (long) block_y * blocks_x + block_x;
            uint8_t prediction[64];
            short *values = coefficients->coefficients + block * 64;
            const IntraQuant *block_quant = &quant;
            uint8_t level = N148_AQ_INITIAL_LEVEL;
            if (adaptive_map) {
                if (!n148_adaptive_level_for_block(
                        adaptive_map, block_x, block_y,
                        subsample_x, subsample_y, &level)) {
                    success = 0;
                    break;
                }
                block_quant = &adaptive_quants[level];
            }
            int mode;
            if (rdo_effort >= 3) {
                double lambda = 0.85 * block_quant->unit_energy[0];
                mode = choose_mode_rdo(
                    source, &reconstructed, block_x, block_y,
                    prediction_neutral(plane_index, perceptual_color),
                    block_quant, modes, block, blocks_x, rdo_effort, lambda,
                    prediction, values);
                if (mode < 0) {
                    success = 0;
                    break;
                }
            } else {
                mode = choose_mode(
                    source, &reconstructed, block_x, block_y,
                    prediction_neutral(plane_index, perceptual_color),
                    prediction);
                if (!quantize_residual(source, block_x, block_y, prediction,
                                       block_quant, values)) {
                    success = 0;
                    break;
                }
            }
            modes[block] = (uint8_t) mode;
            coefficients->nonzero_masks[block] = coefficient_mask(values);
            reconstruct_block(values, prediction, block_quant, &reconstructed,
                              block_x, block_y);
            if (loop_filter && !n148_loop_filter_block(
                    &reconstructed, block_x * 8, block_y * 8, 8,
                    quality, plane_index, level, NULL)) {
                success = 0;
                break;
            }
        }
    }
    free_plane(&reconstructed);
    if (!success) n148_free_coeff_plane(coefficients);
    return success;
}

static int quantize_variable_plane(
    const Plane *source, int quality, int plane_index, int perceptual_color,
    const N148AdaptiveMap *adaptive_map, int subsample_x, int subsample_y,
    const N148TransformMap *transform_map,
    int rdo_effort, int loop_filter,
    N148CoeffPlane *coefficients, uint8_t *modes) {
    size_t count;
    if (!source || !source->data || !transform_map || !modes ||
        plane_index < 0 || plane_index > 2 || rdo_effort < 0 ||
        rdo_effort > 9 || (loop_filter != 0 && loop_filter != 1) ||
        !checked_block_count(source->width, source->height, &count) ||
        !allocate_coefficients(count, coefficients)) return 0;
    int blocks_x = source->width / 8 + (source->width % 8 != 0);
    int blocks_y = source->height / 8 + (source->height % 8 != 0);
    if (transform_map->blocks_x[plane_index] != blocks_x ||
        transform_map->blocks_y[plane_index] != blocks_y) {
        n148_free_coeff_plane(coefficients);
        return 0;
    }

    Plane reconstructed = create_plane(source->width, source->height);
    if (!reconstructed.data) {
        n148_free_coeff_plane(coefficients);
        return 0;
    }
    const int (*base)[8];
    if (perceptual_color) {
        base = plane_index ? Q_PERCEPTUAL_OPPONENT_BASE :
                             Q_PERCEPTUAL_INTENSITY_BASE;
    } else {
        base = plane_index ? Q_CHROMA_BASE : Q_LUMA_BASE;
    }
    IntraQuant quant8;
    VariableQuant quant4, quant16;
    build_quant(base, quality, &quant8);
    if (!build_variable_quant(base, quality, 4, &quant4) ||
        !build_variable_quant(base, quality, 16, &quant16)) {
        free_plane(&reconstructed);
        n148_free_coeff_plane(coefficients);
        return 0;
    }
    IntraQuant adaptive8[N148_AQ_LEVEL_COUNT];
    VariableQuant adaptive4[N148_AQ_LEVEL_COUNT];
    VariableQuant adaptive16[N148_AQ_LEVEL_COUNT];
    if (adaptive_map &&
        (!build_adaptive_quants(base, quality, adaptive8) ||
         !build_adaptive_variable_quants(base, quality, 4, adaptive4) ||
         !build_adaptive_variable_quants(base, quality, 16, adaptive16))) {
        free_plane(&reconstructed);
        n148_free_coeff_plane(coefficients);
        return 0;
    }
    if (rdo_effort >= 3) {
        prepare_rdo_energy(&quant8);
        if (adaptive_map) {
            for (int level = 0; level < N148_AQ_LEVEL_COUNT; level++)
                prepare_rdo_energy(&adaptive8[level]);
        }
    }

    uint8_t neutral = prediction_neutral(plane_index, perceptual_color);
    int success = 1;
    for (int macro_y = 0;
         macro_y < transform_map->rows[plane_index] && success; macro_y++) {
        for (int macro_x = 0;
             macro_x < transform_map->columns[plane_index]; macro_x++) {
            uint8_t strategy;
            if (!n148_transform_strategy_at(transform_map, plane_index,
                                            macro_x, macro_y, &strategy)) {
                success = 0;
                break;
            }
            int first_block_x = macro_x * 2;
            int first_block_y = macro_y * 2;
            if (strategy == N148_TRANSFORM_DCT16) {
                if (first_block_x + 1 >= blocks_x ||
                    first_block_y + 1 >= blocks_y) {
                    success = 0;
                    break;
                }
                uint8_t prediction[16 * 16];
                int mode = choose_square_mode(
                    source, &reconstructed, first_block_x * 8,
                    first_block_y * 8, 16, neutral, prediction);
                const VariableQuant *block_quant = &quant16;
                uint8_t level = N148_AQ_INITIAL_LEVEL;
                if (adaptive_map) {
                    if (!n148_adaptive_level_for_block(
                            adaptive_map, first_block_x, first_block_y,
                            subsample_x, subsample_y, &level)) {
                        success = 0;
                        break;
                    }
                    block_quant = &adaptive16[level];
                }
                short sequence[16 * 16];
                if (!quantize_integer_region(
                        source, first_block_x * 8, first_block_y * 8,
                        prediction, 16, 0, 0, block_quant, sequence)) {
                    success = 0;
                    break;
                }
                for (int chunk = 0; chunk < 4; chunk++) {
                    int block_x = first_block_x + (chunk & 1);
                    int block_y = first_block_y + (chunk >> 1);
                    long block = (long) block_y * blocks_x + block_x;
                    short *values = coefficients->coefficients + block * 64;
                    memcpy(values, sequence + chunk * 64,
                           64 * sizeof(*values));
                    modes[block] = (uint8_t) mode;
                    coefficients->nonzero_masks[block] =
                        coefficient_mask(values);
                }
                if (!reconstruct_integer_region(
                        sequence, prediction, 16, 0, 0, block_quant,
                        &reconstructed, first_block_x * 8,
                        first_block_y * 8) ||
                    (loop_filter && !n148_loop_filter_block(
                        &reconstructed, first_block_x * 8,
                        first_block_y * 8, 16, quality, plane_index,
                        level, NULL))) {
                    success = 0;
                    break;
                }
                continue;
            }

            for (int cell_y = 0; cell_y < 2 && success; cell_y++) {
                int block_y = first_block_y + cell_y;
                if (block_y >= blocks_y) continue;
                for (int cell_x = 0; cell_x < 2; cell_x++) {
                    int block_x = first_block_x + cell_x;
                    if (block_x >= blocks_x) continue;
                    long block = (long) block_y * blocks_x + block_x;
                    short *values = coefficients->coefficients + block * 64;
                    uint8_t prediction[64];
                    uint8_t level = N148_AQ_INITIAL_LEVEL;
                    if (adaptive_map && !n148_adaptive_level_for_block(
                            adaptive_map, block_x, block_y, subsample_x,
                            subsample_y, &level)) {
                        success = 0;
                        break;
                    }
                    if (strategy == N148_TRANSFORM_DCT8) {
                        const IntraQuant *block_quant = adaptive_map ?
                            &adaptive8[level] : &quant8;
                        int mode;
                        if (rdo_effort >= 3) {
                            double lambda =
                                0.85 * block_quant->unit_energy[0];
                            mode = choose_mode_rdo(
                                source, &reconstructed, block_x, block_y,
                                neutral, block_quant, modes, block, blocks_x,
                                rdo_effort, lambda, prediction, values);
                            if (mode < 0) {
                                success = 0;
                                break;
                            }
                        } else {
                            mode = choose_mode(
                                source, &reconstructed, block_x, block_y,
                                neutral, prediction);
                            if (!quantize_residual(
                                    source, block_x, block_y, prediction,
                                    block_quant, values)) {
                                success = 0;
                                break;
                            }
                        }
                        modes[block] = (uint8_t) mode;
                        reconstruct_block(values, prediction, block_quant,
                                          &reconstructed, block_x, block_y);
                    } else if (strategy == N148_TRANSFORM_DCT4) {
                        int mode = choose_mode(
                            source, &reconstructed, block_x, block_y, neutral,
                            prediction);
                        modes[block] = (uint8_t) mode;
                        const VariableQuant *block_quant = adaptive_map ?
                            &adaptive4[level] : &quant4;
                        for (int part = 0; part < 4; part++) {
                            int offset_x = (part & 1) * 4;
                            int offset_y = (part >> 1) * 4;
                            if (!quantize_integer_region(
                                    source, block_x * 8 + offset_x,
                                    block_y * 8 + offset_y, prediction, 8,
                                    offset_x, offset_y, block_quant,
                                    values + part * 16) ||
                                !reconstruct_integer_region(
                                    values + part * 16, prediction, 8,
                                    offset_x, offset_y, block_quant,
                                    &reconstructed, block_x * 8 + offset_x,
                                    block_y * 8 + offset_y)) {
                                success = 0;
                                break;
                            }
                        }
                    } else {
                        success = 0;
                        break;
                    }
                    coefficients->nonzero_masks[block] =
                        coefficient_mask(values);
                    if (success && loop_filter && !n148_loop_filter_block(
                            &reconstructed, block_x * 8, block_y * 8, 8,
                            quality, plane_index, level, NULL)) success = 0;
                    if (!success) break;
                }
            }
        }
    }
    free_plane(&reconstructed);
    if (!success) n148_free_coeff_plane(coefficients);
    return success;
}

int n148_intra_quantize_planes(const Plane *y, const Plane *cb,
                               const Plane *cr, int quality,
                               int perceptual_color,
                               const N148AdaptiveMap *adaptive_map,
                               const N148TransformMap *transform_map,
                               int rdo_effort, int loop_filter,
                               N148CoeffPlane coefficients[3],
                               uint8_t **modes, size_t *mode_count) {
    if (!y || !cb || !cr || !coefficients || !modes || !mode_count ||
        quality < 1 || quality > 100 || rdo_effort < 0 || rdo_effort > 9 ||
        (loop_filter != 0 && loop_filter != 1))
        return 0;
    memset(coefficients, 0, 3 * sizeof(*coefficients));
    *modes = NULL;
    *mode_count = 0;
    size_t y_count, cb_count, cr_count;
    if (!checked_block_count(y->width, y->height, &y_count) ||
        !checked_block_count(cb->width, cb->height, &cb_count) ||
        !checked_block_count(cr->width, cr->height, &cr_count) ||
        cb_count > SIZE_MAX - y_count ||
        cr_count > SIZE_MAX - y_count - cb_count) return 0;
    size_t total = y_count + cb_count + cr_count;
    uint8_t *all_modes = (uint8_t *) malloc(total);
    if (!all_modes) return 0;
    init_dct_tables();
    int subsample_x = cb->width < y->width;
    int subsample_y = cb->height < y->height;
    if (cr->width != cb->width || cr->height != cb->height) {
        free(all_modes);
        return 0;
    }
    if (transform_map && !n148_transform_map_validate(transform_map)) {
        free(all_modes);
        return 0;
    }
    int success;
    if (transform_map) {
        success = quantize_variable_plane(
            y, quality, 0, perceptual_color, adaptive_map, 0, 0,
            transform_map, rdo_effort, loop_filter,
            &coefficients[0], all_modes) &&
            quantize_variable_plane(
                cb, quality, 1, perceptual_color, adaptive_map,
                subsample_x, subsample_y, transform_map, rdo_effort,
                loop_filter,
                &coefficients[1], all_modes + y_count) &&
            quantize_variable_plane(
                cr, quality, 2, perceptual_color, adaptive_map,
                subsample_x, subsample_y, transform_map, rdo_effort,
                loop_filter,
                &coefficients[2], all_modes + y_count + cb_count);
    } else {
        success = quantize_plane(y, quality, 0, perceptual_color,
                                 adaptive_map, 0, 0, rdo_effort, loop_filter,
                                 &coefficients[0], all_modes) &&
            quantize_plane(cb, quality, 1, perceptual_color,
                           adaptive_map, subsample_x, subsample_y, rdo_effort,
                           loop_filter,
                           &coefficients[1], all_modes + y_count) &&
            quantize_plane(cr, quality, 2, perceptual_color,
                           adaptive_map, subsample_x, subsample_y, rdo_effort,
                           loop_filter,
                           &coefficients[2], all_modes + y_count + cb_count);
    }
    if (!success) {
        for (int plane = 0; plane < 3; plane++)
            n148_free_coeff_plane(&coefficients[plane]);
        free(all_modes);
        return 0;
    }
    *modes = all_modes;
    *mode_count = total;
    return 1;
}

static int reconstruct_plane(const N148CoeffPlane *coefficients,
                             const uint8_t *modes, size_t mode_count,
                             int width, int height, int quality,
                             int plane_index, int perceptual_color,
                             const N148AdaptiveMap *adaptive_map,
                             int subsample_x, int subsample_y,
                             int loop_filter,
                             Plane *output) {
    size_t expected;
    if (!coefficients || !coefficients->coefficients || !modes || !output ||
        !checked_block_count(width, height, &expected) ||
        mode_count != expected || coefficients->count != (long) expected ||
        (loop_filter != 0 && loop_filter != 1))
        return 0;
    *output = create_plane(width, height);
    if (!output->data) return 0;
    IntraQuant quant;
    const int (*base)[8];
    if (perceptual_color) {
        base = plane_index ? Q_PERCEPTUAL_OPPONENT_BASE :
                              Q_PERCEPTUAL_INTENSITY_BASE;
    } else {
        base = plane_index ? Q_CHROMA_BASE : Q_LUMA_BASE;
    }
    build_quant(base, quality, &quant);
    IntraQuant adaptive_quants[N148_AQ_LEVEL_COUNT];
    if (adaptive_map &&
        !build_adaptive_quants(base, quality, adaptive_quants)) {
        free_plane(output);
        return 0;
    }
    int blocks_x = width / 8 + (width % 8 != 0);
    int blocks_y = height / 8 + (height % 8 != 0);
    for (int block_y = 0; block_y < blocks_y; block_y++) {
        for (int block_x = 0; block_x < blocks_x; block_x++) {
            long block = (long) block_y * blocks_x + block_x;
            int mode = modes[block];
            if (mode < 0 || mode >= N148_INTRA_MODE_COUNT) {
                free_plane(output);
                return 0;
            }
            uint8_t prediction[64];
            const IntraQuant *block_quant = &quant;
            uint8_t level = N148_AQ_INITIAL_LEVEL;
            if (adaptive_map) {
                if (!n148_adaptive_level_for_block(
                        adaptive_map, block_x, block_y,
                        subsample_x, subsample_y, &level)) {
                    free_plane(output);
                    return 0;
                }
                block_quant = &adaptive_quants[level];
            }
            prediction_block(
                output, block_x, block_y, mode,
                prediction_neutral(plane_index, perceptual_color), prediction);
            reconstruct_block(coefficients->coefficients + block * 64,
                              prediction, block_quant, output,
                              block_x, block_y);
            if (loop_filter && !n148_loop_filter_block(
                    output, block_x * 8, block_y * 8, 8, quality,
                    plane_index, level, NULL)) {
                free_plane(output);
                return 0;
            }
        }
    }
    return 1;
}

static int reconstruct_variable_plane(
    const N148CoeffPlane *coefficients, const uint8_t *modes,
    size_t mode_count, int width, int height, int quality, int plane_index,
    int perceptual_color, const N148AdaptiveMap *adaptive_map,
    int subsample_x, int subsample_y,
    const N148TransformMap *transform_map, int loop_filter, Plane *output) {
    size_t expected;
    if (!coefficients || !coefficients->coefficients || !modes || !output ||
        !transform_map || plane_index < 0 || plane_index > 2 ||
        !checked_block_count(width, height, &expected) ||
        mode_count != expected || coefficients->count != (long) expected ||
        (loop_filter != 0 && loop_filter != 1))
        return 0;
    int blocks_x = width / 8 + (width % 8 != 0);
    int blocks_y = height / 8 + (height % 8 != 0);
    if (transform_map->blocks_x[plane_index] != blocks_x ||
        transform_map->blocks_y[plane_index] != blocks_y) return 0;
    *output = create_plane(width, height);
    if (!output->data) return 0;

    const int (*base)[8];
    if (perceptual_color) {
        base = plane_index ? Q_PERCEPTUAL_OPPONENT_BASE :
                             Q_PERCEPTUAL_INTENSITY_BASE;
    } else {
        base = plane_index ? Q_CHROMA_BASE : Q_LUMA_BASE;
    }
    IntraQuant quant8;
    VariableQuant quant4, quant16;
    build_quant(base, quality, &quant8);
    if (!build_variable_quant(base, quality, 4, &quant4) ||
        !build_variable_quant(base, quality, 16, &quant16)) {
        free_plane(output);
        return 0;
    }
    IntraQuant adaptive8[N148_AQ_LEVEL_COUNT];
    VariableQuant adaptive4[N148_AQ_LEVEL_COUNT];
    VariableQuant adaptive16[N148_AQ_LEVEL_COUNT];
    if (adaptive_map &&
        (!build_adaptive_quants(base, quality, adaptive8) ||
         !build_adaptive_variable_quants(base, quality, 4, adaptive4) ||
         !build_adaptive_variable_quants(base, quality, 16, adaptive16))) {
        free_plane(output);
        return 0;
    }

    uint8_t neutral = prediction_neutral(plane_index, perceptual_color);
    for (int macro_y = 0; macro_y < transform_map->rows[plane_index];
         macro_y++) {
        for (int macro_x = 0; macro_x < transform_map->columns[plane_index];
             macro_x++) {
            uint8_t strategy;
            if (!n148_transform_strategy_at(transform_map, plane_index,
                                            macro_x, macro_y, &strategy)) {
                free_plane(output);
                return 0;
            }
            int first_block_x = macro_x * 2;
            int first_block_y = macro_y * 2;
            if (strategy == N148_TRANSFORM_DCT16) {
                if (first_block_x + 1 >= blocks_x ||
                    first_block_y + 1 >= blocks_y) {
                    free_plane(output);
                    return 0;
                }
                long first = (long) first_block_y * blocks_x + first_block_x;
                int mode = modes[first];
                if (mode < 0 || mode >= N148_INTRA_MODE_COUNT ||
                    modes[first + 1] != mode ||
                    modes[first + blocks_x] != mode ||
                    modes[first + blocks_x + 1] != mode) {
                    free_plane(output);
                    return 0;
                }
                uint8_t prediction[16 * 16];
                prediction_square(output, first_block_x * 8,
                                  first_block_y * 8, 16, mode, neutral,
                                  prediction);
                const VariableQuant *block_quant = &quant16;
                uint8_t level = N148_AQ_INITIAL_LEVEL;
                if (adaptive_map) {
                    if (!n148_adaptive_level_for_block(
                            adaptive_map, first_block_x, first_block_y,
                            subsample_x, subsample_y, &level)) {
                        free_plane(output);
                        return 0;
                    }
                    block_quant = &adaptive16[level];
                }
                short sequence[16 * 16];
                for (int chunk = 0; chunk < 4; chunk++) {
                    int block_x = first_block_x + (chunk & 1);
                    int block_y = first_block_y + (chunk >> 1);
                    long block = (long) block_y * blocks_x + block_x;
                    memcpy(sequence + chunk * 64,
                           coefficients->coefficients + block * 64,
                           64 * sizeof(*sequence));
                }
                if (!reconstruct_integer_region(
                        sequence, prediction, 16, 0, 0, block_quant, output,
                        first_block_x * 8, first_block_y * 8) ||
                    (loop_filter && !n148_loop_filter_block(
                        output, first_block_x * 8, first_block_y * 8, 16,
                        quality, plane_index, level, NULL))) {
                    free_plane(output);
                    return 0;
                }
                continue;
            }

            for (int cell_y = 0; cell_y < 2; cell_y++) {
                int block_y = first_block_y + cell_y;
                if (block_y >= blocks_y) continue;
                for (int cell_x = 0; cell_x < 2; cell_x++) {
                    int block_x = first_block_x + cell_x;
                    if (block_x >= blocks_x) continue;
                    long block = (long) block_y * blocks_x + block_x;
                    int mode = modes[block];
                    if (mode < 0 || mode >= N148_INTRA_MODE_COUNT) {
                        free_plane(output);
                        return 0;
                    }
                    uint8_t prediction[64];
                    prediction_block(output, block_x, block_y, mode, neutral,
                                     prediction);
                    uint8_t level = N148_AQ_INITIAL_LEVEL;
                    if (adaptive_map && !n148_adaptive_level_for_block(
                            adaptive_map, block_x, block_y, subsample_x,
                            subsample_y, &level)) {
                        free_plane(output);
                        return 0;
                    }
                    const short *values =
                        coefficients->coefficients + block * 64;
                    if (strategy == N148_TRANSFORM_DCT8) {
                        const IntraQuant *block_quant = adaptive_map ?
                            &adaptive8[level] : &quant8;
                        reconstruct_block(values, prediction, block_quant,
                                          output, block_x, block_y);
                    } else if (strategy == N148_TRANSFORM_DCT4) {
                        const VariableQuant *block_quant = adaptive_map ?
                            &adaptive4[level] : &quant4;
                        for (int part = 0; part < 4; part++) {
                            int offset_x = (part & 1) * 4;
                            int offset_y = (part >> 1) * 4;
                            if (!reconstruct_integer_region(
                                    values + part * 16, prediction, 8,
                                    offset_x, offset_y, block_quant, output,
                                    block_x * 8 + offset_x,
                                    block_y * 8 + offset_y)) {
                                free_plane(output);
                                return 0;
                            }
                        }
                    } else {
                        free_plane(output);
                        return 0;
                    }
                    if (loop_filter && !n148_loop_filter_block(
                            output, block_x * 8, block_y * 8, 8, quality,
                            plane_index, level, NULL)) {
                        free_plane(output);
                        return 0;
                    }
                }
            }
        }
    }
    return 1;
}

int n148_intra_reconstruct_planes(const N148CoeffPlane coefficients[3],
                                  const uint8_t *modes, size_t mode_count,
                                  int width, int height, int quality,
                                  int chroma, int perceptual_color,
                                  const N148AdaptiveMap *adaptive_map,
                                  const N148TransformMap *transform_map,
                                  int loop_filter,
                                  Plane *y, Plane *cb, Plane *cr) {
    if (!coefficients || !modes || !y || !cb || !cr ||
        width <= 0 || height <= 0 || quality < 1 || quality > 100 ||
        chroma < 0 || chroma > 2 ||
        (loop_filter != 0 && loop_filter != 1)) return 0;
    *y = (Plane){0};
    *cb = (Plane){0};
    *cr = (Plane){0};
    int chroma_width, chroma_height;
    chroma_dimensions(chroma, width, height, &chroma_width, &chroma_height);
    size_t y_count, chroma_count, expected;
    if (!checked_block_count(width, height, &y_count) ||
        !checked_block_count(chroma_width, chroma_height, &chroma_count) ||
        !n148_intra_expected_modes(width, height, chroma, &expected) ||
        mode_count != expected) return 0;
    int subsample_x = chroma != CHROMA_444;
    int subsample_y = chroma == CHROMA_420;
    if (transform_map && !n148_transform_map_validate(transform_map)) return 0;
    int success;
    if (transform_map) {
        success = reconstruct_variable_plane(
            &coefficients[0], modes, y_count, width, height, quality, 0,
            perceptual_color, adaptive_map, 0, 0, transform_map,
            loop_filter, y) &&
            reconstruct_variable_plane(
                &coefficients[1], modes + y_count, chroma_count,
                chroma_width, chroma_height, quality, 1, perceptual_color,
                adaptive_map, subsample_x, subsample_y, transform_map,
                loop_filter, cb) &&
            reconstruct_variable_plane(
                &coefficients[2], modes + y_count + chroma_count,
                chroma_count, chroma_width, chroma_height, quality, 2,
                perceptual_color, adaptive_map, subsample_x, subsample_y,
                transform_map, loop_filter, cr);
    } else {
        success = reconstruct_plane(&coefficients[0], modes, y_count,
                                    width, height, quality, 0,
                                    perceptual_color, adaptive_map, 0, 0,
                                    loop_filter, y) &&
            reconstruct_plane(&coefficients[1], modes + y_count, chroma_count,
                              chroma_width, chroma_height, quality, 1,
                              perceptual_color, adaptive_map,
                              subsample_x, subsample_y, loop_filter, cb) &&
            reconstruct_plane(
                &coefficients[2], modes + y_count + chroma_count,
                chroma_count, chroma_width, chroma_height, quality, 2,
                perceptual_color, adaptive_map, subsample_x, subsample_y,
                loop_filter, cr);
    }
    if (!success) {
        free_plane(y);
        free_plane(cb);
        free_plane(cr);
    }
    return success;
}

src/directional_intra.h

O directional_intra.h é a interface do motor de predição da V2, com as dez direções, os blocos de 4x4 e o planar do artigo 31.

O arquivo completo tem 169 linhas:

/*
 * N.148i directional and sub-block intra prediction
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#ifndef N148_DIRECTIONAL_INTRA_H
#define N148_DIRECTIONAL_INTRA_H

#include <stddef.h>
#include <stdint.h>

#include "encoder.h"
#include "ppm.h"
#include "segmentation.h"
#include "variable_transform.h"

enum {
    N148_DIRECTIONAL_INTRA_DC = 0,
    N148_DIRECTIONAL_INTRA_VERTICAL = 1,
    N148_DIRECTIONAL_INTRA_HORIZONTAL = 2,
    N148_DIRECTIONAL_INTRA_TRUE_MOTION = 3,
    N148_DIRECTIONAL_INTRA_DOWN_LEFT = 4,
    N148_DIRECTIONAL_INTRA_DOWN_RIGHT = 5,
    N148_DIRECTIONAL_INTRA_VERTICAL_RIGHT = 6,
    N148_DIRECTIONAL_INTRA_HORIZONTAL_DOWN = 7,
    N148_DIRECTIONAL_INTRA_VERTICAL_LEFT = 8,
    N148_DIRECTIONAL_INTRA_HORIZONTAL_UP = 9,
    N148_DIRECTIONAL_INTRA_MODE_COUNT = 10,
    N148_INTRA_REFERENCE_COUNT = 3,
    N148_PACKED_INTRA_MODE_COUNT =
        N148_DIRECTIONAL_INTRA_MODE_COUNT * N148_INTRA_REFERENCE_COUNT,
    N148_INTRA_MODE_SLOTS_PER_BLOCK = 4,
};

static inline int n148_intra_base_mode(int packed_mode) {
    return packed_mode % N148_DIRECTIONAL_INTRA_MODE_COUNT;
}

static inline int n148_intra_reference_index(int packed_mode) {
    return packed_mode / N148_DIRECTIONAL_INTRA_MODE_COUNT;
}

/* One causal split decision is stored per 8x8 coefficient cell. Geometry is
   retained so the entropy context resets at plane boundaries. */
typedef struct {
    uint8_t *split;
    size_t count;
    size_t plane_offsets[3];
    int blocks_x[3];
    int blocks_y[3];
} N148PartitionMap;

/* Internal calibration hook. The two transform slots are DCT4 and DCT8,
   respectively. Statistics describe the unquantized luma prediction
   residual selected by the final contextual RDO pass; coefficient positions
   are stored in each transform's natural row-major order. This is not part of
   the public library ABI. */
enum {
    N148_LUMA_STATS_DCT4 = 0,
    N148_LUMA_STATS_DCT8 = 1,
    N148_LUMA_STATS_TRANSFORM_COUNT = 2,
};

typedef struct {
    uint64_t block_count[N148_LUMA_STATS_TRANSFORM_COUNT]
                        [N148_DIRECTIONAL_INTRA_MODE_COUNT];
    double sum[N148_LUMA_STATS_TRANSFORM_COUNT]
              [N148_DIRECTIONAL_INTRA_MODE_COUNT][64];
    double sum_squares[N148_LUMA_STATS_TRANSFORM_COUNT]
                      [N148_DIRECTIONAL_INTRA_MODE_COUNT][64];
    double sum_absolute[N148_LUMA_STATS_TRANSFORM_COUNT]
                       [N148_DIRECTIONAL_INTRA_MODE_COUNT][64];
} N148LumaStatistics;

typedef enum {
    N148_TRELLIS_OFF = 0,
    N148_TRELLIS_LEGACY = 1,
    N148_TRELLIS_PERCEPTUAL_LUMA = 2
} N148TrellisPolicy;

/* Format-local encoder/decoder prediction semantics. Older formats leave
   this mask at zero, so their reconstruction stays byte-for-byte isolated. */
enum {
    N148_FIDELITY_FILTER_REFERENCES = 1u << 0,
    N148_FIDELITY_PLANAR_PREDICTION = 1u << 1,
    N148_FIDELITY_STRUCTURAL_RDO = 1u << 2,
    N148_FIDELITY_QUALITY_LAMBDA = 1u << 3,
    N148_FIDELITY_DCT32 = 1u << 4,
    N148_FIDELITY_SECOND_ORDER_DC = 1u << 5,
    N148_FIDELITY_FINE_DIRECTIONS = 1u << 6,
    N148_FIDELITY_MULTIPLE_REFERENCES = 1u << 7,
    /* Encoder-only search policy; never serialized into the format. */
    N148_FIDELITY_FAST_MODE_SEARCH = 1u << 8,
    N148_FIDELITY_SPECTRAL_LUMA_QUANT = 1u << 9,
    N148_FIDELITY_REFINED_SPECTRAL_LUMA_QUANT = 1u << 10,
    N148_FIDELITY_STRUCTURAL_LUMA_QUANT = 1u << 11,
    N148_FIDELITY_BALANCED_RECONSTRUCTION = 1u << 12,
    N148_FIDELITY_DETAIL_RECONSTRUCTION = 1u << 13,
    N148_FIDELITY_ALL = (1u << 14) - 1u,
};

int n148_fidelity_tools_set(uint32_t tools);
int n148_fidelity_quality_set(int quality);
int n148_fidelity_structural_quant(void);
int n148_fidelity_balanced_reconstruction(void);
int n148_fidelity_detail_reconstruction(void);
/* The public RGB call binds this encoder reference for its complete lifetime.
   Calls retain the existing externally serialized API contract. */
void n148_fidelity_rgb_reference(const unsigned char *pixels, size_t stride,
                                 int width, int height);

int n148_luma_statistics_begin(N148LumaStatistics *stats);
void n148_luma_statistics_end(N148LumaStatistics *stats);

/* Allocate the directional-intra partition map. The quantizer fills each entry with zero
   for one 8x8 transform or one for four 4x4 transforms. */
int n148_partition_map_allocate(int width, int height, int chroma,
                                   N148PartitionMap *map);
int n148_partition_map_validate(const N148PartitionMap *map);
uint8_t n148_partition_map_predict(const N148PartitionMap *map,
                                      size_t index);
void n148_partition_map_release(N148PartitionMap *map);

/* Quantize prediction residuals in Y, Cb, Cr order. Four mode slots are kept
   per 8x8 coefficient cell. DCT8 cells repeat their single mode in all slots;
   DCT4 cells store one causal mode per 4x4 sub-block. */
int n148_directional_intra_quantize_planes(
    const Plane *y, const Plane *cb, const Plane *cr, int quality,
    int chroma_quality, int calibrated_chroma, int calibrated_luma,
    int extended_modes,
    int split_4x4, int contextual_rdo, int effort, int trellis_policy,
    int loop_filter,
    N148PartitionMap *partition_map,
    const N148SegmentationMap *segmentation_map,
    N148TransformMap *transform_map,
    N148CoeffPlane coefficients[3], uint8_t **modes, size_t *mode_count);

/* Joint chroma intra uses one optimized decision for Cb and Cr.
   The returned internal mode layout still mirrors the selected chroma mode
   into both planes so the mature causal reconstruction path can be reused. */
int n148_joint_chroma_intra_quantize_planes(
    const Plane *y, const Plane *cb, const Plane *cr, int quality,
    int chroma_quality, int calibrated_chroma, int calibrated_luma,
    int extended_modes,
    int split_4x4, int contextual_rdo, int effort, int trellis_policy,
    int loop_filter,
    N148PartitionMap *partition_map,
    const N148SegmentationMap *segmentation_map,
    N148TransformMap *transform_map,
    N148CoeffPlane coefficients[3], uint8_t **modes, size_t *mode_count);

/* Reconstruct the three planes using the normative scalar feedback path. */
int n148_directional_intra_reconstruct_planes(
    const N148CoeffPlane coefficients[3], const uint8_t *modes,
    size_t mode_count, int width, int height, int quality,
    int chroma_quality, int calibrated_chroma, int calibrated_luma, int chroma,
    int extended_modes, int split_4x4, int loop_filter,
    const N148PartitionMap *partition_map,
    const N148SegmentationMap *segmentation_map,
    const N148TransformMap *transform_map,
    Plane *y, Plane *cb, Plane *cr);

/* Return four mode slots for every 8x8 coefficient cell in all planes. */
int n148_directional_intra_expected_modes(int width, int height, int chroma,
                                 size_t *mode_count);

#endif

src/directional_intra.c

O directional_intra.c é o maior arquivo da V2, com 6.145 linhas, porque ele junta as dez direções e o planar do artigo 31, as decisões de RDO do artigo 32, a busca que escolhe o tamanho dos blocos do artigo 33 e as camadas de reconstrução do artigo 38.

O arquivo completo tem 6.145 linhas:

/*
 * N.148i directional and sub-block intra prediction
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 *
 * The directional predictors and the partition search in this file are an
 * original, compact implementation. The encoder always predicts from pixels
 * it has already reconstructed, which gives the decoder the same information
 * and prevents drift.
 */

#include "directional_intra.h"

#include <float.h>
#include <limits.h>
#include <math.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#include "dct.h"
#include "cpu.h"
#if defined(__x86_64__) || defined(__i386__)
#include <immintrin.h>
#endif
#include "header.h"
#include "loop_filter.h"
#include "rdo.h"
#include "segmentation.h"
#include "tables.h"
#include "variable_transform.h"

typedef struct {
    float reciprocal[64];
    float multiplier[64];
    double unit_energy[64];
    double perceptual_energy[64];
    int dc_step;
} IntraQuant8;

typedef struct {
    int step[16];
    uint32_t reciprocal_q32[16];
    double unit_energy[16];
    double perceptual_energy[16];
    int dc_step;
} IntraQuant4;

typedef struct {
    int step[16 * 16];
    uint32_t reciprocal_q32[16 * 16];
    int dc_step;
} IntraQuant16;

typedef struct {
    int step[32 * 32];
    uint32_t reciprocal_q32[32 * 32];
    int dc_step;
} IntraQuant32;

typedef struct {
    short coefficients[64];
    uint8_t modes[N148_INTRA_MODE_SLOTS_PER_BLOCK];
    uint8_t pixels[64];
    uint64_t distortion;
    double proxy_bits;
} IntraBlockCandidate;

typedef struct {
    int x;
    int y;
    int width;
    int height;
    uint8_t pixels[18 * 18];
} IntraMacroSnapshot;

typedef struct {
    short coefficients[4][64];
    uint8_t modes[4][N148_INTRA_MODE_SLOTS_PER_BLOCK];
    uint8_t splits[4];
    IntraMacroSnapshot reconstruction;
    uint64_t distortion;
    double proxy_bits;
    int ending_dc_category;
} IntraMacroCandidate;

typedef struct {
    int x;
    int y;
    int width;
    int height;
    uint8_t pixels[34 * 34];
} IntraSuperSnapshot;

typedef struct {
    short coefficients[16][64];
    uint8_t modes[16][N148_INTRA_MODE_SLOTS_PER_BLOCK];
    uint8_t splits[16];
    uint8_t strategies[4];
    IntraSuperSnapshot reconstruction;
    uint64_t distortion;
    double proxy_bits;
    int ending_dc_category;
} IntraSuperCandidate;

#define BASE_TRELLIS_LAMBDA_SCALE 0.04
#define INTRA_RDO_LAMBDA_SCALE 0.85
#define CONTEXTUAL_TRELLIS_LAMBDA_SCALE 0.040
#define STRUCTURAL_TRELLIS_LAMBDA_SCALE (0.85 * BASE_TRELLIS_LAMBDA_SCALE)
#define PERCEPTUAL_LUMA_TRELLIS_LAMBDA_SCALE 0.040
#define PERCEPTUAL_LUMA_LOW_FREQUENCY_BOOST 2.0
#define PERCEPTUAL_LUMA_PROTECTED_FREQUENCY_SUM 2
#define DCT16_QUANT_SCALE_PERCENT 115
#define DCT32_QUANT_SCALE_PERCENT 115
#define INTRA_RATE_DC_BUCKETS 3
#define INTRA_RATE_BANDS 4
#define INTRA_RATE_ACTIVITY_BUCKETS 2
#define INTRA_RATE_DC_MODELS (2 * INTRA_RATE_DC_BUCKETS)
#define INTRA_RATE_AC_MODELS (2 * INTRA_RATE_BANDS * INTRA_RATE_ACTIVITY_BUCKETS)
#define INTRA_RATE_COEFFICIENT_MODELS \
    (INTRA_RATE_DC_MODELS + INTRA_RATE_AC_MODELS)
#define INTRA_RATE_MODE_CONTEXTS (N148_DIRECTIONAL_INTRA_MODE_COUNT + 2)
#define INTRA_RATE_MODE_MODELS (2 * INTRA_RATE_MODE_CONTEXTS)
#define INTRA_RATE_PARTITION_MODEL \
    (INTRA_RATE_COEFFICIENT_MODELS + INTRA_RATE_MODE_MODELS)
#define INTRA_RATE_TRANSFORM_MODEL (INTRA_RATE_PARTITION_MODEL + 1)
#define INTRA_RATE_MODEL_COUNT (INTRA_RATE_TRANSFORM_MODEL + 1)

typedef struct {
    double bits[INTRA_RATE_MODEL_COUNT][256];
} IntraRateModel;

/* Codec calls are externally serialized, so the diagnostic collector follows
   the same lifetime rule as the existing shared dispatch and scratch state.
   Keeping the sink internal avoids adding a thirteenth public ABI symbol. */
static N148LumaStatistics *luma_stats_sink;
static uint32_t fidelity_tools;
static int fidelity_quality = 50;
static double fidelity_luma_rdo_scale = INTRA_RDO_LAMBDA_SCALE;
static N148RgbSource fidelity_rgb_source;

int n148_fidelity_detail_reconstruction(void) {
    return (fidelity_tools & N148_FIDELITY_DETAIL_RECONSTRUCTION) != 0;
}

int n148_fidelity_balanced_reconstruction(void) {
    return (fidelity_tools & N148_FIDELITY_BALANCED_RECONSTRUCTION) != 0;
}

int n148_fidelity_structural_quant(void) {
    return (fidelity_tools & N148_FIDELITY_STRUCTURAL_LUMA_QUANT) != 0;
}

void n148_fidelity_rgb_reference(const unsigned char *pixels, size_t stride,
                                 int width, int height) {
    fidelity_rgb_source = (N148RgbSource){pixels, stride, width, height};
}


static const int (*luma_quant_base(int calibrated))[8] {
    if (!calibrated) return Q_LUMA_BASE;
    if (n148_fidelity_balanced_reconstruction())
        return N148_BALANCED_LUMA_QUANT_BASE;
    if (fidelity_tools & N148_FIDELITY_STRUCTURAL_LUMA_QUANT)
        return N148_STRUCTURAL_LUMA_QUANT_BASE;
    if (fidelity_tools & N148_FIDELITY_REFINED_SPECTRAL_LUMA_QUANT)
        return N148_REFINED_SPECTRAL_LUMA_QUANT_BASE;
    return (fidelity_tools & N148_FIDELITY_SPECTRAL_LUMA_QUANT) ?
        N148_SPECTRAL_LUMA_QUANT_BASE : FORMAT_5_LUMA_QUANT_BASE;
}

static void update_fidelity_luma_rdo_scale(void) {
    fidelity_luma_rdo_scale = INTRA_RDO_LAMBDA_SCALE;
    if (!(fidelity_tools & N148_FIDELITY_QUALITY_LAMBDA)) return;
    if (fidelity_quality <= 45) fidelity_luma_rdo_scale = 0.65;
    else if (fidelity_quality <= 60) fidelity_luma_rdo_scale = 0.70;
    else if (fidelity_quality <= 75) fidelity_luma_rdo_scale = 0.75;
    /* The structural profile balances final syntax decisions with its
       finer coefficient refinement; original profile scales stay intact. */
    if (fidelity_tools & N148_FIDELITY_STRUCTURAL_LUMA_QUANT)
        fidelity_luma_rdo_scale = sqrt(
            fidelity_luma_rdo_scale * STRUCTURAL_TRELLIS_LAMBDA_SCALE);
}

static int luma_mode_count(int extended_modes, int size, int effort) {
    int count = extended_modes ? N148_DIRECTIONAL_INTRA_MODE_COUNT : 4;
    if (extended_modes && size >= 8 && effort >= 5 &&
        (fidelity_tools & N148_FIDELITY_MULTIPLE_REFERENCES))
        count = N148_PACKED_INTRA_MODE_COUNT;
    return count;
}

static int luma_allowed_modes(int extended_modes) {
    if (extended_modes &&
        (fidelity_tools & N148_FIDELITY_MULTIPLE_REFERENCES))
        return N148_PACKED_INTRA_MODE_COUNT;
    return extended_modes ? N148_DIRECTIONAL_INTRA_MODE_COUNT : 4;
}

int n148_fidelity_tools_set(uint32_t tools) {
    if (tools & ~N148_FIDELITY_ALL) return 0;
    fidelity_tools = tools;
    update_fidelity_luma_rdo_scale();
    return 1;
}

int n148_fidelity_quality_set(int quality) {
    if (quality < 1 || quality > 100) return 0;
    fidelity_quality = quality;
    update_fidelity_luma_rdo_scale();
    return 1;
}

static int fidelity_luma_transform_map_validate(
    const N148TransformMap *map) {
    return n148_luma_transform_map_validate_extended(
        map, (fidelity_tools & N148_FIDELITY_DCT32) != 0);
}

int n148_luma_statistics_begin(N148LumaStatistics *stats) {
    if (!stats || luma_stats_sink) return 0;
    memset(stats, 0, sizeof(*stats));
    luma_stats_sink = stats;
    return 1;
}

void n148_luma_statistics_end(N148LumaStatistics *stats) {
    if (luma_stats_sink == stats) luma_stats_sink = NULL;
}

static int checked_block_count(int width, int height, size_t *count) {
    if (width <= 0 || height <= 0 || !count) return 0;
    size_t blocks_x = (size_t)(width / 8 + (width % 8 != 0));
    size_t blocks_y = (size_t)(height / 8 + (height % 8 != 0));
    if (blocks_y != 0 && blocks_x > SIZE_MAX / blocks_y) return 0;
    *count = blocks_x * blocks_y;
    return *count != 0 && *count <= LONG_MAX;
}

static int plane_geometry(int width, int height, int *blocks_x,
                          int *blocks_y, size_t *count) {
    if (!blocks_x || !blocks_y ||
        !checked_block_count(width, height, count)) return 0;
    *blocks_x = width / 8 + (width % 8 != 0);
    *blocks_y = height / 8 + (height % 8 != 0);
    return 1;
}

int n148_partition_map_allocate(int width, int height, int chroma,
                                   N148PartitionMap *map) {
    if (!map || chroma < CHROMA_444 || chroma > CHROMA_420) return 0;
    memset(map, 0, sizeof(*map));
    int chroma_width, chroma_height;
    chroma_dimensions(chroma, width, height, &chroma_width, &chroma_height);
    int widths[3] = {width, chroma_width, chroma_width};
    int heights[3] = {height, chroma_height, chroma_height};
    size_t total = 0;
    for (int plane = 0; plane < 3; plane++) {
        size_t count;
        map->plane_offsets[plane] = total;
        if (!plane_geometry(widths[plane], heights[plane],
                            &map->blocks_x[plane], &map->blocks_y[plane],
                            &count) || count > SIZE_MAX - total) {
            memset(map, 0, sizeof(*map));
            return 0;
        }
        total += count;
    }
    map->split = (uint8_t *) calloc(total, 1);
    if (!map->split) {
        memset(map, 0, sizeof(*map));
        return 0;
    }
    map->count = total;
    return 1;
}

int n148_partition_map_validate(const N148PartitionMap *map) {
    if (!map || !map->split || map->count == 0 ||
        map->plane_offsets[0] != 0) return 0;
    size_t offset = 0;
    for (int plane = 0; plane < 3; plane++) {
        if (map->plane_offsets[plane] != offset ||
            map->blocks_x[plane] <= 0 || map->blocks_y[plane] <= 0 ||
            (size_t) map->blocks_x[plane] >
                SIZE_MAX / (size_t) map->blocks_y[plane]) return 0;
        size_t count = (size_t) map->blocks_x[plane] *
            (size_t) map->blocks_y[plane];
        if (count > map->count - offset) return 0;
        for (size_t index = 0; index < count; index++)
            if (map->split[offset + index] > 1) return 0;
        offset += count;
    }
    return offset == map->count;
}

static int partition_plane_for_index(const N148PartitionMap *map,
                                     size_t index) {
    if (!map || index >= map->count) return -1;
    if (index >= map->plane_offsets[2]) return 2;
    if (index >= map->plane_offsets[1]) return 1;
    return 0;
}

uint8_t n148_partition_map_predict(const N148PartitionMap *map,
                                      size_t index) {
    int plane = partition_plane_for_index(map, index);
    if (plane < 0) return 0;
    size_t local = index - map->plane_offsets[plane];
    int blocks_x = map->blocks_x[plane];
    if (local % (size_t) blocks_x != 0) return map->split[index - 1];
    if (local >= (size_t) blocks_x)
        return map->split[index - (size_t) blocks_x];
    return 0;
}

void n148_partition_map_release(N148PartitionMap *map) {
    if (!map) return;
    free(map->split);
    memset(map, 0, sizeof(*map));
}

int n148_directional_intra_expected_modes(int width, int height, int chroma,
                                 size_t *mode_count) {
    if (!mode_count || chroma < CHROMA_444 || chroma > CHROMA_420) return 0;
    int chroma_width, chroma_height;
    chroma_dimensions(chroma, width, height, &chroma_width, &chroma_height);
    size_t y_count, chroma_count;
    if (!checked_block_count(width, height, &y_count) ||
        !checked_block_count(chroma_width, chroma_height, &chroma_count) ||
        chroma_count > (SIZE_MAX - y_count) / 2) return 0;
    size_t blocks = y_count + chroma_count * 2;
    if (blocks > SIZE_MAX / N148_INTRA_MODE_SLOTS_PER_BLOCK) return 0;
    *mode_count = blocks * N148_INTRA_MODE_SLOTS_PER_BLOCK;
    return 1;
}

static int allocate_coefficients(size_t count, N148CoeffPlane *output) {
    if (!output || count == 0 || count > LONG_MAX ||
        count > SIZE_MAX / (64 * sizeof(short)) ||
        count > SIZE_MAX / sizeof(*output->nonzero_masks)) return 0;
    size_t coefficient_bytes = count * 64 * sizeof(short);
    size_t mask_bytes = count * sizeof(*output->nonzero_masks);
    if (coefficient_bytes > SIZE_MAX - mask_bytes) return 0;
    output->coefficients = (short *) calloc(1, coefficient_bytes + mask_bytes);
    if (!output->coefficients) return 0;
    output->nonzero_masks = (unsigned long long *)
        ((uint8_t *) output->coefficients + coefficient_bytes);
    output->nonzero_counts = NULL;
    output->count = (long) count;
    return 1;
}

/* Private hot-loop access. Both quantize entry points and both
   reconstruction paths validate the entire immutable segmentation map before
   reaching this helper. Retain per-access geometry and level checks. */
static int segmentation_level_prevalidated(
    const N148SegmentationMap *map, int block_x, int block_y,
    int subsample_x, int subsample_y, uint8_t *level) {
    if (!map || !map->levels || !level || block_x < 0 || block_y < 0 ||
        (subsample_x != 0 && subsample_x != 1) ||
        (subsample_y != 0 && subsample_y != 1)) return 0;
    size_t region_x = ((size_t) block_x * 8u * (1u << subsample_x)) /
        N148_SEGMENT_REGION_SIZE;
    size_t region_y = ((size_t) block_y * 8u * (1u << subsample_y)) /
        N148_SEGMENT_REGION_SIZE;
    if (region_x >= (size_t)map->columns || region_y >= (size_t)map->rows)
        return 0;
    size_t index = region_y * (size_t)map->columns + region_x;
    if (index >= map->count || map->levels[index] >= N148_SEGMENT_COUNT)
        return 0;
    *level = map->levels[index];
    return 1;
}

static void build_quant8_from_table(const int table[8][8], IntraQuant8 *quant) {
    quant->dc_step = table[0][0];
    for (int row = 0; row < 8; row++) {
        for (int column = 0; column < 8; column++) {
            int index = row * 8 + column;
            double scale = aan_scale_factor(row, column);
            quant->reciprocal[index] =
                (float)(1.0 / (table[row][column] * scale));
            quant->multiplier[index] =
                (float)(table[row][column] * scale / 64.0);
        }
    }
    for (int position = 0; position < 64; position++) {
        float basis[64] = {0.0f};
        int natural = ZIGZAG[position];
        basis[natural] = quant->multiplier[natural];
        n148_idct_block_scalar(basis, basis);
        double energy = 0.0;
        double gradient_energy = 0.0;
        for (int sample = 0; sample < 64; sample++) {
            double response = basis[sample] - 128.0;
            energy += response * response;
            int row = sample / 8;
            int column = sample % 8;
            if (column > 0) {
                double previous = basis[sample - 1] - 128.0;
                double difference = response - previous;
                gradient_energy += difference * difference;
            }
            if (row > 0) {
                double previous = basis[sample - 8] - 128.0;
                double difference = response - previous;
                gradient_energy += difference * difference;
            }
        }
        quant->unit_energy[position] = energy;
        quant->perceptual_energy[position] =
            energy + 0.25 * gradient_energy;
    }
}

static void build_quant4_from_table(const int table[8][8], IntraQuant4 *quant,
                                    int apply_fidelity) {
    (void) apply_fidelity;
    quant->dc_step = table[0][0];
    for (int row = 0; row < 4; row++) {
        int source_row = (row * 7 + 1) / 3;
        for (int column = 0; column < 4; column++) {
            int source_column = (column * 7 + 1) / 3;
            int position = row * 4 + column;
            quant->step[position] = table[source_row][source_column];
            /* floor((2^32 - 1) / step) fits even for step == 1. The
               quantizer corrects its quotient by at most one. */
            quant->reciprocal_q32[position] =
                UINT32_MAX / (uint32_t) quant->step[position];
        }
    }
    for (int position = 0; position < 16; position++) {
        int32_t transformed[16] = {0};
        int32_t spatial[16];
        int natural = n148_variable_zigzag(4, position);
        transformed[natural] = quant->step[natural];
        quant->unit_energy[position] =
            n148_variable_dct4_energy(natural, quant->step[natural]);
        if (!n148_variable_inverse(transformed, 4, spatial)) {
            quant->perceptual_energy[position] =
                (double) quant->step[natural] * quant->step[natural];
            continue;
        }
        double energy = 0.0;
        double gradient_energy = 0.0;
        for (int sample = 0; sample < 16; sample++) {
            double response = spatial[sample];
            energy += response * response;
            int row = sample / 4;
            int column = sample % 4;
            if (column > 0) {
                double difference = response - spatial[sample - 1];
                gradient_energy += difference * difference;
            }
            if (row > 0) {
                double difference = response - spatial[sample - 4];
                gradient_energy += difference * difference;
            }
        }
        quant->perceptual_energy[position] =
            energy + 0.25 * gradient_energy;
    }
}

/* DCT16 has its own 16x16 step matrix. The accepted residual-luma table is
   sampled over normalized frequency coordinates instead of repeating 8x8
   cells, so equal relative frequencies retain equal quantizer strength. */
static void build_quant16_from_table(const int table[8][8],
                                     IntraQuant16 *quant) {
    for (int row = 0; row < 16; row++) {
        int source_row = (row * 7 + 7) / 15;
        for (int column = 0; column < 16; column++) {
            int source_column = (column * 7 + 7) / 15;
            int value = table[source_row][source_column];
            value = (value * (n148_fidelity_detail_reconstruction() ?
                100 : DCT16_QUANT_SCALE_PERCENT) + 50) / 100;
            if (value > 255) value = 255;
            int position = row * 16 + column;
            quant->step[position] = value;
            quant->reciprocal_q32[position] =
                UINT32_MAX / (uint32_t) value;
        }
    }
    quant->dc_step = quant->step[0];
}

static int build_segment_quantizers16(
    const int base[8][8], int quality,
    const N148SegmentationMap *segmentation_map,
    IntraQuant16 quant16[N148_SEGMENT_COUNT]) {
    int scaled[8][8];
    scale_table(base, quality, scaled);
    int levels = segmentation_map ? N148_SEGMENT_COUNT : 1;
    for (int level = 0; level < levels; level++) {
        int adjusted[8][8];
        if (segmentation_map) {
            if (!n148_segmentation_adjust_table(
                    (const int (*)[8]) scaled, segmentation_map,
                    (uint8_t) level, 0, adjusted)) return 0;
            build_quant16_from_table(
                (const int (*)[8]) adjusted, &quant16[level]);
        } else {
            build_quant16_from_table(
                (const int (*)[8]) scaled, &quant16[level]);
        }
    }
    return 1;
}

static void build_quant32_from_table(const int table[8][8],
                                     IntraQuant32 *quant) {
    for (int row = 0; row < 32; row++) {
        int source_row = (row * 7 + 15) / 31;
        for (int column = 0; column < 32; column++) {
            int source_column = (column * 7 + 15) / 31;
            int value = table[source_row][source_column];
            value = (value * DCT32_QUANT_SCALE_PERCENT + 50) / 100;
            if (value > 255) value = 255;
            int position = row * 32 + column;
            quant->step[position] = value;
            quant->reciprocal_q32[position] =
                UINT32_MAX / (uint32_t) value;
        }
    }
    quant->dc_step = quant->step[0];
}

static int build_segment_quantizers32(
    const int base[8][8], int quality,
    const N148SegmentationMap *segmentation_map,
    IntraQuant32 quant32[N148_SEGMENT_COUNT]) {
    int scaled[8][8];
    scale_table(base, quality, scaled);
    int levels = segmentation_map ? N148_SEGMENT_COUNT : 1;
    for (int level = 0; level < levels; level++) {
        int adjusted[8][8];
        if (segmentation_map) {
            if (!n148_segmentation_adjust_table(
                    (const int (*)[8]) scaled, segmentation_map,
                    (uint8_t) level, 0, adjusted)) return 0;
            build_quant32_from_table((const int (*)[8]) adjusted,
                                     &quant32[level]);
        } else {
            build_quant32_from_table((const int (*)[8]) scaled,
                                     &quant32[level]);
        }
    }
    return 1;
}

static int build_segment_quantizers(
    const int base[8][8], int quality, int plane_index,
    const N148SegmentationMap *segmentation_map,
    IntraQuant8 quant8[N148_SEGMENT_COUNT],
    IntraQuant4 quant4[N148_SEGMENT_COUNT]) {
    int scaled[8][8];
    scale_table(base, quality, scaled);
    int levels = segmentation_map && plane_index == 0 ?
        N148_SEGMENT_COUNT : 1;
    for (int level = 0; level < levels; level++) {
        int adjusted[8][8];
        if (segmentation_map) {
            if (!n148_segmentation_adjust_table(
                    (const int (*)[8]) scaled, segmentation_map,
                    (uint8_t) level,
                    plane_index, adjusted)) return 0;
            build_quant8_from_table(
                (const int (*)[8]) adjusted, &quant8[level]);
            build_quant4_from_table(
                (const int (*)[8]) adjusted, &quant4[level],
                plane_index == 0);
        } else {
            build_quant8_from_table(
                (const int (*)[8]) scaled, &quant8[level]);
            build_quant4_from_table(
                (const int (*)[8]) scaled, &quant4[level],
                plane_index == 0);
        }
    }
    return 1;
}

/* Reconstruction only reads the dequantization multipliers and 4x4 steps.
   The encoder's quantizer setup also builds reciprocal and perceptual-energy
   tables, including 64 inverse transforms per 8x8 quantizer. */
static int build_segment_decode_quantizers(
    const int base[8][8], int quality, int plane_index,
    const N148SegmentationMap *segmentation_map,
    IntraQuant8 quant8[N148_SEGMENT_COUNT],
    IntraQuant4 quant4[N148_SEGMENT_COUNT]) {
    int scaled[8][8];
    scale_table(base, quality, scaled);
    int levels = segmentation_map && plane_index == 0 ?
        N148_SEGMENT_COUNT : 1;
    for (int level = 0; level < levels; level++) {
        int adjusted[8][8];
        const int (*table)[8] = (const int (*)[8]) scaled;
        if (segmentation_map) {
            if (!n148_segmentation_adjust_table(
                    table, segmentation_map, (uint8_t) level,
                    plane_index, adjusted)) return 0;
            table = (const int (*)[8]) adjusted;
        }
        for (int row = 0; row < 8; row++) {
            for (int column = 0; column < 8; column++) {
                int index = row * 8 + column;
                double scale = aan_scale_factor(row, column);
                quant8[level].multiplier[index] =
                    (float)(table[row][column] * scale / 64.0);
            }
        }
        for (int row = 0; row < 4; row++) {
            int source_row = (row * 7 + 1) / 3;
            for (int column = 0; column < 4; column++) {
                int source_column = (column * 7 + 1) / 3;
                quant4[level].step[row * 4 + column] =
                    table[source_row][source_column];
            }
        }
    }
    return 1;
}

static int sample_clamped(const Plane *plane, int x, int y) {
    if (x < 0) x = 0;
    if (y < 0) y = 0;
    if (x >= plane->width) x = plane->width - 1;
    if (y >= plane->height) y = plane->height - 1;
    return plane->data[(long) y * plane->width + x];
}

static uint8_t clamp_byte(int value) {
    if (value < 0) return 0;
    if (value > 255) return 255;
    return (uint8_t) value;
}

static int average2(int first, int second) {
    return (first + second + 1) >> 1;
}

static int average3(int first, int middle, int last) {
    return (first + 2 * middle + last + 2) >> 2;
}

static int extended_sample(const uint8_t *values, int count, int index) {
    if (index < 0) index = 0;
    if (index >= count) index = count - 1;
    return values[index];
}

/* Boundary coordinate zero is top-left. Positive coordinates walk right on
   the top edge, while negative coordinates walk down the left edge. */
static int diagonal_boundary(const uint8_t *top, const uint8_t *left,
                             int count, int top_left, int coordinate) {
    if (coordinate == 0) return top_left;
    if (coordinate > 0)
        return extended_sample(top, count, coordinate - 1);
    return extended_sample(left, count, -coordinate - 1);
}

static int diagonal_half_sample(const uint8_t *top, const uint8_t *left,
                                int count, int top_left,
                                int coordinate_twice) {
    int lower;
    if (coordinate_twice >= 0) lower = coordinate_twice / 2;
    else lower = -((-coordinate_twice + 1) / 2);
    int remainder = coordinate_twice - 2 * lower;
    int first = diagonal_boundary(top, left, count, top_left, lower);
    if (remainder == 0) return first;
    int second = diagonal_boundary(top, left, count, top_left, lower + 1);
    return average2(first, second);
}

static int edge_half_sample(const uint8_t *edge, int count,
                            int coordinate_twice) {
    if (coordinate_twice < 0) coordinate_twice = 0;
    int index = coordinate_twice / 2;
    int first = extended_sample(edge, count, index);
    if ((coordinate_twice & 1) == 0) return first;
    return average2(first, extended_sample(edge, count, index + 1));
}

/* The 4x4 directional family alternates two-tap half-sample interpolation
   with three-tap filtering at integer positions. Keeping this rule explicit
   avoids the blocky stair steps produced by plain nearest-neighbor rays. */
static int filtered_edge_half_sample(const uint8_t *edge, int count,
                                     int coordinate_twice) {
    if (coordinate_twice < 0) coordinate_twice = 0;
    int index = coordinate_twice / 2;
    if (coordinate_twice & 1)
        return average2(extended_sample(edge, count, index),
                        extended_sample(edge, count, index + 1));
    return average3(extended_sample(edge, count, index - 1),
                    extended_sample(edge, count, index),
                    extended_sample(edge, count, index + 1));
}

static int boundary4(const uint8_t top[34], const uint8_t left[34],
                     int top_left, int coordinate) {
    if (coordinate == 0) return top_left;
    return coordinate > 0 ? top[coordinate - 1] : left[-coordinate - 1];
}

/* These equations are an independent expression of the ten VP8-style 4x4
   predictors. They use only already reconstructed top and left samples. */
static void predict_square4(const uint8_t top[34], const uint8_t left[34],
                            int edge_count, int top_left, int dc, int mode,
                            uint32_t tools,
                            uint8_t prediction[16]) {
    if (mode == N148_DIRECTIONAL_INTRA_DC) {
        memset(prediction, dc, 16);
        return;
    }
    if (mode == N148_DIRECTIONAL_INTRA_VERTICAL) {
        uint8_t predicted_row[4];
        for (int column = 0; column < 4; column++)
            predicted_row[column] = (uint8_t) average3(
                boundary4(top, left, top_left, column),
                boundary4(top, left, top_left, column + 1),
                boundary4(top, left, top_left, column + 2));
        for (int row = 0; row < 4; row++)
            memcpy(prediction + row * 4, predicted_row, 4);
        return;
    }
    if (mode == N148_DIRECTIONAL_INTRA_HORIZONTAL) {
        for (int row = 0; row < 4; row++) {
            int value = average3(
                boundary4(top, left, top_left, -row),
                boundary4(top, left, top_left, -row - 1),
                boundary4(top, left, top_left, -row - 2));
            memset(prediction + row * 4, value, 4);
        }
        return;
    }
    if (mode == N148_DIRECTIONAL_INTRA_TRUE_MOTION) {
        for (int row = 0; row < 4; row++)
            for (int column = 0; column < 4; column++)
                prediction[row * 4 + column] = clamp_byte(
                    left[row] + top[column] - top_left);
        return;
    }
    for (int row = 0; row < 4; row++) {
        for (int column = 0; column < 4; column++) {
            int value = dc;
            switch (mode) {
                case N148_DIRECTIONAL_INTRA_DC:
                    break;
                case N148_DIRECTIONAL_INTRA_VERTICAL:
                    value = average3(
                        boundary4(top, left, top_left, column),
                        boundary4(top, left, top_left, column + 1),
                        boundary4(top, left, top_left, column + 2));
                    break;
                case N148_DIRECTIONAL_INTRA_HORIZONTAL:
                    value = average3(
                        boundary4(top, left, top_left, -row),
                        boundary4(top, left, top_left, -row - 1),
                        boundary4(top, left, top_left, -row - 2));
                    break;
                case N148_DIRECTIONAL_INTRA_TRUE_MOTION:
                    /* Keep the sharper true-motion predictor for 4x4
                       detail. The planar-prediction experiment is deliberately
                       limited to larger gradient regions. */
                    value = left[row] + top[column] - top_left;
                    break;
                case N148_DIRECTIONAL_INTRA_DOWN_LEFT: {
                    int index = column + row;
                    value = average3(
                        extended_sample(top, edge_count, index),
                        extended_sample(top, edge_count, index + 1),
                        extended_sample(top, edge_count, index + 2));
                    break;
                }
                case N148_DIRECTIONAL_INTRA_DOWN_RIGHT: {
                    int coordinate = column - row;
                    value = average3(
                        boundary4(top, left, top_left, coordinate + 1),
                        boundary4(top, left, top_left, coordinate),
                        boundary4(top, left, top_left, coordinate - 1));
                    break;
                }
                case N148_DIRECTIONAL_INTRA_VERTICAL_RIGHT:
                    if (row == 0) {
                        value = average2(
                            boundary4(top, left, top_left, column),
                            boundary4(top, left, top_left, column + 1));
                    } else if (row == 1) {
                        value = average3(
                            boundary4(top, left, top_left, column - 1),
                            boundary4(top, left, top_left, column),
                            boundary4(top, left, top_left, column + 1));
                    } else if (column > 0) {
                        value = prediction[(row - 2) * 4 + column - 1];
                    } else {
                        value = average3(
                            left[row - 1], left[row - 2],
                            row == 2 ? top_left : left[row - 3]);
                    }
                    break;
                case N148_DIRECTIONAL_INTRA_HORIZONTAL_DOWN:
                    if (column == 0) {
                        value = average2(
                            left[row], row == 0 ? top_left : left[row - 1]);
                    } else if (column == 1) {
                        value = average3(
                            left[row], row == 0 ? top_left : left[row - 1],
                            row == 0 ? top[0] :
                            (row == 1 ? top_left : left[row - 2]));
                    } else if (row > 0) {
                        value = prediction[(row - 1) * 4 + column - 2];
                    } else {
                        value = average3(top[column - 2], top[column - 1],
                                         top[column]);
                    }
                    break;
                case N148_DIRECTIONAL_INTRA_VERTICAL_LEFT:
                    value = filtered_edge_half_sample(
                        top, edge_count, 2 * column +
                        ((tools & N148_FIDELITY_FINE_DIRECTIONS) ?
                         (row + 1) / 2 : row) + 1);
                    break;
                case N148_DIRECTIONAL_INTRA_HORIZONTAL_UP:
                    value = filtered_edge_half_sample(
                        left, edge_count, 2 * row +
                        ((tools & N148_FIDELITY_FINE_DIRECTIONS) ?
                         (column + 1) / 2 : column) + 1);
                    break;
                default:
                    value = 128;
                    break;
            }
            prediction[row * 4 + column] = clamp_byte(value);
        }
    }
}

typedef struct {
    uint8_t top[66];
    uint8_t left[66];
    int edge_count;
    int top_left;
    int dc;
    uint32_t tools;
} N148PreparedSquare;

static void prepare_square_references(
    const Plane *reconstructed, int x0, int y0, int size, uint8_t neutral,
    int causal_right, uint32_t tools, int reference_index,
    N148PreparedSquare *references) {
    int reference_distance = reference_index + 1;
    int has_top = y0 >= reference_distance;
    int has_left = x0 >= reference_distance;
    uint8_t *top = references->top;
    uint8_t *left = references->left;
    int edge_count = size * 2 + 2;
    int top_limit = size >= 16 || y0 % 8 == 0 ?
        reconstructed->width - 1 : (x0 / 8) * 8 + 7;
    if (causal_right >= x0 && causal_right < top_limit)
        top_limit = causal_right;
    int left_limit = size >= 16 ? y0 + size - 1 :
        (x0 % 8 == 0 ? (y0 / 8) * 8 + 7 : y0 + size - 1);
    if (top_limit >= reconstructed->width) top_limit = reconstructed->width - 1;
    if (left_limit >= reconstructed->height)
        left_limit = reconstructed->height - 1;
    int top_sum = 0;
    int left_sum = 0;
    if (has_top && has_left && x0 >= reference_distance &&
        y0 >= reference_distance &&
        top_limit >= x0 && top_limit < reconstructed->width &&
        left_limit >= y0 && left_limit < reconstructed->height &&
        x0 <= INT_MAX - edge_count && y0 <= INT_MAX - edge_count) {
        const uint8_t *top_row = reconstructed->data +
            (long)(y0 - reference_distance) * reconstructed->width;
        int left_column = x0 - reference_distance;
        for (int index = 0; index < edge_count; index++) {
            int top_x = x0 + index;
            int left_y = y0 + index;
            if (top_x > top_limit) top_x = top_limit;
            if (left_y > left_limit) left_y = left_limit;
            top[index] = top_row[top_x];
            left[index] = reconstructed->data[
                (long) left_y * reconstructed->width + left_column];
            if (index < size) {
                top_sum += top[index];
                left_sum += left[index];
            }
        }
    } else {
        for (int index = 0; index < edge_count; index++) {
            top[index] = has_top ? (uint8_t) sample_clamped(
                reconstructed,
                x0 + index < top_limit ? x0 + index : top_limit,
                y0 - reference_distance) : neutral;
            left[index] = has_left ? (uint8_t) sample_clamped(
                reconstructed, x0 - reference_distance,
                y0 + index < left_limit ? y0 + index : left_limit) : neutral;
            if (index < size) {
                top_sum += top[index];
                left_sum += left[index];
            }
        }
    }
    if ((tools & N148_FIDELITY_FILTER_REFERENCES) && size >= 8) {
        uint8_t original_top[66], original_left[66];
        memcpy(original_top, top, (size_t) edge_count);
        memcpy(original_left, left, (size_t) edge_count);
        if (has_top) {
            for (int index = 0; index < edge_count; index++)
                top[index] = (uint8_t) average3(
                    extended_sample(original_top, edge_count, index - 1),
                    original_top[index],
                    extended_sample(original_top, edge_count, index + 1));
        }
        if (has_left) {
            for (int index = 0; index < edge_count; index++)
                left[index] = (uint8_t) average3(
                    extended_sample(original_left, edge_count, index - 1),
                    original_left[index],
                    extended_sample(original_left, edge_count, index + 1));
        }
        top_sum = 0;
        left_sum = 0;
        for (int index = 0; index < size; index++) {
            top_sum += top[index];
            left_sum += left[index];
        }
    }
    int top_left = has_top && has_left ?
        sample_clamped(reconstructed, x0 - reference_distance,
                       y0 - reference_distance) : neutral;
    int dc = neutral;
    if (has_top && has_left) dc = (top_sum + left_sum + size) / (2 * size);
    else if (has_top) dc = (top_sum + size / 2) / size;
    else if (has_left) dc = (left_sum + size / 2) / size;
    if ((tools & N148_FIDELITY_SECOND_ORDER_DC) && has_top && has_left) {
        int top_mean = (top_sum + size / 2) / size;
        int left_mean = (left_sum + size / 2) / size;
        int extrapolated = top_mean + left_mean - top_left;
        dc = clamp_byte((dc + extrapolated + 1) / 2);
    }
    references->edge_count = edge_count;
    references->top_left = top_left;
    references->dc = dc;
    references->tools = tools;
}

static void predict_square_prepared(const N148PreparedSquare *references,
                                    int size, int mode, uint8_t neutral,
                                    uint8_t *prediction) {
    const uint8_t *top = references->top;
    const uint8_t *left = references->left;
    int edge_count = references->edge_count;
    int top_left = references->top_left;
    int dc = references->dc;
    uint32_t tools = references->tools;

    if (size == 4) {
        predict_square4(top, left, edge_count, top_left, dc, mode, tools,
                        prediction);
        return;
    }

    if (mode == N148_DIRECTIONAL_INTRA_DC) {
        memset(prediction, dc, (size_t) size * size);
        return;
    }
    if (mode == N148_DIRECTIONAL_INTRA_VERTICAL) {
        for (int row = 0; row < size; row++)
            memcpy(prediction + row * size, top, (size_t) size);
        return;
    }
    if (mode == N148_DIRECTIONAL_INTRA_HORIZONTAL) {
        for (int row = 0; row < size; row++)
            memset(prediction + row * size, left[row], (size_t) size);
        return;
    }
    if (mode == N148_DIRECTIONAL_INTRA_TRUE_MOTION) {
        if (tools & N148_FIDELITY_PLANAR_PREDICTION) {
            int shift = size == 8 ? 4 : size == 16 ? 5 : 6;
            for (int row = 0; row < size; row++) {
                int base = (size - 1) * left[row] + top[size] +
                    (row + 1) * left[size] + size;
                int slope = top[size] - left[row];
                int top_weight = size - 1 - row;
                for (int column = 0; column < size; column++)
                    prediction[row * size + column] = (uint8_t)(
                        (base + column * slope +
                         top_weight * top[column]) >> shift);
            }
        } else {
            for (int row = 0; row < size; row++)
                for (int column = 0; column < size; column++)
                    prediction[row * size + column] = clamp_byte(
                        left[row] + top[column] - top_left);
        }
        return;
    }

    /* Each angular ray repeats across rows. Evaluate its interpolation
       once per coordinate, preserving the existing scalar rounding. */
    if (size == 8 && mode >= N148_DIRECTIONAL_INTRA_DOWN_LEFT &&
        mode <= N148_DIRECTIONAL_INTRA_HORIZONTAL_UP) {
        uint8_t ray[22];
        if (mode == N148_DIRECTIONAL_INTRA_DOWN_LEFT) {
            for (int d = 0; d < 15; d++) ray[d] = (uint8_t)average3(
                extended_sample(top, edge_count, d),
                extended_sample(top, edge_count, d+1),
                extended_sample(top, edge_count, d+2));
            for (int row = 0; row < 8; row++) memcpy(prediction + row*8, ray+row, 8);
        } else if (mode == N148_DIRECTIONAL_INTRA_DOWN_RIGHT) {
            for (int c = -7; c <= 7; c++) ray[c+7] = (uint8_t)average3(
                diagonal_boundary(top,left,edge_count,top_left,c-1),
                diagonal_boundary(top,left,edge_count,top_left,c),
                diagonal_boundary(top,left,edge_count,top_left,c+1));
            for (int row = 0; row < 8; row++) memcpy(prediction + row*8, ray+7-row, 8);
        } else if (mode == N148_DIRECTIONAL_INTRA_VERTICAL_RIGHT) {
            for (int c = -6; c <= 15; c++) ray[c+6] = (uint8_t)
                diagonal_half_sample(top,left,edge_count,top_left,c);
            for (int row = 0; row < 8; row++)
                for (int col = 0; col < 8; col++)
                    prediction[row*8+col] = ray[2*col-row+7];
        } else if (mode == N148_DIRECTIONAL_INTRA_HORIZONTAL_DOWN) {
            for (int c = -15; c <= 6; c++) ray[c+15] = (uint8_t)
                diagonal_half_sample(top,left,edge_count,top_left,c);
            for (int row = 0; row < 8; row++) memcpy(prediction + row*8, ray+14-2*row, 8);
        } else {
            const uint8_t *edge = mode == N148_DIRECTIONAL_INTRA_VERTICAL_LEFT ? top : left;
            for (int c = 0; c < 22; c++) ray[c] = (uint8_t)edge_half_sample(edge,edge_count,c+1);
            for (int row = 0; row < 8; row++) {
                for (int col = 0; col < 8; col++) {
                    int major = mode == N148_DIRECTIONAL_INTRA_VERTICAL_LEFT ? col : row;
                    int minor = mode == N148_DIRECTIONAL_INTRA_VERTICAL_LEFT ? row : col;
                    if (tools & N148_FIDELITY_FINE_DIRECTIONS) minor = (minor+1)/2;
                    prediction[row*8+col] = ray[2*major+minor];
                }
            }
        }
        return;
    }


    for (int row = 0; row < size; row++) {
        for (int column = 0; column < size; column++) {
            int value;
            switch (mode) {
                case N148_DIRECTIONAL_INTRA_DC:
                    value = dc;
                    break;
                case N148_DIRECTIONAL_INTRA_VERTICAL:
                    value = top[column];
                    break;
                case N148_DIRECTIONAL_INTRA_HORIZONTAL:
                    value = left[row];
                    break;
                case N148_DIRECTIONAL_INTRA_TRUE_MOTION:
                    if ((tools & N148_FIDELITY_PLANAR_PREDICTION) &&
                        size >= 8) {
                        value = ((size - 1 - column) * left[row] +
                                 (column + 1) * top[size] +
                                 (size - 1 - row) * top[column] +
                                 (row + 1) * left[size] + size) /
                            (2 * size);
                    } else {
                        value = left[row] + top[column] - top_left;
                    }
                    break;
                case N148_DIRECTIONAL_INTRA_DOWN_LEFT: {
                    int index = column + row + 1;
                    value = average3(
                        extended_sample(top, edge_count, index - 1),
                        extended_sample(top, edge_count, index),
                        extended_sample(top, edge_count, index + 1));
                    break;
                }
                case N148_DIRECTIONAL_INTRA_DOWN_RIGHT: {
                    int coordinate = column - row;
                    value = average3(
                        diagonal_boundary(top, left, edge_count, top_left,
                                          coordinate - 1),
                        diagonal_boundary(top, left, edge_count, top_left,
                                          coordinate),
                        diagonal_boundary(top, left, edge_count, top_left,
                                          coordinate + 1));
                    break;
                }
                case N148_DIRECTIONAL_INTRA_VERTICAL_RIGHT:
                    value = diagonal_half_sample(
                        top, left, edge_count, top_left,
                        2 * column - row + 1);
                    break;
                case N148_DIRECTIONAL_INTRA_HORIZONTAL_DOWN:
                    value = diagonal_half_sample(
                        top, left, edge_count, top_left,
                        column - 2 * row - 1);
                    break;
                case N148_DIRECTIONAL_INTRA_VERTICAL_LEFT:
                    value = edge_half_sample(top, edge_count,
                        2 * column +
                        ((tools & N148_FIDELITY_FINE_DIRECTIONS) ?
                         (row + 1) / 2 : row) + 1);
                    break;
                case N148_DIRECTIONAL_INTRA_HORIZONTAL_UP:
                    value = edge_half_sample(left, edge_count,
                        2 * row +
                        ((tools & N148_FIDELITY_FINE_DIRECTIONS) ?
                         (column + 1) / 2 : column) + 1);
                    break;
                default:
                    value = neutral;
                    break;
            }
            prediction[row * size + column] = clamp_byte(value);
        }
    }
}

static void predict_square(const Plane *reconstructed, int x0, int y0,
                           int size, int mode, uint8_t neutral,
                           int causal_right, int apply_fidelity,
                           uint8_t *prediction) {
    uint32_t tools = apply_fidelity ? fidelity_tools : 0;
    int reference_index = 0;
    if ((tools & N148_FIDELITY_MULTIPLE_REFERENCES) && size >= 8) {
        reference_index = n148_intra_reference_index(mode);
        mode = n148_intra_base_mode(mode);
    }
    N148PreparedSquare references;
    prepare_square_references(reconstructed, x0, y0, size, neutral,
                              causal_right, tools, reference_index,
                              &references);
    predict_square_prepared(&references, size, mode, neutral, prediction);
}

static void hadamard(int *values, int size) {
    for (int span = 1; span < size; span *= 2) {
        for (int first = 0; first < size; first += span * 2) {
            for (int offset = 0; offset < span; offset++) {
                int a = values[first + offset];
                int b = values[first + offset + span];
                values[first + offset] = a + b;
                values[first + offset + span] = a - b;
            }
        }
    }
}

/* Exact sums of squared byte differences for full native transform blocks.
   A row is completed before applying the original predictor cutoff. */
#if defined(__x86_64__) || defined(__i386__)
__attribute__((target("avx2")))
static uint64_t pixel_error(const uint8_t *a, int stride_a,
                               const uint8_t *b, int stride_b,
                               int size, uint64_t cutoff) {
    uint64_t total = 0;
    for (int row = 0; row < size; row++) {
        __m128i sum;
        if (size <= 8) {
            __m128i left, right;
            if (size == 4) {
                uint32_t x, y;
                memcpy(&x, a, 4); memcpy(&y, b, 4);
                left = _mm_cvtsi32_si128((int)x);
                right = _mm_cvtsi32_si128((int)y);
            } else {
                left = _mm_loadl_epi64((const __m128i *)a);
                right = _mm_loadl_epi64((const __m128i *)b);
            }
            __m128i delta = _mm_sub_epi16(_mm_cvtepu8_epi16(left),
                                        _mm_cvtepu8_epi16(right));
            sum = _mm_madd_epi16(delta, delta);
        } else {
            __m256i accumulated = _mm256_setzero_si256();
            for (int column = 0; column < size; column += 16) {
                __m128i left = _mm_loadu_si128((const __m128i *)(a+column));
                __m128i right = _mm_loadu_si128((const __m128i *)(b+column));
                __m256i delta = _mm256_sub_epi16(_mm256_cvtepu8_epi16(left),
                                                _mm256_cvtepu8_epi16(right));
                accumulated = _mm256_add_epi32(accumulated,
                                               _mm256_madd_epi16(delta, delta));
            }
            sum = _mm_add_epi32(_mm256_castsi256_si128(accumulated),
                                _mm256_extracti128_si256(accumulated, 1));
        }
        sum = _mm_add_epi32(sum, _mm_srli_si128(sum, 8));
        sum = _mm_add_epi32(sum, _mm_srli_si128(sum, 4));
        total += (unsigned)_mm_cvtsi128_si32(sum);
        if (total >= cutoff) break;
        a += stride_a;
        b += stride_b;
    }
    return total;
}
#endif


static uint64_t prediction_sse(const Plane *source, int x0, int y0,
                               int size, const uint8_t *prediction,
                               uint64_t cutoff) {
#if defined(__x86_64__) || defined(__i386__)
    if ((size == 4 || size == 8 || size == 16 || size == 32) &&
        x0 >= 0 && y0 >= 0 && size <= source->width-x0 &&
        size <= source->height-y0 && n148_cpu_level() >= N148_CPU_AVX2)
        return pixel_error(source->data+(long)y0*source->width+x0,
            source->width, prediction, size, size, cutoff);
#endif
    uint64_t error = 0;
    if (x0 >= 0 && y0 >= 0 && size <= source->width - x0 &&
        size <= source->height - y0) {
        for (int row = 0; row < size; row++) {
            const uint8_t *source_row = source->data +
                (long)(y0 + row) * source->width + x0;
            const uint8_t *prediction_row = prediction + row * size;
            for (int column = 0; column < size; column++) {
                int residual = source_row[column] - prediction_row[column];
                error += (uint64_t)(residual * residual);
            }
            if (error >= cutoff) break;
        }
    } else {
        for (int row = 0; row < size; row++) {
            for (int column = 0; column < size; column++) {
                int residual = sample_clamped(source, x0 + column,
                                              y0 + row) -
                               prediction[row * size + column];
                error += (uint64_t)(residual * residual);
            }
            if (error >= cutoff) break;
        }
    }
    return error;
}

static uint64_t prediction_satd(const Plane *source, int x0, int y0,
                                int size, const uint8_t *prediction,
                                uint64_t cutoff) {
    int transformed[32 * 32];
    if (x0 >= 0 && y0 >= 0 && size <= source->width - x0 &&
        size <= source->height - y0) {
        for (int row = 0; row < size; row++) {
            const uint8_t *source_row = source->data +
                (long)(y0 + row) * source->width + x0;
            for (int column = 0; column < size; column++)
                transformed[row * size + column] =
                    source_row[column] - prediction[row * size + column];
            hadamard(transformed + row * size, size);
        }
    } else {
        for (int row = 0; row < size; row++) {
            for (int column = 0; column < size; column++)
                transformed[row * size + column] =
                    sample_clamped(source, x0 + column, y0 + row) -
                    prediction[row * size + column];
            hadamard(transformed + row * size, size);
        }
    }
    uint64_t score = 0;
    for (int column = 0; column < size; column++) {
        int vertical[32];
        for (int row = 0; row < size; row++)
            vertical[row] = transformed[row * size + column];
        hadamard(vertical, size);
        for (int row = 0; row < size; row++) {
            int value = vertical[row];
            score += (uint64_t)(value < 0 ? -value : value);
        }
        if (score >= cutoff) return score;
    }
    return score;
}

static int choose_mode(const Plane *source, const Plane *reconstructed,
                       int x0, int y0, int size, uint8_t neutral,
                       int mode_count, int causal_right,
                       int apply_fidelity, uint8_t *prediction,
                       int *runner_up, uint64_t *prediction_score) {
    int fast_search = (fidelity_tools & N148_FIDELITY_FAST_MODE_SEARCH) != 0;
    if (fast_search && mode_count > 4) mode_count = 4;
    uint64_t best_score = UINT64_MAX;
    uint64_t second_score = UINT64_MAX;
    int best_mode = N148_DIRECTIONAL_INTRA_DC;
    int second_mode = -1;
    uint8_t candidate[32 * 32];
    uint32_t tools = apply_fidelity ? fidelity_tools : 0;
    int multiple_references =
        (tools & N148_FIDELITY_MULTIPLE_REFERENCES) && size >= 8;
    N148PreparedSquare references[N148_INTRA_REFERENCE_COUNT];
    uint8_t prepared[N148_INTRA_REFERENCE_COUNT] = {0};
    for (int mode = 0; mode < mode_count; mode++) {
        int reference_index = multiple_references ?
            n148_intra_reference_index(mode) : 0;
        int base_mode = multiple_references ?
            n148_intra_base_mode(mode) : mode;
        if (!prepared[reference_index]) {
            prepare_square_references(
                reconstructed, x0, y0, size, neutral, causal_right,
                tools, reference_index, &references[reference_index]);
            prepared[reference_index] = 1;
        }
        predict_square_prepared(&references[reference_index], size,
                                base_mode, neutral, candidate);
        uint64_t cutoff = runner_up ? second_score : best_score;
        uint64_t score = fast_search ?
            prediction_sse(source, x0, y0, size, candidate, cutoff) :
            prediction_satd(source, x0, y0, size, candidate, cutoff);
        if (score < best_score) {
            if (best_score != UINT64_MAX) {
                second_score = best_score;
                second_mode = best_mode;
            }
            best_score = score;
            best_mode = mode;
            memcpy(prediction, candidate, (size_t) size * (size_t) size);
        } else if (runner_up && score < second_score) {
            second_score = score;
            second_mode = mode;
        }
    }
    if (runner_up) *runner_up = second_mode;
    if (prediction_score) *prediction_score = best_score;
    return best_mode;
}

/* Every integer transform produces a signed 32-bit level and quantizer steps
   are in [1, 255]. The floor reciprocal can undershoot the exact quotient by
   at most one for the rounded numerator, so one remainder check restores the
   same integer result without a hardware divide in the block hot path. */
#if defined(__GNUC__) || defined(__clang__)
__attribute__((always_inline))
#endif
static inline int quantize_integer_level(int32_t value, int step,
                                         uint32_t reciprocal_q32,
                                         short *result) {
    uint32_t magnitude = value < 0 ?
        (uint32_t)(-(int64_t) value) : (uint32_t) value;
    uint32_t rounded = magnitude + (uint32_t)(step / 2);
    uint32_t level = (uint32_t)(
        ((uint64_t) rounded * reciprocal_q32) >> 32);
    level += rounded - level * (uint32_t) step >= (uint32_t) step;
    if (level > (value < 0 ? 32768u : 32767u)) return 0;
    *result = (short)(value < 0 ? -(int) level : (int) level);
    return 1;
}

#if defined(__x86_64__) || defined(__i386__)
__attribute__((target("avx2")))
static void residual8_avx2(const Plane *source, int x0, int y0,
    const uint8_t prediction[64], float block[64]) {
    const __m256 centre = _mm256_set1_ps(128.0f);
    for (int row = 0; row < 8; row++) {
        const uint8_t *input = source->data + (long)(y0 + row) * source->width + x0;
        __m128i src = _mm_loadl_epi64((const __m128i *)input);
        __m128i pred = _mm_loadl_epi64((const __m128i *)(prediction + row * 8));
        __m256i residual = _mm256_sub_epi32(_mm256_cvtepu8_epi32(src),
                                           _mm256_cvtepu8_epi32(pred));
        _mm256_storeu_ps(block + row * 8,
            _mm256_add_ps(_mm256_cvtepi32_ps(residual),centre));
    }
}
__attribute__((target("avx2")))
static int quantize8_avx2(const float transformed[64],
    const IntraQuant8 *quant, short output[64], float ideal_levels[64]) {
    float ideal[64];
    int32_t levels[64];
    const __m256i upper = _mm256_set1_epi32(SHRT_MAX);
    const __m256i lower = _mm256_set1_epi32(SHRT_MIN);
    __m256i invalid = _mm256_setzero_si256();
    for (int i = 0; i < 64; i += 8) {
        __m256 value = _mm256_mul_ps(_mm256_loadu_ps(transformed + i),
                                     _mm256_loadu_ps(quant->reciprocal + i));
        __m256i rounded = _mm256_cvtps_epi32(value);
        invalid = _mm256_or_si256(invalid,_mm256_or_si256(
            _mm256_cmpgt_epi32(rounded,upper),_mm256_cmpgt_epi32(lower,rounded)));
        _mm256_storeu_ps(ideal + i,value);
        _mm256_storeu_si256((__m256i *)(levels + i),rounded);
    }
    if (_mm256_movemask_epi8(invalid)) return 0;
    for (int position = 0; position < 64; position++) {
        int natural = ZIGZAG[position];
        output[position] = (short)levels[natural];
        if (ideal_levels) ideal_levels[position] = ideal[natural];
    }
    return 1;
}
#endif

static int quantize8(const Plane *source, int x0, int y0,
                     const uint8_t prediction[64], const IntraQuant8 *quant,
                     short output[64], float ideal_levels[64]) {
    float block[64], transformed[64];
#if defined(__x86_64__) || defined(__i386__)
    int vector = n148_cpu_level() >= N148_CPU_AVX2;
    if (vector && x0 >= 0 && y0 >= 0 && x0 <= source->width - 8 &&
        y0 <= source->height - 8) {
        residual8_avx2(source,x0,y0,prediction,block);
    } else
#endif
    for (int row = 0; row < 8; row++) {
        for (int column = 0; column < 8; column++) {
            int index = row * 8 + column;
            block[index] = (float)(sample_clamped(source, x0 + column,
                                                  y0 + row) -
                                   prediction[index] + 128);
        }
    }
    dct_block_fast(block, transformed);
#if defined(__x86_64__) || defined(__i386__)
    if (vector) return quantize8_avx2(
        transformed,quant,output,ideal_levels);
#endif
    for (int position = 0; position < 64; position++) {
        int natural = ZIGZAG[position];
        float ideal = transformed[natural] * quant->reciprocal[natural];
        long value = lrintf(ideal);
        if (value < SHRT_MIN || value > SHRT_MAX) return 0;
        output[position] = (short) value;
        if (ideal_levels) ideal_levels[position] = ideal;
    }
    return 1;
}

static inline int coefficients_all_zero(const short *coefficients,
                                        int count) {
    for (int position = 0; position < count; position++)
        if (coefficients[position] != 0) return 0;
    return 1;
}

static inline int coefficients4_all_zero(const short coefficients[16]) {
    if (sizeof(short) != 2) return coefficients_all_zero(coefficients, 16);
    uint64_t words[4];
    memcpy(words, coefficients, sizeof(words));
    return (words[0] | words[1] | words[2] | words[3]) == 0;
}

static void copy_prediction_block(const uint8_t *prediction, int size,
                                  Plane *output, int x0, int y0) {
    int max_x = output->width - x0;
    int max_y = output->height - y0;
    if (max_x > size) max_x = size;
    if (max_y > size) max_y = size;
    if (max_x <= 0 || max_y <= 0) return;
    for (int row = 0; row < max_y; row++)
        memcpy(output->data + (long)(y0 + row) * output->width + x0,
               prediction + row * size, (size_t) max_x);
}

static int reconstruct8_masked(const short coefficients[64],
                               const uint8_t prediction[64],
                               const IntraQuant8 *quant, Plane *output,
                               int x0, int y0, unsigned long long mask) {
    static const uint8_t inverse_zigzag[64] = {
         0,  1,  5,  6, 14, 15, 27, 28,
         2,  4,  7, 13, 16, 26, 29, 42,
         3,  8, 12, 17, 25, 30, 41, 43,
         9, 11, 18, 24, 31, 40, 44, 53,
        10, 19, 23, 32, 39, 45, 52, 54,
        20, 22, 33, 38, 46, 51, 55, 60,
        21, 34, 37, 47, 50, 56, 59, 61,
        35, 36, 48, 49, 57, 58, 62, 63,
    };
    int first_ac = 1;
    if (mask != ~0ull) {
        first_ac = (mask & ~1ull) == 0 ? 64 : 1;
    } else {
        while (first_ac < 64 && coefficients[first_ac] == 0) first_ac++;
    }
    if (first_ac == 64) {
        if (coefficients[0] == 0) {
            copy_prediction_block(prediction, 8, output, x0, y0);
            return 1;
        }
        float dc = coefficients[0] * quant->multiplier[0];
        int width = output->width - x0;
        int height = output->height - y0;
        if (width > 8) width = 8;
        if (height > 8) height = 8;
#if defined(__x86_64__) || defined(__i386__)
        if (width == 8 && height == 8 &&
            n148_cpu_level() >= N148_CPU_AVX2) {
            idct_block_add_prediction_dc_avx2(
                dc, prediction,
                output->data + (long)y0 * output->width + x0,
                output->width);
            return 1;
        }
#endif
        for (int row = 0; row < height; row++) {
            uint8_t *destination = output->data +
                (long)(y0 + row) * output->width + x0;
            for (int column = 0; column < width; column++) {
                int index = row * 8 + column;
                float value = prediction[index] + (dc + 128.0f);
                value -= 128.0f;
                if (value < 0.0f) value = 0.0f;
                if (value > 255.0f) value = 255.0f;
                destination[column] = (uint8_t)(value + 0.5f);
            }
        }
        return 1;
    }
    /* Read in inverse zig-zag order so the 8x8 dequantization writes
       contiguous natural-order residuals. */
    float residual[64];
    for (int natural = 0; natural < 64; natural++) {
        residual[natural] = coefficients[inverse_zigzag[natural]] *
            quant->multiplier[natural];
    }
    int max_x = output->width - x0;
    int max_y = output->height - y0;
    if (max_x > 8) max_x = 8;
    if (max_y > 8) max_y = 8;
    if (max_x <= 0 || max_y <= 0) return 1;
#if defined(__x86_64__) || defined(__i386__)
    if (max_x == 8 && max_y == 8 &&
        n148_cpu_level() >= N148_CPU_AVX2) {
        idct_block_add_prediction_avx2(
            residual, prediction,
            output->data + (long) y0 * output->width + x0,
            output->width);
        return 1;
    }
#endif
    idct_block_fast(residual, residual);
    for (int row = 0; row < max_y; row++) {
        uint8_t *destination = output->data +
            (long)(y0 + row) * output->width + x0;
        for (int column = 0; column < max_x; column++) {
            int index = row * 8 + column;
            float value = prediction[index] + residual[index] - 128.0f;
            if (value < 0.0f) value = 0.0f;
            if (value > 255.0f) value = 255.0f;
            destination[column] = (uint8_t)(value + 0.5f);
        }
    }
    return 1;
}

static int reconstruct8(const short coefficients[64],
                        const uint8_t prediction[64],
                        const IntraQuant8 *quant, Plane *output,
                        int x0, int y0) {
    return reconstruct8_masked(
        coefficients, prediction, quant, output, x0, y0, ~0ull);
}

#include "quantize4_avx2.inc"
static int quantize4(const Plane *source, int x0, int y0,
                     const uint8_t prediction[16], const IntraQuant4 *quant,
                     short output[16], float ideal_levels[16]) {
    int32_t residual[16], transformed[16];
    int vector=0;
#if defined(__x86_64__) || defined(__i386__)
    vector=n148_cpu_level()>=N148_CPU_AVX2;
    if(vector && x0>=0 && y0>=0 && source->width-x0>=4 && source->height-y0>=4)
        residual4_avx2(source,x0,y0,prediction,residual);
    else
#endif
    for (int row = 0; row < 4; row++) {
        for (int column = 0; column < 4; column++) {
            residual[row * 4 + column] =
                sample_clamped(source, x0 + column, y0 + row) -
                prediction[row * 4 + column];
        }
    }
    if (!n148_variable_forward(residual, 4, transformed)) return 0;
#if defined(__x86_64__) || defined(__i386__)
    if(vector)return quantize4_avx2(transformed,quant,output,ideal_levels);
#endif
    for (int position = 0; position < 16; position++) {
        int natural = n148_variable_zigzag(4, position);
        if (natural < 0) return 0;
        int step = quant->step[natural];
        if (!quantize_integer_level(
                transformed[natural], step,
                quant->reciprocal_q32[natural], &output[position])) return 0;
        if (ideal_levels)
            ideal_levels[position] = (float) transformed[natural] /
                (float) step;
    }
    return 1;
}

static int reconstruct4_masked(const short coefficients[16],
                               const uint8_t prediction[16],
                               const IntraQuant4 *quant, Plane *output,
                               int x0, int y0, unsigned int mask) {
    if (mask == 0 ||
        (mask == UINT_MAX && coefficients4_all_zero(coefficients))) {
        copy_prediction_block(prediction, 4, output, x0, y0);
        return 1;
    }
    if (mask == 1) {
        /* The integer 4x4 inverse maps a DC-only coefficient to the same
           rounded quarter-level at every pixel (8192^2 / 2^28 = 1/4). */
        int32_t dc = (int32_t) coefficients[0] * quant->step[0];
        int value = dc >= 0 ? (int)(((int64_t) dc + 2) / 4) :
            -(int)((-(int64_t) dc + 2) / 4);
        int max_x = output->width - x0;
        int max_y = output->height - y0;
        if (max_x > 4) max_x = 4;
        if (max_y > 4) max_y = 4;
        for (int row = 0; row < max_y; row++) {
            uint8_t *destination = output->data +
                (long)(y0 + row) * output->width + x0;
            for (int column = 0; column < max_x; column++)
                destination[column] = clamp_byte(
                    prediction[row * 4 + column] + value);
        }
        return 1;
    }
    if (mask != UINT_MAX && (mask & ~15u) == 0) {
        /* Scan positions 0 through 3 are DC, horizontal AC1, vertical AC1
           and vertical AC2. Evaluate the same separable integer inverse
           with its identical final rounding while skipping zero products. */
        int32_t dc = (int32_t) coefficients[0] * quant->step[0];
        int32_t horizontal = (int32_t) coefficients[1] * quant->step[1];
        int32_t vertical = (int32_t) coefficients[2] * quant->step[4];
        int32_t vertical2 = (int32_t) coefficients[3] * quant->step[8];
        int64_t column[4] = {
            8192ll * dc + 10703ll * vertical + 8192ll * vertical2,
            8192ll * dc + 4433ll * vertical - 8192ll * vertical2,
            8192ll * dc - 4433ll * vertical - 8192ll * vertical2,
            8192ll * dc - 10703ll * vertical + 8192ll * vertical2,
        };
        int64_t row_delta[4] = {
            10703ll * 8192 * horizontal,
            4433ll * 8192 * horizontal,
            -4433ll * 8192 * horizontal,
            -10703ll * 8192 * horizontal,
        };
        int32_t residual[16];
        for (int row = 0; row < 4; row++) {
            for (int column_index = 0; column_index < 4; column_index++) {
                int64_t sum = 8192ll * column[row] +
                    row_delta[column_index];
                int64_t rounded = sum >= 0 ?
                    (sum + 134217728ll) / 268435456ll :
                    -((-sum + 134217728ll) / 268435456ll);
                if (rounded < INT32_MIN || rounded > INT32_MAX) return 0;
                residual[row * 4 + column_index] = (int32_t) rounded;
            }
        }
        int max_x = output->width - x0;
        int max_y = output->height - y0;
        if (max_x > 4) max_x = 4;
        if (max_y > 4) max_y = 4;
        for (int row = 0; row < max_y; row++) {
            uint8_t *destination = output->data +
                (long)(y0 + row) * output->width + x0;
            for (int column_index = 0; column_index < max_x;
                 column_index++)
                destination[column_index] = clamp_byte(
                    prediction[row * 4 + column_index] +
                    residual[row * 4 + column_index]);
        }
        return 1;
    }
    int32_t transformed[16], residual[16];
    for (int position = 0; position < 16; position++) {
        int natural = n148_variable_zigzag(4, position);
        if (natural < 0) return 0;
        transformed[natural] =
            (int32_t) coefficients[position] * quant->step[natural];
    }
    if (!n148_variable_inverse(transformed, 4, residual)) return 0;
    int max_x = output->width - x0;
    int max_y = output->height - y0;
    if (max_x > 4) max_x = 4;
    if (max_y > 4) max_y = 4;
    if (max_x <= 0 || max_y <= 0) return 1;
    for (int row = 0; row < max_y; row++) {
        uint8_t *destination = output->data +
            (long)(y0 + row) * output->width + x0;
        for (int column = 0; column < max_x; column++) {
            int value = prediction[row * 4 + column] +
                residual[row * 4 + column];
            destination[column] = clamp_byte(value);
        }
    }
    return 1;
}

static uint64_t coefficient_unit_mask(const short *values, int length);

static int reconstruct4(const short coefficients[16],
                        const uint8_t prediction[16],
                        const IntraQuant4 *quant, Plane *output,
                        int x0, int y0) {
    return reconstruct4_masked(
        coefficients, prediction, quant, output, x0, y0,
        (unsigned int)coefficient_unit_mask(coefficients,16));
}

static int quantize16(const Plane *source, int x0, int y0,
                      const uint8_t prediction[16 * 16],
                      const IntraQuant16 *quant,
                      short output[16 * 16]) {
    int32_t residual[16 * 16], transformed[16 * 16];
    for (int row = 0; row < 16; row++) {
        for (int column = 0; column < 16; column++) {
            residual[row * 16 + column] =
                sample_clamped(source, x0 + column, y0 + row) -
                prediction[row * 16 + column];
        }
    }
    if (!n148_variable_forward(residual, 16, transformed)) return 0;
    for (int position = 0; position < 16 * 16; position++) {
        int natural = n148_variable_zigzag(16, position);
        if (natural < 0 || !quantize_integer_level(
                transformed[natural], quant->step[natural],
                quant->reciprocal_q32[natural], &output[position])) return 0;
    }
    return 1;
}

static int reconstruct16(const short coefficients[16 * 16],
                         const uint8_t prediction[16 * 16],
                         const IntraQuant16 *quant, Plane *output,
                         int x0, int y0, int use_sparse,
                         const unsigned long long masks[4]) {
    if (masks ? !(masks[0] | masks[1] | masks[2] | masks[3]) :
                coefficients_all_zero(coefficients, 16 * 16)) {
        copy_prediction_block(prediction, 16, output, x0, y0);
        return 1;
    }
    int32_t transformed[16 * 16], residual[16 * 16];
    uint32_t active_rows = 0, active_columns = 0;
    int active_coefficients = 0;
    if (masks && use_sparse) {
#if defined(__GNUC__) || defined(__clang__)
        for (int cell = 0; cell < 4; cell++)
            active_coefficients += __builtin_popcountll(masks[cell]);
#else
        for (int cell = 0; cell < 4; cell++) {
            unsigned long long bits = masks[cell];
            while (bits) { active_coefficients++; bits &= bits - 1; }
        }
#endif
    }
    if (use_sparse && masks && active_coefficients <= 128) {
        memset(transformed, 0, sizeof(transformed));
        for (int cell = 0; cell < 4; cell++) {
            unsigned long long bits = masks[cell];
            while (bits) {
#if defined(__GNUC__) || defined(__clang__)
                int position = __builtin_ctzll(bits);
#else
                int position = 0;
                while (!((bits >> position) & 1ull)) position++;
#endif
                int natural = n148_variable_zigzag(16, cell * 64 + position);
                if (natural < 0) return 0;
                int32_t value = (int32_t) coefficients[cell * 64 + position] *
                    quant->step[natural];
                transformed[natural] = value;
                if (value != 0) {
                    active_rows |= 1u << (natural / 16);
                    active_columns |= 1u << (natural % 16);
                }
                bits &= bits - 1;
            }
        }
    } else if (use_sparse) {
        for (int position = 0; position < 16 * 16; position++) {
            int natural = n148_variable_zigzag(16, position);
            if (natural < 0) return 0;
            transformed[natural] =
                (int32_t) coefficients[position] * quant->step[natural];
            if (transformed[natural] != 0) {
                active_rows |= 1u << (natural / 16);
                active_columns |= 1u << (natural % 16);
            }
        }
    } else {
        for (int position = 0; position < 16 * 16; position++) {
            int natural = n148_variable_zigzag(16, position);
            if (natural < 0) return 0;
            transformed[natural] =
                (int32_t) coefficients[position] * quant->step[natural];
        }
    }
    int active_count = 0;
    if (use_sparse) {
#if defined(__GNUC__) || defined(__clang__)
        active_count = __builtin_popcount(active_rows) +
            __builtin_popcount(active_columns);
#else
        for (int index = 0; index < 16; index++)
            active_count += ((active_rows >> index) & 1u) +
                ((active_columns >> index) & 1u);
#endif
    }
    if (!(use_sparse && active_count <= 20 ? n148_variable_inverse_sparse16(
              transformed, active_rows, active_columns, residual) :
          n148_variable_inverse(transformed, 16, residual))) return 0;
    int max_x = output->width - x0;
    int max_y = output->height - y0;
    if (max_x > 16) max_x = 16;
    if (max_y > 16) max_y = 16;
    if (max_x <= 0 || max_y <= 0) return 1;
    for (int row = 0; row < max_y; row++) {
        uint8_t *destination = output->data +
            (long)(y0 + row) * output->width + x0;
        for (int column = 0; column < max_x; column++) {
            int value = prediction[row * 16 + column] +
                residual[row * 16 + column];
            destination[column] = clamp_byte(value);
        }
    }
    return 1;
}

static int quantize32(const Plane *source, int x0, int y0,
                      const uint8_t prediction[32 * 32],
                      const IntraQuant32 *quant,
                      short output[32 * 32]) {
    int32_t residual[32 * 32], transformed[32 * 32];
    for (int row = 0; row < 32; row++) {
        for (int column = 0; column < 32; column++) {
            residual[row * 32 + column] =
                sample_clamped(source, x0 + column, y0 + row) -
                prediction[row * 32 + column];
        }
    }
    if (!n148_variable_forward(residual, 32, transformed)) return 0;
    for (int position = 0; position < 32 * 32; position++) {
        int natural = n148_variable_zigzag(32, position);
        if (natural < 0 || !quantize_integer_level(
                transformed[natural], quant->step[natural],
                quant->reciprocal_q32[natural], &output[position])) return 0;
    }
    return 1;
}

static int reconstruct32(const short coefficients[32 * 32],
                         const uint8_t prediction[32 * 32],
                         const IntraQuant32 *quant, Plane *output,
                         int x0, int y0) {
    if (coefficients_all_zero(coefficients, 32 * 32)) {
        copy_prediction_block(prediction, 32, output, x0, y0);
        return 1;
    }
    int32_t transformed[32 * 32] = {0}, residual[32 * 32];
    for (int position = 0; position < 32 * 32; position++) {
        int natural = n148_variable_zigzag(32, position);
        if (natural < 0) return 0;
        transformed[natural] =
            (int32_t) coefficients[position] * quant->step[natural];
    }
    if (!n148_variable_inverse(transformed, 32, residual)) return 0;
    int max_x = output->width - x0;
    int max_y = output->height - y0;
    if (max_x > 32) max_x = 32;
    if (max_y > 32) max_y = 32;
    if (max_x <= 0 || max_y <= 0) return 1;
    for (int row = 0; row < max_y; row++) {
        uint8_t *destination = output->data +
            (long)(y0 + row) * output->width + x0;
        for (int column = 0; column < max_x; column++) {
            int value = prediction[row * 32 + column] +
                residual[row * 32 + column];
            destination[column] = clamp_byte(value);
        }
    }
    return 1;
}

#if defined(__x86_64__) || defined(__i386__)
__attribute__((target("avx2")))
static uint64_t coefficient_unit_mask_avx2(const short *values, int length) {
    const __m256i zero = _mm256_setzero_si256();
    __m256i a = _mm256_cmpeq_epi16(_mm256_loadu_si256((const __m256i *)values), zero);
    if (length == 16) {
        __m128i packed = _mm_packs_epi16(_mm256_castsi256_si128(a),
                                       _mm256_extracti128_si256(a, 1));
        return (unsigned)(~_mm_movemask_epi8(packed)) & 0xffffu;
    }
    __m256i b = _mm256_cmpeq_epi16(_mm256_loadu_si256((const __m256i *)(values + 16)), zero);
    __m256i c = _mm256_cmpeq_epi16(_mm256_loadu_si256((const __m256i *)(values + 32)), zero);
    __m256i d = _mm256_cmpeq_epi16(_mm256_loadu_si256((const __m256i *)(values + 48)), zero);
    __m256i first = _mm256_permute4x64_epi64(_mm256_packs_epi16(a, b), 0xd8);
    __m256i second = _mm256_permute4x64_epi64(_mm256_packs_epi16(c, d), 0xd8);
    uint32_t low = ~(uint32_t)_mm256_movemask_epi8(first);
    uint32_t high = ~(uint32_t)_mm256_movemask_epi8(second);
    return (uint64_t)low | ((uint64_t)high << 32);
}
#endif

static uint64_t coefficient_unit_mask(const short *values, int length) {
#if defined(__x86_64__) || defined(__i386__)
    if ((length == 16 || length == 64) && n148_cpu_level() >= N148_CPU_AVX2)
        return coefficient_unit_mask_avx2(values, length);
#endif
    uint64_t mask = 0;
    for (int i = 0; i < length; i++)
        if (values[i] != 0) mask |= 1ull << i;
    return mask;
}

static unsigned long long coefficient_mask(const short coefficients[64]) {
    return coefficient_unit_mask(coefficients, 64);
}

static int coefficient_category(short value) {
    unsigned int magnitude = value < 0 ?
        0u - (unsigned int)value : (unsigned int)value;
#if defined(__GNUC__) || defined(__clang__)
    return magnitude ? (int)(sizeof(magnitude) * CHAR_BIT) -
        __builtin_clz(magnitude) : 0;
#else
    int bits = 0;
    while (magnitude) { magnitude >>= 1; bits++; }
    return bits;
#endif
}

static int rate_dc_bucket(int previous_category) {
    if (previous_category == 0) return 0;
    return previous_category <= 3 ? 1 : 2;
}

static int rate_band(int position) {
    return (position >= 6) + (position >= 15) + (position >= 28);
}

static int rate_neighbor_active(const N148CoeffPlane *coefficients,
                                long block, int blocks_x, int position) {
    if (block % blocks_x != 0) {
        int value = coefficients->coefficients[(block - 1) * 64 + position];
        if (value <= -4 || value >= 4) return 1;
    }
    if (block >= blocks_x) {
        int value = coefficients->coefficients[
            (block - blocks_x) * 64 + position];
        if (value <= -4 || value >= 4) return 1;
    }
    return 0;
}

static int rate_dc_model(int plane_class, int previous_category) {
    return plane_class * INTRA_RATE_DC_BUCKETS +
        rate_dc_bucket(previous_category);
}

static int rate_ac_model_packed(const N148CoeffPlane *coefficients,
                                long block, int blocks_x, int plane_class,
                                int packed_position, int local_position,
                                int previous_category) {
    int active = previous_category >= 3 || rate_neighbor_active(
        coefficients, block, blocks_x, packed_position);
    return INTRA_RATE_DC_MODELS +
        ((plane_class * INTRA_RATE_BANDS + rate_band(local_position)) *
         INTRA_RATE_ACTIVITY_BUCKETS) + active;
}

static int rate_large_ac_model(int plane_class, int position,
                               int previous_category) {
    int active = previous_category >= 3;
    return INTRA_RATE_DC_MODELS +
        ((plane_class * INTRA_RATE_BANDS + rate_band(position)) *
         INTRA_RATE_ACTIVITY_BUCKETS) + active;
}

static long mode_slot_index(int block_x, int block_y, int part,
                            int blocks_x) {
    return ((long) block_y * blocks_x + block_x) *
        N148_INTRA_MODE_SLOTS_PER_BLOCK + part;
}

static int mode_at_virtual(const uint8_t *modes, int virtual_x,
                           int virtual_y, int blocks_x) {
    int block_x = virtual_x / 2;
    int block_y = virtual_y / 2;
    int part = (virtual_y & 1) * 2 + (virtual_x & 1);
    return modes[mode_slot_index(block_x, block_y, part, blocks_x)];
}

static int mode_reference_prediction(const uint8_t *modes, long block,
                                     int part, int blocks_x,
                                     int base_mode) {
    int block_x = (int)(block % blocks_x);
    int block_y = (int)(block / blocks_x);
    int virtual_x = block_x * 2 + (part & 1);
    int virtual_y = block_y * 2 + (part >> 1);
    int has_left = virtual_x > 0;
    int has_top = virtual_y > 0;
    int left = has_left ?
        mode_at_virtual(modes, virtual_x - 1, virtual_y, blocks_x) : 0;
    int top = has_top ?
        mode_at_virtual(modes, virtual_x, virtual_y - 1, blocks_x) : 0;
    int left_matches = has_left &&
        n148_intra_base_mode(left) == base_mode;
    int top_matches = has_top &&
        n148_intra_base_mode(top) == base_mode;
    if (left_matches && top_matches) {
        int left_reference = n148_intra_reference_index(left);
        int top_reference = n148_intra_reference_index(top);
        return left_reference == top_reference ? left_reference : 0;
    }
    if (left_matches) return n148_intra_reference_index(left);
    if (top_matches) return n148_intra_reference_index(top);
    return 0;
}

static int mode_signal_symbol(const uint8_t *modes, long block, int part,
                              int blocks_x, int mode,
                              int allowed_modes) {
    if (allowed_modes <= N148_DIRECTIONAL_INTRA_MODE_COUNT) return mode;
    int base_mode = n148_intra_base_mode(mode);
    int reference = n148_intra_reference_index(mode);
    int prediction = mode_reference_prediction(
        modes, block, part, blocks_x, base_mode);
    int residual = (reference + N148_INTRA_REFERENCE_COUNT - prediction) %
        N148_INTRA_REFERENCE_COUNT;
    return base_mode + N148_DIRECTIONAL_INTRA_MODE_COUNT * residual;
}

static int rate_mode_context(const uint8_t *modes, long block, int part,
                             int blocks_x) {
    int block_x = (int)(block % blocks_x);
    int block_y = (int)(block / blocks_x);
    int virtual_x = block_x * 2 + (part & 1);
    int virtual_y = block_y * 2 + (part >> 1);
    int has_left = virtual_x > 0;
    int has_top = virtual_y > 0;
    if (!has_left && !has_top) return 0;
    int left = has_left ? n148_intra_base_mode(
        mode_at_virtual(modes, virtual_x - 1, virtual_y, blocks_x)) : -1;
    int top = has_top ? n148_intra_base_mode(
        mode_at_virtual(modes, virtual_x, virtual_y - 1, blocks_x)) : -1;
    if (has_left && has_top && left != top)
        return N148_DIRECTIONAL_INTRA_MODE_COUNT + 1;
    return 1 + (has_left ? left : top);
}

static int rate_mode_model(int plane_class, const uint8_t *modes,
                           long block, int part, int blocks_x) {
    return INTRA_RATE_COEFFICIENT_MODELS +
        plane_class * INTRA_RATE_MODE_CONTEXTS +
        rate_mode_context(modes, block, part, blocks_x);
}

static int add_rate_count(uint32_t counts[INTRA_RATE_MODEL_COUNT][256],
                          int model, int symbol) {
    if (model < 0 || model >= INTRA_RATE_MODEL_COUNT ||
        symbol < 0 || symbol > 255 || counts[model][symbol] == UINT32_MAX)
        return 0;
    counts[model][symbol]++;
    return 1;
}

static int collect_coefficient_unit_counts(
    const N148CoeffPlane *coefficients, long block, int blocks_x,
    int plane_class, int packed_offset, int length,
    int *previous_dc_category,
    uint32_t counts[INTRA_RATE_MODEL_COUNT][256]) {
    const short *values = coefficients->coefficients + block * 64 +
        packed_offset;
    int category = coefficient_category(values[0]);
    if (!add_rate_count(counts,
                        rate_dc_model(plane_class, *previous_dc_category),
                        category)) return 0;
    *previous_dc_category = category;
    int next_position = 1;
    int previous_ac_category = 0;
    uint64_t active = coefficients->nonzero_masks[block] >> packed_offset;
    if (length < 64) active &= (1ull << length) - 1ull;
    active &= ~1ull;
    while (active) {
#if defined(__GNUC__) || defined(__clang__)
        int position = __builtin_ctzll(active);
#else
        int position = 0;
        uint64_t probe = active;
        while (!(probe & 1u)) { position++; probe >>= 1; }
#endif
        active &= active - 1;
        int run = position - next_position;
        while (run > 15) {
            int model = rate_ac_model_packed(
                coefficients, block, blocks_x, plane_class,
                packed_offset + next_position, next_position,
                previous_ac_category);
            if (!add_rate_count(counts, model, 0xf0)) return 0;
            next_position += 16;
            previous_ac_category = 0;
            run -= 16;
        }
        category = coefficient_category(values[position]);
        int model = rate_ac_model_packed(
            coefficients, block, blocks_x, plane_class,
            packed_offset + next_position, next_position,
            previous_ac_category);
        if (category < 1 || category > 15 ||
            !add_rate_count(counts, model, (run << 4) | category)) return 0;
        next_position = position + 1;
        previous_ac_category = category;
    }
    if (next_position < length) {
        int model = rate_ac_model_packed(
            coefficients, block, blocks_x, plane_class,
            packed_offset + next_position, next_position,
            previous_ac_category);
        if (!add_rate_count(counts, model, 0)) return 0;
    }
    return 1;
}

static int collect_coefficient_counts(
    const N148CoeffPlane *coefficients, const uint8_t *splits,
    int blocks_x, int plane_class,
    uint32_t counts[INTRA_RATE_MODEL_COUNT][256]) {
    int previous_dc_category = 0;
    for (long block = 0; block < coefficients->count; block++) {
        int parts = splits[block] ? N148_INTRA_MODE_SLOTS_PER_BLOCK : 1;
        int length = splits[block] ? 16 : 64;
        for (int part = 0; part < parts; part++) {
            if (!collect_coefficient_unit_counts(
                    coefficients, block, blocks_x, plane_class, part * 16,
                    length, &previous_dc_category, counts)) return 0;
        }
    }
    return 1;
}

static int collect_large_coefficient_counts(
    const short *values, int length, int plane_class,
    int *previous_dc_category,
    uint32_t counts[INTRA_RATE_MODEL_COUNT][256]) {
    if (!values || (length != 16 * 16 && length != 32 * 32)) return 0;
    int category = coefficient_category(values[0]);
    if (!add_rate_count(
            counts, rate_dc_model(plane_class, *previous_dc_category),
            category)) return 0;
    *previous_dc_category = category;
    int next_position = 1;
    int previous_ac_category = 0;
    for (int position = 1; position < length; position++) {
        if (values[position] == 0) continue;
        int run = position - next_position;
        while (run > 15) {
            int model = rate_large_ac_model(
                plane_class, next_position, previous_ac_category);
            if (!add_rate_count(counts, model, 0xf0)) return 0;
            next_position += 16;
            previous_ac_category = 0;
            run -= 16;
        }
        category = coefficient_category(values[position]);
        int model = rate_large_ac_model(
            plane_class, next_position, previous_ac_category);
        if (category < 1 || category > 15 ||
            !add_rate_count(counts, model, (run << 4) | category)) return 0;
        next_position = position + 1;
        previous_ac_category = category;
    }
    if (next_position < length) {
        int model = rate_large_ac_model(
            plane_class, next_position, previous_ac_category);
        if (!add_rate_count(counts, model, 0)) return 0;
    }
    return 1;
}

static int collect_variable_luma_coefficient_counts(
    const N148CoeffPlane *coefficients, const uint8_t *splits,
    const N148TransformMap *transform_map, int blocks_x, int blocks_y,
    uint32_t counts[INTRA_RATE_MODEL_COUNT][256]) {
    if (!coefficients || !splits || !transform_map || blocks_x <= 0 ||
        blocks_y <= 0 ||
        coefficients->count != (long) blocks_x * blocks_y ||
        !fidelity_luma_transform_map_validate(transform_map)) return 0;
    int previous_dc_category = 0;
    for (int macro_y = 0; macro_y < transform_map->rows[0]; macro_y++) {
        for (int macro_x = 0; macro_x < transform_map->columns[0];
             macro_x++) {
            size_t transform_index = (size_t) macro_y *
                (size_t) transform_map->columns[0] + (size_t) macro_x;
            int first_x = macro_x * 2;
            int first_y = macro_y * 2;
            if (n148_luma_transform_dct32_member(
                    transform_map, macro_x, macro_y)) {
                if (!n148_luma_transform_dct32_origin(
                        transform_map, macro_x, macro_y)) continue;
                short sequence[32 * 32];
                for (int cell = 0; cell < 16; cell++) {
                    int block_x = first_x + (cell & 3);
                    int block_y = first_y + (cell >> 2);
                    if (block_x >= blocks_x || block_y >= blocks_y)
                        return 0;
                    long block = (long) block_y * blocks_x + block_x;
                    if (splits[block]) return 0;
                    memcpy(sequence + cell * 64,
                           coefficients->coefficients + block * 64,
                           64 * sizeof(*sequence));
                }
                if (!collect_large_coefficient_counts(
                        sequence, 32 * 32, 0, &previous_dc_category,
                        counts)) return 0;
                continue;
            }
            if (transform_map->strategies[transform_index] ==
                N148_TRANSFORM_DCT16) {
                short sequence[16 * 16];
                for (int cell = 0; cell < 4; cell++) {
                    int block_x = first_x + (cell & 1);
                    int block_y = first_y + (cell >> 1);
                    if (block_x >= blocks_x || block_y >= blocks_y)
                        return 0;
                    long block = (long) block_y * blocks_x + block_x;
                    if (splits[block]) return 0;
                    memcpy(sequence + cell * 64,
                           coefficients->coefficients + block * 64,
                           64 * sizeof(*sequence));
                }
                if (!collect_large_coefficient_counts(
                        sequence, 16 * 16, 0, &previous_dc_category,
                        counts)) return 0;
                continue;
            }
            for (int cell_y = 0; cell_y < 2; cell_y++) {
                int block_y = first_y + cell_y;
                if (block_y >= blocks_y) continue;
                for (int cell_x = 0; cell_x < 2; cell_x++) {
                    int block_x = first_x + cell_x;
                    if (block_x >= blocks_x) continue;
                    long block = (long) block_y * blocks_x + block_x;
                    int parts = splits[block] ?
                        N148_INTRA_MODE_SLOTS_PER_BLOCK : 1;
                    int length = splits[block] ? 16 : 64;
                    for (int part = 0; part < parts; part++)
                        if (!collect_coefficient_unit_counts(
                                coefficients, block, blocks_x, 0,
                                part * 16, length, &previous_dc_category,
                                counts)) return 0;
                }
            }
        }
    }
    return 1;
}

static int collect_mode_counts(
    const uint8_t *modes, long block_count, int blocks_x, int plane_class,
    const uint8_t *splits, int allowed_modes,
    uint32_t counts[INTRA_RATE_MODEL_COUNT][256]) {
    for (long block = 0; block < block_count; block++) {
        int parts = splits[block] ? N148_INTRA_MODE_SLOTS_PER_BLOCK : 1;
        int mode_limit = allowed_modes;
        for (int part = 0; part < parts; part++) {
            int mode = modes[block * N148_INTRA_MODE_SLOTS_PER_BLOCK + part];
            int model = rate_mode_model(
                plane_class, modes, block, part, blocks_x);
            int symbol = mode_signal_symbol(
                modes, block, part, blocks_x, mode, allowed_modes);
            if (mode < 0 || mode >= mode_limit ||
                (splits[block] &&
                 n148_intra_reference_index(mode) != 0) || symbol < 0 ||
                symbol >= allowed_modes ||
                !add_rate_count(counts, model, symbol)) return 0;
        }
    }
    return 1;
}

static int collect_variable_luma_mode_counts(
    const uint8_t *modes, long block_count, int blocks_x, int blocks_y,
    const uint8_t *splits, int allowed_modes,
    const N148TransformMap *transform_map,
    uint32_t counts[INTRA_RATE_MODEL_COUNT][256]) {
    if (!modes || !splits || !transform_map || blocks_x <= 0 ||
        blocks_y <= 0 || block_count != (long) blocks_x * blocks_y ||
        !fidelity_luma_transform_map_validate(transform_map)) return 0;
    for (int macro_y = 0; macro_y < transform_map->rows[0]; macro_y++) {
        for (int macro_x = 0; macro_x < transform_map->columns[0];
             macro_x++) {
            size_t transform_index = (size_t) macro_y *
                (size_t) transform_map->columns[0] + (size_t) macro_x;
            int first_x = macro_x * 2;
            int first_y = macro_y * 2;
            if (n148_luma_transform_dct32_member(
                    transform_map, macro_x, macro_y)) {
                if (!n148_luma_transform_dct32_origin(
                        transform_map, macro_x, macro_y)) continue;
                long first_block = (long) first_y * blocks_x + first_x;
                int mode = modes[first_block * N148_INTRA_MODE_SLOTS_PER_BLOCK];
                for (int cell = 0; cell < 16; cell++) {
                    int block_x = first_x + (cell & 3);
                    int block_y = first_y + (cell >> 2);
                    long block = (long) block_y * blocks_x + block_x;
                    if (splits[block]) return 0;
                    for (int part = 0;
                         part < N148_INTRA_MODE_SLOTS_PER_BLOCK; part++)
                        if (modes[block * N148_INTRA_MODE_SLOTS_PER_BLOCK +
                                  part] != mode) return 0;
                }
                int model = rate_mode_model(
                    0, modes, first_block, 0, blocks_x);
                int symbol = mode_signal_symbol(
                    modes, first_block, 0, blocks_x, mode, allowed_modes);
                if (mode < 0 || mode >= allowed_modes || symbol < 0 ||
                    symbol >= allowed_modes ||
                    !add_rate_count(counts, model, symbol)) return 0;
                continue;
            }
            if (transform_map->strategies[transform_index] ==
                N148_TRANSFORM_DCT16) {
                long block = (long) first_y * blocks_x + first_x;
                int mode = modes[block * N148_INTRA_MODE_SLOTS_PER_BLOCK];
                int model = rate_mode_model(0, modes, block, 0, blocks_x);
                int symbol = mode_signal_symbol(
                    modes, block, 0, blocks_x, mode, allowed_modes);
                if (mode < 0 || mode >= allowed_modes || symbol < 0 ||
                    symbol >= allowed_modes ||
                    !add_rate_count(counts, model, symbol)) return 0;
                continue;
            }
            for (int cell_y = 0; cell_y < 2; cell_y++) {
                int block_y = first_y + cell_y;
                if (block_y >= blocks_y) continue;
                for (int cell_x = 0; cell_x < 2; cell_x++) {
                    int block_x = first_x + cell_x;
                    if (block_x >= blocks_x) continue;
                    long block = (long) block_y * blocks_x + block_x;
                    int parts = splits[block] ?
                        N148_INTRA_MODE_SLOTS_PER_BLOCK : 1;
                    for (int part = 0; part < parts; part++) {
                        int mode = modes[block *
                            N148_INTRA_MODE_SLOTS_PER_BLOCK + part];
                        int model = rate_mode_model(
                            0, modes, block, part, blocks_x);
                        int symbol = mode_signal_symbol(
                            modes, block, part, blocks_x, mode,
                            allowed_modes);
                        if (mode < 0 || mode >= allowed_modes ||
                            (splits[block] &&
                             n148_intra_reference_index(mode) != 0) ||
                            symbol < 0 || symbol >= allowed_modes ||
                            !add_rate_count(counts, model, symbol)) return 0;
                    }
                }
            }
        }
    }
    return 1;
}

static int build_rate_model(
    const N148CoeffPlane coefficients[3], const uint8_t *modes,
    const N148PartitionMap *partition_map, int allowed_modes,
    int joint_chroma, const N148TransformMap *transform_map,
    IntraRateModel *rate_model) {
    if (!coefficients || !modes || !partition_map || !rate_model ||
        allowed_modes < 1 ||
        allowed_modes > N148_PACKED_INTRA_MODE_COUNT ||
        (joint_chroma != 0 && joint_chroma != 1) ||
        !n148_partition_map_validate(partition_map) ||
        (transform_map &&
         !fidelity_luma_transform_map_validate(transform_map))) return 0;
    uint32_t counts[INTRA_RATE_MODEL_COUNT][256] = {{0}};
    size_t mode_offset = 0;
    for (int plane = 0; plane < 3; plane++) {
        int blocks_x = partition_map->blocks_x[plane];
        int blocks_y = partition_map->blocks_y[plane];
        long block_count = coefficients[plane].count;
        const uint8_t *plane_splits = partition_map->split +
            partition_map->plane_offsets[plane];
        int plane_allowed_modes = plane == 0 ? allowed_modes :
            (allowed_modes < N148_DIRECTIONAL_INTRA_MODE_COUNT ? allowed_modes :
                                                        N148_DIRECTIONAL_INTRA_MODE_COUNT);
        if (plane == 0 && transform_map) {
            if (!collect_variable_luma_coefficient_counts(
                    &coefficients[plane], plane_splits, transform_map,
                    blocks_x, blocks_y, counts) ||
                !collect_variable_luma_mode_counts(
                    modes + mode_offset, block_count, blocks_x, blocks_y,
                    plane_splits, plane_allowed_modes, transform_map,
                    counts))
                return 0;
        } else {
            if (!collect_coefficient_counts(
                    &coefficients[plane], plane_splits, blocks_x,
                    plane == 0 ? 0 : 1, counts)) return 0;
            if (!(joint_chroma && plane == 2) && !collect_mode_counts(
                    modes + mode_offset, block_count, blocks_x,
                    plane == 0 ? 0 : 1, plane_splits,
                    plane_allowed_modes, counts)) return 0;
        }
        mode_offset += (size_t) block_count *
            N148_INTRA_MODE_SLOTS_PER_BLOCK;
    }
    for (size_t index = 0; index < partition_map->count; index++) {
        if (transform_map && index < partition_map->plane_offsets[1]) {
            size_t local = index;
            int block_x = (int)(local %
                (size_t) partition_map->blocks_x[0]);
            int block_y = (int)(local /
                (size_t) partition_map->blocks_x[0]);
            size_t transform_index = (size_t)(block_y / 2) *
                (size_t) transform_map->columns[0] +
                (size_t)(block_x / 2);
            int macro_x = block_x / 2;
            int macro_y = block_y / 2;
            if (n148_luma_transform_dct32_member(
                    transform_map, macro_x, macro_y) ||
                transform_map->strategies[transform_index] ==
                    N148_TRANSFORM_DCT16) continue;
        }
        int symbol = partition_map->split[index] ^
            n148_partition_map_predict(partition_map, index);
        if (!add_rate_count(counts, INTRA_RATE_PARTITION_MODEL, symbol))
            return 0;
    }
    if (transform_map) {
        for (size_t index = 0; index < transform_map->plane_offsets[1];
             index++) {
            uint8_t strategy = transform_map->strategies[index];
            uint8_t prediction = n148_transform_map_predict(
                transform_map, index);
            int symbol = (strategy + N148_TRANSFORM_STRATEGY_COUNT -
                          prediction) % N148_TRANSFORM_STRATEGY_COUNT;
            if (!add_rate_count(counts, INTRA_RATE_TRANSFORM_MODEL, symbol))
                return 0;
        }
    }

    memset(rate_model, 0, sizeof(*rate_model));
    for (int model = 0; model < INTRA_RATE_MODEL_COUNT; model++) {
        int mode_model_offset = model - INTRA_RATE_COEFFICIENT_MODELS;
        if (allowed_modes > N148_DIRECTIONAL_INTRA_MODE_COUNT &&
            mode_model_offset >= 0 &&
            mode_model_offset < INTRA_RATE_MODE_CONTEXTS) {
            uint64_t base_counts[N148_DIRECTIONAL_INTRA_MODE_COUNT] = {0};
            uint64_t total = 0;
            for (int base_mode = 0;
                 base_mode < N148_DIRECTIONAL_INTRA_MODE_COUNT; base_mode++) {
                for (int reference = 0;
                     reference < N148_INTRA_REFERENCE_COUNT;
                     reference++)
                    base_counts[base_mode] += counts[model][base_mode +
                        reference * N148_DIRECTIONAL_INTRA_MODE_COUNT];
                total += base_counts[base_mode];
            }
            const double prior = 0.25;
            double base_denominator = (double) total +
                prior * N148_DIRECTIONAL_INTRA_MODE_COUNT;
            for (int symbol = 0; symbol < 256; symbol++)
                rate_model->bits[model][symbol] = 64.0;
            for (int base_mode = 0;
                 base_mode < N148_DIRECTIONAL_INTRA_MODE_COUNT; base_mode++) {
                double base_bits = -log2(
                    ((double) base_counts[base_mode] + prior) /
                    base_denominator);
                double reference_denominator =
                    (double) base_counts[base_mode] +
                    prior * N148_INTRA_REFERENCE_COUNT;
                for (int reference = 0;
                     reference < N148_INTRA_REFERENCE_COUNT;
                     reference++) {
                    int symbol = base_mode +
                        reference * N148_DIRECTIONAL_INTRA_MODE_COUNT;
                    double reference_bits = -log2(
                        ((double) counts[model][symbol] + prior) /
                        reference_denominator);
                    /* A ternary reference selector carries less than two
                       raw bits. Capping only this RDO proxy prevents a cold
                       first pass from forbidding an otherwise useful line;
                       the final rANS stream still pays its exact cost. */
                    if (reference_bits > 2.0) reference_bits = 2.0;
                    rate_model->bits[model][symbol] =
                        base_bits + reference_bits;
                }
            }
            continue;
        }
        int mode_alphabet = mode_model_offset >= INTRA_RATE_MODE_CONTEXTS ?
            (allowed_modes < N148_DIRECTIONAL_INTRA_MODE_COUNT ? allowed_modes :
                                                        N148_DIRECTIONAL_INTRA_MODE_COUNT) :
            allowed_modes;
        int alphabet = model < INTRA_RATE_DC_MODELS ? 17 :
            (model < INTRA_RATE_COEFFICIENT_MODELS ? 256 :
             (model < INTRA_RATE_PARTITION_MODEL ? mode_alphabet :
              (model == INTRA_RATE_PARTITION_MODEL ? 2 : 3)));
        uint64_t total = 0;
        for (int symbol = 0; symbol < alphabet; symbol++)
            total += counts[model][symbol];
        const double prior = 0.25;
        double denominator = (double) total + prior * alphabet;
        for (int symbol = 0; symbol < 256; symbol++) {
            if (symbol < alphabet) {
                rate_model->bits[model][symbol] = -log2(
                    ((double) counts[model][symbol] + prior) / denominator);
            } else {
                rate_model->bits[model][symbol] = 64.0;
            }
        }
    }
    return 1;
}

static uint64_t block_error(const Plane *source, const Plane *reconstructed,
                            int x0, int y0) {
    int max_x = source->width - x0;
    int max_y = source->height - y0;
    if (max_x > 8) max_x = 8;
    if (max_y > 8) max_y = 8;
    uint64_t error = 0;
    for (int row = 0; row < max_y; row++) {
        for (int column = 0; column < max_x; column++) {
            int difference = sample_clamped(source, x0 + column, y0 + row) -
                sample_clamped(reconstructed, x0 + column, y0 + row);
            error += (uint64_t)(difference * difference);
        }
    }
    return error;
}

static void copy_block_from_plane(const Plane *plane, int x0, int y0,
                                  uint8_t block[64]) {
    for (int row = 0; row < 8; row++)
        for (int column = 0; column < 8; column++)
            block[row * 8 + column] =
                (uint8_t) sample_clamped(plane, x0 + column, y0 + row);
}

static void restore_valid_block(Plane *plane, int x0, int y0,
                                const uint8_t block[64]) {
    int max_x = plane->width - x0;
    int max_y = plane->height - y0;
    if (max_x > 8) max_x = 8;
    if (max_y > 8) max_y = 8;
    for (int row = 0; row < max_y; row++)
        memcpy(plane->data + (long)(y0 + row) * plane->width + x0,
               block + row * 8, (size_t) max_x);
}

static void take_macro_snapshot(const Plane *plane, int x0, int y0,
                                IntraMacroSnapshot *snapshot) {
    snapshot->x = x0 >= 2 ? x0 - 2 : 0;
    snapshot->y = y0 >= 2 ? y0 - 2 : 0;
    int right = x0 + 16;
    int bottom = y0 + 16;
    if (right > plane->width) right = plane->width;
    if (bottom > plane->height) bottom = plane->height;
    snapshot->width = right - snapshot->x;
    snapshot->height = bottom - snapshot->y;
    for (int row = 0; row < snapshot->height; row++)
        memcpy(snapshot->pixels + row * 18,
               plane->data + (long)(snapshot->y + row) * plane->width +
                   snapshot->x,
               (size_t) snapshot->width);
}

static void restore_macro_snapshot(Plane *plane,
                                   const IntraMacroSnapshot *snapshot) {
    for (int row = 0; row < snapshot->height; row++)
        memcpy(plane->data +
                   (long)(snapshot->y + row) * plane->width + snapshot->x,
               snapshot->pixels + row * 18,
               (size_t) snapshot->width);
}

static void take_super_snapshot(const Plane *plane, int x0, int y0,
                                IntraSuperSnapshot *snapshot) {
    snapshot->x = x0 >= 2 ? x0 - 2 : 0;
    snapshot->y = y0 >= 2 ? y0 - 2 : 0;
    int right = x0 + 32;
    int bottom = y0 + 32;
    if (right > plane->width) right = plane->width;
    if (bottom > plane->height) bottom = plane->height;
    snapshot->width = right - snapshot->x;
    snapshot->height = bottom - snapshot->y;
    for (int row = 0; row < snapshot->height; row++)
        memcpy(snapshot->pixels + row * 34,
               plane->data + (long)(snapshot->y + row) * plane->width +
                   snapshot->x,
               (size_t) snapshot->width);
}

static void restore_super_snapshot(Plane *plane,
                                   const IntraSuperSnapshot *snapshot) {
    for (int row = 0; row < snapshot->height; row++)
        memcpy(plane->data +
                   (long)(snapshot->y + row) * plane->width + snapshot->x,
               snapshot->pixels + row * 34,
               (size_t) snapshot->width);
}

static uint64_t region_error(const Plane *source,
                             const Plane *reconstructed,
                             int x0, int y0, int size) {
#if defined(__x86_64__) || defined(__i386__)
    if ((size == 4 || size == 8 || size == 16 || size == 32) &&
        x0 >= 0 && y0 >= 0 && size <= source->width-x0 &&
        size <= source->height-y0 && size <= reconstructed->width-x0 &&
        size <= reconstructed->height-y0 && n148_cpu_level() >= N148_CPU_AVX2)
        return pixel_error(source->data+(long)y0*source->width+x0,
            source->width, reconstructed->data+(long)y0*reconstructed->width+x0,
            reconstructed->width, size, UINT64_MAX);
#endif
    int max_x = source->width - x0;
    int max_y = source->height - y0;
    if (max_x > size) max_x = size;
    if (max_y > size) max_y = size;
    uint64_t error = 0;
    for (int row = 0; row < max_y; row++) {
        for (int column = 0; column < max_x; column++) {
            int difference = sample_clamped(source, x0 + column, y0 + row) -
                sample_clamped(reconstructed, x0 + column, y0 + row);
            error += (uint64_t)(difference * difference);
        }
    }
    return error;
}

static uint64_t fidelity_variance_sqrt(uint64_t value) {
    /* This is only called for the variance of at most 32x32 8-bit pixels.
       The variance is below 2^37, so double represents the input exactly
       and both candidate squares fit in uint64_t. Correct the hardware
       square-root estimate to keep the RDO decision bit-for-bit identical. */
    uint64_t result = (uint64_t) sqrt((double) value);
    if (result * result > value) result--;
    else if ((result + 1) * (result + 1) <= value) result++;
    return result;
}

/* A deterministic contrast term approximates SSIM's local-variance factor.
   sqrt(n*sum(x^2)-sum(x)^2) equals n times the population standard
   deviation. Four times its squared mismatch is added on the SSE scale. The
   term is encoder-only and applies exclusively to luma RDO. */
static uint64_t fidelity_region_error(
    const Plane *source, const Plane *reconstructed,
    int x0, int y0, int size, int apply_fidelity) {
    uint64_t error = region_error(source, reconstructed, x0, y0, size);
    if (!apply_fidelity ||
        !(fidelity_tools & N148_FIDELITY_STRUCTURAL_RDO)) return error;
    int max_x = source->width - x0;
    int max_y = source->height - y0;
    if (max_x > size) max_x = size;
    if (max_y > size) max_y = size;
    uint64_t samples = (uint64_t) max_x * (uint64_t) max_y;
    if (samples == 0) return error;
    uint64_t source_sum = 0, reconstructed_sum = 0;
    uint64_t source_squares = 0, reconstructed_squares = 0;
    for (int row = 0; row < max_y; row++) {
        for (int column = 0; column < max_x; column++) {
            uint64_t original = (uint64_t) sample_clamped(
                source, x0 + column, y0 + row);
            uint64_t decoded = (uint64_t) sample_clamped(
                reconstructed, x0 + column, y0 + row);
            source_sum += original;
            reconstructed_sum += decoded;
            source_squares += original * original;
            reconstructed_squares += decoded * decoded;
        }
    }
    uint64_t source_variance = samples * source_squares -
        source_sum * source_sum;
    uint64_t reconstructed_variance = samples * reconstructed_squares -
        reconstructed_sum * reconstructed_sum;
    uint64_t source_root = fidelity_variance_sqrt(source_variance);
    uint64_t reconstructed_root = fidelity_variance_sqrt(
        reconstructed_variance);
    uint64_t difference = source_root > reconstructed_root ?
        source_root - reconstructed_root :
        reconstructed_root - source_root;
    uint64_t denominator = (samples + 2u) / 4u;
    if (denominator == 0) denominator = 1;
    uint64_t penalty = (difference * difference + denominator / 2u) /
        denominator;
    return UINT64_MAX - error < penalty ? UINT64_MAX : error + penalty;
}

static double fidelity_rdo_lambda(int dc_step, int apply_fidelity) {
    double scale = apply_fidelity ? fidelity_luma_rdo_scale :
        INTRA_RDO_LAMBDA_SCALE;
    if (apply_fidelity && n148_fidelity_detail_reconstruction()) scale *= 0.9;
    return scale * dc_step * dc_step;
}

static double estimate_coefficient_unit_bits(
    const IntraRateModel *rate_model, const N148CoeffPlane *plane,
    long block, int blocks_x, int plane_class, int previous_dc_category,
    const short values[64], int packed_offset, int length,
    int *ending_dc_category) {
    const short *unit = values + packed_offset;
    int category = coefficient_category(unit[0]);
    int model = rate_dc_model(plane_class, previous_dc_category);
    double bits = rate_model->bits[model][category] + category;
    if (ending_dc_category) *ending_dc_category = category;
    int next_position = 1;
    int previous_ac_category = 0;
    uint64_t active = coefficient_unit_mask(unit, length) & ~1ull;
    while (active) {
#if defined(__GNUC__) || defined(__clang__)
        int position = __builtin_ctzll(active);
#else
        int position = 0;
        uint64_t probe = active;
        while (!(probe & 1u)) { position++; probe >>= 1; }
#endif
        active &= active - 1;
        int run = position - next_position;
        while (run > 15) {
            model = rate_ac_model_packed(
                plane, block, blocks_x, plane_class,
                packed_offset + next_position, next_position,
                previous_ac_category);
            bits += rate_model->bits[model][0xf0];
            next_position += 16;
            previous_ac_category = 0;
            run -= 16;
        }
        category = coefficient_category(unit[position]);
        model = rate_ac_model_packed(
            plane, block, blocks_x, plane_class,
            packed_offset + next_position, next_position,
            previous_ac_category);
        bits += rate_model->bits[model][(run << 4) | category] + category;
        next_position = position + 1;
        previous_ac_category = category;
    }
    if (next_position < length) {
        model = rate_ac_model_packed(
            plane, block, blocks_x, plane_class,
            packed_offset + next_position, next_position,
            previous_ac_category);
        bits += rate_model->bits[model][0];
    }
    return bits;
}

static double estimate_coefficient_bits(
    const IntraRateModel *rate_model, const N148CoeffPlane *plane,
    long block, int blocks_x, int plane_class, int previous_dc_category,
    const short values[64], int split) {
    int parts = split ? N148_INTRA_MODE_SLOTS_PER_BLOCK : 1;
    int length = split ? 16 : 64;
    double bits = 0.0;
    int dc_category = previous_dc_category;
    for (int part = 0; part < parts; part++) {
        bits += estimate_coefficient_unit_bits(
            rate_model, plane, block, blocks_x, plane_class, dc_category,
            values, part * 16, length, &dc_category);
    }
    return bits;
}

static double estimate_large_coefficient_bits(
    const IntraRateModel *rate_model, int plane_class,
    int previous_dc_category, const short *values, int length) {
    if (!values || (length != 16 * 16 && length != 32 * 32)) return DBL_MAX;
    int category = coefficient_category(values[0]);
    double bits = rate_model->bits[
        rate_dc_model(plane_class, previous_dc_category)][category] +
        category;
    int next_position = 1;
    int previous_ac_category = 0;
    for (int position = 1; position < length; position++) {
        if (values[position] == 0) continue;
        int run = position - next_position;
        while (run > 15) {
            int model = rate_large_ac_model(
                plane_class, next_position, previous_ac_category);
            bits += rate_model->bits[model][0xf0];
            next_position += 16;
            previous_ac_category = 0;
            run -= 16;
        }
        category = coefficient_category(values[position]);
        int model = rate_large_ac_model(
            plane_class, next_position, previous_ac_category);
        bits += rate_model->bits[model][(run << 4) | category] + category;
        next_position = position + 1;
        previous_ac_category = category;
    }
    if (next_position < length) {
        int model = rate_large_ac_model(
            plane_class, next_position, previous_ac_category);
        bits += rate_model->bits[model][0];
    }
    return bits;
}

typedef struct {
    double cost;
    int previous_position;
    int previous_category;
    short value;
} IntraTrellisState;

typedef struct {
    double cost;
    int category;
} IntraTrellisPredecessor;

static int add_trellis_candidate(short candidates[4], int count, int value) {
    if (value == 0 || value < SHRT_MIN || value > SHRT_MAX) return count;
    for (int index = 0; index < count; index++)
        if (candidates[index] == value) return count;
    if (count < 4) candidates[count++] = (short) value;
    return count;
}

/* lrintf followed by int conversion, specialized only for the finite range
   where the SSE2 conversion has the same result and floating-point flags.
   It observes the current hardware rounding mode. Out-of-range values keep
   the existing library path. */
static inline int trellis_round(float value) {
#if (defined(__x86_64__) || defined(__i386__)) && defined(__SSE2__)
    if (value >= -2147483648.0f && value < 2147483648.0f)
        return _mm_cvtss_si32(_mm_set_ss(value));
#endif
    return (int)lrintf(value);
}


static int trellis_candidates(float ideal, short input, int effort,
                              int trellis_policy,
                              short candidates[4]) {
    int count = 0;
    int rounded = trellis_round(ideal);
    count = add_trellis_candidate(candidates, count, input);
    count = add_trellis_candidate(candidates, count, rounded);
    if (rounded > 1)
        count = add_trellis_candidate(candidates, count, rounded - 1);
    else if (rounded < -1)
        count = add_trellis_candidate(candidates, count, rounded + 1);
    if (trellis_policy == N148_TRELLIS_PERCEPTUAL_LUMA || effort >= 8) {
        if (rounded > 0)
            count = add_trellis_candidate(candidates, count, rounded + 1);
        else if (rounded < 0)
            count = add_trellis_candidate(candidates, count, rounded - 1);
        else if (ideal != 0.0f)
            count = add_trellis_candidate(
                candidates, count, ideal < 0.0f ? -1 : 1);
    }
    return count;
}

static double trellis_coefficient_distortion(float ideal, short value,
                                              double energy) {
    double difference = (double) ideal - value;
    return difference * difference * energy;
}

static double trellis_frequency_energy(double energy, int length,
                                       int position, int trellis_policy) {
    if (trellis_policy != N148_TRELLIS_PERCEPTUAL_LUMA) return energy;
    int size = length == 16 ? 4 : 8;
    int natural = size == 4 ? n148_variable_zigzag(4, position) :
        ZIGZAG[position];
    int frequency = natural / size + natural % size;
    if (frequency > PERCEPTUAL_LUMA_PROTECTED_FREQUENCY_SUM) return energy;
    return energy * (1.0 + PERCEPTUAL_LUMA_LOW_FREQUENCY_BOOST /
                      (frequency + 1.0));
}

typedef struct {
    const IntraRateModel *rate_model;
    int base_model[64];
    uint8_t neighbor_active[64];
} IntraTrellisRateCache;

static int trellis_ac_model(const IntraTrellisRateCache *cache,
                            int position, int previous_category) {
    return cache->base_model[position] +
        (previous_category >= 3 || cache->neighbor_active[position]);
}

static double estimate_trellis_event_bits(
    const IntraTrellisRateCache *cache,
    int next_position, int previous_category, int position, int category) {
    int run = position - next_position;
    double bits = 0.0;
    while (run > 15) {
        int model = trellis_ac_model(cache, next_position, previous_category);
        bits += cache->rate_model->bits[model][0xf0];
        next_position += 16;
        previous_category = 0;
        run -= 16;
    }
    int model = trellis_ac_model(cache, next_position, previous_category);
    return bits + cache->rate_model->bits[model][(run << 4) | category] +
        category;
}

static double estimate_trellis_eob_bits(
    const IntraTrellisRateCache *cache,
    int next_position, int previous_category, int length) {
    if (next_position >= length) return 0.0;
    int model = trellis_ac_model(cache, next_position, previous_category);
    return cache->rate_model->bits[model][0];
}

static double cached_trellis_unit_bits(
    const IntraTrellisRateCache *cache, int plane_class, int previous_dc_category,
    const short values[64], int packed_offset, int length, int *ending_dc_category) {
    const short *unit = values + packed_offset;
    int category = coefficient_category(unit[0]);
    int model = rate_dc_model(plane_class, previous_dc_category);
    double bits = cache->rate_model->bits[model][category] + category;
    if (ending_dc_category) *ending_dc_category = category;
    int next_position = 1;
    int previous_ac_category = 0;
    uint64_t active = coefficient_unit_mask(unit, length) & ~1ull;
    while (active) {
#if defined(__GNUC__) || defined(__clang__)
        int position = __builtin_ctzll(active);
#else
        int position = 0;
        uint64_t probe = active;
        while (!(probe & 1u)) { position++; probe >>= 1; }
#endif
        active &= active - 1;
        int run = position - next_position;
        while (run > 15) {
            model = trellis_ac_model(cache, next_position, previous_ac_category);
            bits += cache->rate_model->bits[model][0xf0];
            next_position += 16;
            previous_ac_category = 0;
            run -= 16;
        }
        category = coefficient_category(unit[position]);
        model = trellis_ac_model(cache, next_position, previous_ac_category);
        bits += cache->rate_model->bits[model][(run << 4) | category] + category;
        next_position = position + 1;
        previous_ac_category = category;
    }
    if (next_position < length) {
        model = trellis_ac_model(cache, next_position, previous_ac_category);
        bits += cache->rate_model->bits[model][0];
    }
    return bits;
}

static double cached_trellis_objective(
    const IntraTrellisRateCache *cache, int plane_class, int previous_dc_category,
    const float *ideal_levels, const double *effective_energy,
    const short values[64], int packed_offset, int length, double lambda) {
    double distortion = 0.0;
    for (int position = 1; position < length; position++)
        distortion += trellis_coefficient_distortion(
            ideal_levels[position], values[packed_offset + position], effective_energy[position]);
    double bits = cached_trellis_unit_bits(cache, plane_class, previous_dc_category,
                                          values, packed_offset, length, NULL);
    return distortion + lambda * bits;
}

static double trellis_unit_objective(
    const IntraRateModel *rate_model, const N148CoeffPlane *plane,
    long block, int blocks_x, int plane_class, int previous_dc_category,
    const float *ideal_levels, const double *energy,
    const short values[64], int packed_offset, int length, double lambda,
    int trellis_policy) {
    double distortion = 0.0;
    for (int position = 1; position < length; position++)
        distortion += trellis_coefficient_distortion(
            ideal_levels[position], values[packed_offset + position],
            trellis_frequency_energy(
                energy[position], length, position, trellis_policy));
    int ignored_dc_category;
    double bits = estimate_coefficient_unit_bits(
        rate_model, plane, block, blocks_x, plane_class,
        previous_dc_category, values, packed_offset, length,
        &ignored_dc_category);
    return distortion + lambda * bits;
}

/* Dynamic programming over run/category states. Unlike the base proxy, this
   pass prices the exact contextual symbols that the current frame will emit
   and weights transform directions by their spatial gradient energy. The
   perceptual-luma profile's
   policy additionally protects selected low frequencies. */
static int refine_coefficients_contextually(
    const IntraRateModel *rate_model, const N148CoeffPlane *plane,
    long block, int blocks_x, int plane_class, int previous_dc_category,
    const float *ideal_levels, const double *energy, int packed_offset,
    int length, int effort, int trellis_policy, int structural_sse,
    short values[64]) {
    if (!rate_model || !plane || !ideal_levels || !energy || !values ||
        length < 2 || length > 64 || packed_offset < 0 ||
        packed_offset + length > 64 || effort < 0 || effort > 9 ||
        trellis_policy < N148_TRELLIS_LEGACY ||
        trellis_policy > N148_TRELLIS_PERCEPTUAL_LUMA)
        return 0;
    double lambda = (structural_sse ? STRUCTURAL_TRELLIS_LAMBDA_SCALE :
        trellis_policy == N148_TRELLIS_PERCEPTUAL_LUMA ?
        PERCEPTUAL_LUMA_TRELLIS_LAMBDA_SCALE :
        CONTEXTUAL_TRELLIS_LAMBDA_SCALE) * energy[0];
    if (structural_sse && n148_fidelity_balanced_reconstruction())
        lambda = (plane_class ? 0.068 : 0.068) * energy[0];
    /* With no AC input and no available nonzero level, the DP has
       only its all-zero path. Check the same objective's finiteness once. */
    if (trellis_policy == N148_TRELLIS_LEGACY && effort < 8 &&
        !(coefficient_unit_mask(values + packed_offset, length) & ~1ull)) {
        int only_zero = 1;
        for (int position = 1; position < length; ++position) {
            if (trellis_round(ideal_levels[position]) != 0) {
                only_zero = 0;
                break;
            }
        }
        if (only_zero) return isfinite(trellis_unit_objective(
            rate_model, plane, block, blocks_x, plane_class,
            previous_dc_category, ideal_levels, energy, values,
            packed_offset, length, lambda, trellis_policy));
    }
    IntraTrellisRateCache cache = {.rate_model = rate_model};
    double effective_energy[64];
    for (int position = 1; position < length; position++) {
        cache.base_model[position] = INTRA_RATE_DC_MODELS +
            ((plane_class * INTRA_RATE_BANDS + rate_band(position)) *
             INTRA_RATE_ACTIVITY_BUCKETS);
        cache.neighbor_active[position] = (uint8_t) rate_neighbor_active(
            plane, block, blocks_x, packed_offset + position);
        effective_energy[position] = trellis_frequency_energy(
            energy[position], length, position, trellis_policy);
    }
    double input_distortion = 0.0;
    double zero_prefix[65] = {0.0};
    for (int position = 1; position < length; position++) {
        zero_prefix[position + 1] = zero_prefix[position] +
            trellis_coefficient_distortion(
                ideal_levels[position], 0, effective_energy[position]);
        input_distortion += trellis_coefficient_distortion(
            ideal_levels[position], values[packed_offset + position], effective_energy[position]);
    }
    /* Only two classes of predecessor category affect any later event.
       Retain one state per class, and a separate terminal state so final
       floating-point ties are still resolved over every category. */
    IntraTrellisState states[64][2];
    int active_positions[64];
    int active_count = 0;
    double prefix_minimum_base[64], prefix_maximum_magnitude[64];
    double best = zero_prefix[length] - zero_prefix[1] + lambda *
        estimate_trellis_eob_bits(&cache, 1, 0, length);
    int best_position = -1;
    int best_category = 0;
    IntraTrellisState terminal = {0};

    for (int position = 1; position < length; position++) {
        short candidates[4];
        int candidate_count = trellis_candidates(
            ideal_levels[position], values[packed_offset + position],
            effort, trellis_policy, candidates);
        if (!candidate_count) continue;
        IntraTrellisState current[4];
        int categories[4];
        int current_count = 0;
        int first_category = coefficient_category(candidates[0]);
        double first_distortion = trellis_coefficient_distortion(
            ideal_levels[position], candidates[0], effective_energy[position]);
        for (int candidate_index = 0; candidate_index < candidate_count;
             candidate_index++) {
            short value = candidates[candidate_index];
            int category = coefficient_category(value);
            if (category <= 0 || category > 15) continue;
            double coefficient_cost = trellis_coefficient_distortion(
                ideal_levels[position], value, effective_energy[position]);
            /* Same category means identical transition rates. A later
               candidate with no smaller distortion cannot beat the first one,
               including floating-point ties, which retain the earlier value. */
            if (candidate_index && category == first_category &&
                coefficient_cost >= first_distortion) continue;
            double current_best = zero_prefix[position] - zero_prefix[1] +
                coefficient_cost + lambda * estimate_trellis_event_bits(
                    &cache, 1, 0, position, category);
            int previous_position = -1;
            int previous_bucket = 0;
            for (int active = active_count - 1; active >= 0; active--) {
                int previous = active_positions[active];
                double group_bound = prefix_minimum_base[active] +
                    zero_prefix[position] + coefficient_cost;
                /* Conservative allowance for the reassociated lower bound.
                   Overflow disables pruning. Original costs and tie order
                   are still used for every surviving predecessor. */
                double slack = 64.0 * DBL_EPSILON *
                    (prefix_maximum_magnitude[active] + zero_prefix[position] +
                     coefficient_cost + fabs(current_best) + 1.0);
                if (group_bound > current_best + slack) break;
                for (int bucket = 0; bucket < 2; bucket++) {
                    const IntraTrellisState *prior = &states[previous][bucket];
                    if (prior->cost == DBL_MAX) continue;
                    double lower_bound = prior->cost + zero_prefix[position] -
                        zero_prefix[previous + 1] + coefficient_cost;
                    /* Same evaluation order as the full cost, before adding
                       its nonnegative rate. Strict bound leaves equal-cost
                       predecessor ties available for original order. */
                    if (lower_bound > current_best) continue;
                    double cost = lower_bound + lambda *
                        estimate_trellis_event_bits(
                            &cache, previous + 1, bucket ? 3 : 1,
                            position, category);
                    if (cost < current_best ||
                        (cost == current_best && previous_position >= 0 &&
                         (previous < previous_position ||
                          (previous == previous_position && bucket < previous_bucket)))) {
                        current_best = cost;
                        previous_position = previous;
                        previous_bucket = bucket;
                    }
                }
            }
            int slot = 0;
            while (slot < current_count && categories[slot] != category) slot++;
            if (slot == current_count) {
                categories[slot] = category;
                current[slot].cost = DBL_MAX;
                current_count++;
            }
            if (current_best < current[slot].cost) {
                current[slot].cost = current_best;
                current[slot].previous_position = previous_position;
                current[slot].previous_category = previous_bucket;
                current[slot].value = value;
            }
        }
        states[position][0].cost = DBL_MAX;
        states[position][1].cost = DBL_MAX;
        states[position][0].value = states[position][1].value = 0;
        for (int slot = 0; slot < current_count; slot++) {
            const IntraTrellisState *node = &current[slot];
            if (node->cost == DBL_MAX) continue;
            int category = categories[slot];
            int bucket = category >= 3;
            IntraTrellisState *kept = &states[position][bucket];
            if (node->cost < kept->cost ||
                (node->cost == kept->cost &&
                 category < coefficient_category(kept->value)))
                *kept = *node;
            double cost = node->cost + zero_prefix[length] -
                zero_prefix[position + 1] + lambda *
                estimate_trellis_eob_bits(&cache, position + 1, category, length);
            if (cost < best || (cost == best && best_position == position &&
                                category < best_category)) {
                best = cost;
                best_position = position;
                best_category = category;
                terminal = *node;
            }
        }
        if (states[position][0].cost != DBL_MAX ||
            states[position][1].cost != DBL_MAX) {
            double minimum = active_count ? prefix_minimum_base[active_count-1] : DBL_MAX;
            double magnitude = active_count ? prefix_maximum_magnitude[active_count-1] : 0.0;
            for (int bucket = 0; bucket < 2; bucket++) {
                double cost = states[position][bucket].cost;
                if (cost == DBL_MAX) continue;
                double base = cost - zero_prefix[position + 1];
                if (base < minimum) minimum = base;
                double bound = fabs(cost) + zero_prefix[position + 1];
                if (bound > magnitude) magnitude = bound;
            }
            prefix_minimum_base[active_count] = minimum;
            prefix_maximum_magnitude[active_count] = magnitude;
            active_positions[active_count++] = position;
        }
    }

    short input[64];
    memcpy(input, values, sizeof(input));
    memset(values + packed_offset + 1, 0,
           (size_t)(length - 1) * sizeof(*values));
    if (best_position >= 1) {
        values[packed_offset + best_position] = terminal.value;
        int previous_position = terminal.previous_position;
        int previous_bucket = terminal.previous_category;
        while (previous_position >= 1) {
            const IntraTrellisState *node = &states[previous_position][previous_bucket];
            values[packed_offset + previous_position] = node->value;
            previous_position = node->previous_position;
            previous_bucket = node->previous_category;
        }
    }
    double input_cost = input_distortion + lambda * cached_trellis_unit_bits(
        &cache, plane_class, previous_dc_category, input, packed_offset, length, NULL);
    /* Equal coefficient vectors have exactly equal objectives. Preserve the
       original nonfinite rejection while avoiding its duplicate calculation. */
    if (memcmp(input, values, sizeof(input)) == 0) return isfinite(input_cost);
    double output_cost = cached_trellis_objective(
        &cache, plane_class, previous_dc_category, ideal_levels, effective_energy,
        values, packed_offset, length, lambda);
    if (!isfinite(input_cost) || !isfinite(output_cost) ||
        output_cost > input_cost + 1e-9 * (fabs(input_cost) + 1.0)) {
        memcpy(values, input, sizeof(input));
        return 0;
    }
    return 1;
}

static int candidate_mode_at_virtual(
    const uint8_t *committed_modes, long current_block,
    const uint8_t candidate_modes[N148_INTRA_MODE_SLOTS_PER_BLOCK],
    int virtual_x, int virtual_y, int blocks_x) {
    int block_x = virtual_x / 2;
    int block_y = virtual_y / 2;
    int part = (virtual_y & 1) * 2 + (virtual_x & 1);
    long block = (long) block_y * blocks_x + block_x;
    if (block == current_block) return candidate_modes[part];
    return committed_modes[block * N148_INTRA_MODE_SLOTS_PER_BLOCK + part];
}

static int candidate_reference_prediction(
    const uint8_t *committed_modes, long block,
    const uint8_t candidate_modes[N148_INTRA_MODE_SLOTS_PER_BLOCK],
    int part, int blocks_x, int base_mode) {
    int block_x = (int)(block % blocks_x);
    int block_y = (int)(block / blocks_x);
    int virtual_x = block_x * 2 + (part & 1);
    int virtual_y = block_y * 2 + (part >> 1);
    int has_left = virtual_x > 0;
    int has_top = virtual_y > 0;
    int left = has_left ? candidate_mode_at_virtual(
        committed_modes, block, candidate_modes,
        virtual_x - 1, virtual_y, blocks_x) : 0;
    int top = has_top ? candidate_mode_at_virtual(
        committed_modes, block, candidate_modes,
        virtual_x, virtual_y - 1, blocks_x) : 0;
    int left_matches = has_left &&
        n148_intra_base_mode(left) == base_mode;
    int top_matches = has_top &&
        n148_intra_base_mode(top) == base_mode;
    if (left_matches && top_matches) {
        int left_reference = n148_intra_reference_index(left);
        int top_reference = n148_intra_reference_index(top);
        return left_reference == top_reference ? left_reference : 0;
    }
    if (left_matches) return n148_intra_reference_index(left);
    if (top_matches) return n148_intra_reference_index(top);
    return 0;
}

static int candidate_mode_context(
    const uint8_t *committed_modes, long block,
    const uint8_t candidate_modes[N148_INTRA_MODE_SLOTS_PER_BLOCK],
    int part, int blocks_x) {
    int block_x = (int)(block % blocks_x);
    int block_y = (int)(block / blocks_x);
    int virtual_x = block_x * 2 + (part & 1);
    int virtual_y = block_y * 2 + (part >> 1);
    int has_left = virtual_x > 0;
    int has_top = virtual_y > 0;
    if (!has_left && !has_top) return 0;
    int left = has_left ? n148_intra_base_mode(candidate_mode_at_virtual(
        committed_modes, block, candidate_modes,
        virtual_x - 1, virtual_y, blocks_x)) : -1;
    int top = has_top ? n148_intra_base_mode(candidate_mode_at_virtual(
        committed_modes, block, candidate_modes,
        virtual_x, virtual_y - 1, blocks_x)) : -1;
    if (has_left && has_top && left != top)
        return N148_DIRECTIONAL_INTRA_MODE_COUNT + 1;
    return 1 + (has_left ? left : top);
}

static double estimate_mode_bits_from(
    const IntraRateModel *rate_model, int plane_class,
    const uint8_t *committed_modes, long block,
    const uint8_t candidate_modes[N148_INTRA_MODE_SLOTS_PER_BLOCK],
    int first_part, int parts, int blocks_x, double bits) {
    for (int part = first_part; part < parts; part++) {
        int context = candidate_mode_context(
            committed_modes, block, candidate_modes, part, blocks_x);
        int model = INTRA_RATE_COEFFICIENT_MODELS +
            plane_class * INTRA_RATE_MODE_CONTEXTS + context;
        int mode = candidate_modes[part];
        int symbol = mode;
        if (plane_class == 0 &&
            (fidelity_tools & N148_FIDELITY_MULTIPLE_REFERENCES)) {
            int base_mode = n148_intra_base_mode(mode);
            int prediction = candidate_reference_prediction(
                committed_modes, block, candidate_modes, part, blocks_x,
                base_mode);
            int residual = (n148_intra_reference_index(mode) +
                N148_INTRA_REFERENCE_COUNT - prediction) %
                N148_INTRA_REFERENCE_COUNT;
            symbol = base_mode + N148_DIRECTIONAL_INTRA_MODE_COUNT * residual;
        }
        bits += rate_model->bits[model][symbol];
    }
    return bits;
}

static double estimate_mode_bits(
    const IntraRateModel *rate_model, int plane_class,
    const uint8_t *committed_modes, long block,
    const uint8_t candidate_modes[N148_INTRA_MODE_SLOTS_PER_BLOCK],
    int parts, int blocks_x) {
    return estimate_mode_bits_from(
        rate_model, plane_class, committed_modes, block, candidate_modes,
        0, parts, blocks_x, 0.0);
}

static double estimate_partition_bits(
    const IntraRateModel *rate_model, const N148PartitionMap *partition_map,
    size_t map_index, int split) {
    int prediction = n148_partition_map_predict(partition_map, map_index);
    return rate_model->bits[INTRA_RATE_PARTITION_MODEL][split ^ prediction];
}

/* Rank four base modes and two angular candidates using quantized SSE
   plus the initial contextual rate; reconstruct and trellis the winner. */
#if defined(__x86_64__) || defined(__i386__)
__attribute__((target("avx2")))
static uint64_t activity_mask_avx2(const short *values) {
    uint64_t result = 0;
    __m256i upper = _mm256_set1_epi16(3), lower = _mm256_set1_epi16(-3);
    for (int i = 0; i < 64; i += 32) {
        __m256i a = _mm256_loadu_si256((const __m256i *)(values+i));
        __m256i b = _mm256_loadu_si256((const __m256i *)(values+i+16));
        a = _mm256_or_si256(_mm256_cmpgt_epi16(a,upper),_mm256_cmpgt_epi16(lower,a));
        b = _mm256_or_si256(_mm256_cmpgt_epi16(b,upper),_mm256_cmpgt_epi16(lower,b));
        __m256i packed = _mm256_permute4x64_epi64(_mm256_packs_epi16(a,b),0xd8);
        result |= (uint64_t)(uint32_t)_mm256_movemask_epi8(packed) << i;
    }
    return result;
}
#endif
static uint64_t activity_mask(const short *values) {
#if defined(__x86_64__) || defined(__i386__)
    if (n148_cpu_level() >= N148_CPU_AVX2) return activity_mask_avx2(values);
#endif
    uint64_t mask = 0;
    for (int i=0;i<64;i++) if (values[i] <= -4 || values[i] >= 4) mask |= 1ull<<i;
    return mask;
}
static uint64_t coefficient_neighbor_mask(const N148CoeffPlane *plane,
                                         long block, int blocks_x) {
    uint64_t mask = 0;
    if (block % blocks_x) mask |= activity_mask(plane->coefficients+(block-1)*64);
    if (block >= blocks_x) mask |= activity_mask(plane->coefficients+(block-blocks_x)*64);
    return mask;
}

static double cached_coefficient8_bits(
    const IntraRateModel *rate_model, uint64_t neighbor_mask,
    int previous_dc_category, const short values[64]) {
    const short *unit = values;
    const int plane_class = 0, length = 64;
    int category = coefficient_category(unit[0]);
    int model = rate_dc_model(plane_class, previous_dc_category);
    double bits = rate_model->bits[model][category] + category;
    int next_position = 1;
    int previous_ac_category = 0;
    uint64_t active = coefficient_unit_mask(unit, length) & ~1ull;
    while (active) {
#if defined(__GNUC__) || defined(__clang__)
        int position = __builtin_ctzll(active);
#else
        int position = 0;
        uint64_t probe = active;
        while (!(probe & 1u)) { position++; probe >>= 1; }
#endif
        active &= active - 1;
        int run = position - next_position;
        while (run > 15) {
            model = (INTRA_RATE_DC_MODELS + rate_band(next_position) *
                INTRA_RATE_ACTIVITY_BUCKETS +
                (previous_ac_category >= 3 || ((neighbor_mask >> next_position) & 1u)));
            bits += rate_model->bits[model][0xf0];
            next_position += 16;
            previous_ac_category = 0;
            run -= 16;
        }
        category = coefficient_category(unit[position]);
        model = (INTRA_RATE_DC_MODELS + rate_band(next_position) *
                INTRA_RATE_ACTIVITY_BUCKETS +
                (previous_ac_category >= 3 || ((neighbor_mask >> next_position) & 1u)));
        bits += rate_model->bits[model][(run << 4) | category] + category;
        next_position = position + 1;
        previous_ac_category = category;
    }
    if (next_position < length) {
        model = (INTRA_RATE_DC_MODELS + rate_band(next_position) *
                INTRA_RATE_ACTIVITY_BUCKETS +
                (previous_ac_category >= 3 || ((neighbor_mask >> next_position) & 1u)));
        bits += rate_model->bits[model][0];
    }
    return bits;
}


/* Compute independent products in SIMD, then accumulate in the original
 * scalar order. A partial nonnegative sum can reject only a losing trial. */
#if defined(__x86_64__) || defined(__i386__)
__attribute__((target("avx2")))
static double quantized_error_avx2(const float *ideal, const short *levels,
    const double *energy, int length, double mode_cost, double best_cost) {
    double distortion=0.0;
    for (int k=0; k<length; k+=4) {
        __m128i packed=_mm_loadl_epi64((const __m128i *)(levels+k));
        __m256d value=_mm256_cvtepi32_pd(_mm_cvtepi16_epi32(packed));
        __m256d target=_mm256_cvtps_pd(_mm_loadu_ps(ideal+k));
        __m256d delta=_mm256_sub_pd(target,value);
        __m256d term=_mm256_mul_pd(_mm256_mul_pd(delta,delta),_mm256_loadu_pd(energy+k));
        double terms[4];
        _mm256_storeu_pd(terms,term);
        distortion+=terms[0];
        distortion+=terms[1];
        distortion+=terms[2];
        distortion+=terms[3];
        if (distortion+mode_cost>=best_cost) break;
    }
    return distortion;
}
#endif

static double quantized_error(const float *ideal, const short *levels,
    const double *energy, int length, double mode_cost, double best_cost) {
#if defined(__x86_64__) || defined(__i386__)
    if (n148_cpu_level()>=N148_CPU_AVX2)
        return quantized_error_avx2(ideal,levels,energy,length,mode_cost,best_cost);
#endif
    double distortion=0.0;
    for (int k=0; k<length; k++) {
        double error=(double)ideal[k]-levels[k];
        distortion+=error*error*energy[k];
        if ((k&3)==3 && distortion+mode_cost>=best_cost) break;
    }
    return distortion;
}

static int choose_quantized_mode8(
    const Plane *source, const Plane *reconstructed, int x0, int y0,
    uint8_t neutral, int mode_count, int causal_right, const IntraQuant8 *quant,
    const IntraRateModel *rate_model, const N148CoeffPlane *coefficient_plane,
    const uint8_t *committed_modes, long block, int blocks_x,
    int previous_dc_category, uint8_t prediction[64],
    short best_coefficients[64], float best_ideal[64]) {
    N148PreparedSquare references;
    prepare_square_references(reconstructed, x0, y0, 8, neutral,
                              causal_right, fidelity_tools, 0, &references);
    if (mode_count > 10) mode_count = 10;
    /* Keep the four established quantized trials, then shortlist two of
       the six existing angular modes by prediction SSE. Only the shortlist
       omits transforms; the selected modes keep the full quantized score. */
    uint8_t extra_prediction[6][64];
    int first_extra = -1, second_extra = -1;
    uint64_t first_sse = UINT64_MAX, second_sse = UINT64_MAX;
    for (int mode = 4; mode < mode_count; mode++) {
        predict_square_prepared(&references, 8, mode, neutral, extra_prediction[mode-4]);
        uint64_t score = prediction_sse(source, x0, y0, 8,
                                       extra_prediction[mode-4], second_sse);
        if (score < first_sse) {
            second_sse = first_sse; second_extra = first_extra;
            first_sse = score; first_extra = mode;
        } else if (score < second_sse) {
            second_sse = score; second_extra = mode;
        }
    }
    uint64_t neighbor_mask = coefficient_neighbor_mask(coefficient_plane, block, blocks_x);
    double best_cost = DBL_MAX;
    int best_mode = -1;
    double lambda = fidelity_rdo_lambda(quant->dc_step, 1);
    for (int mode = 0; mode < mode_count; mode++) {
        if (mode >= 4 && mode != first_extra && mode != second_extra) continue;
        uint8_t trial[64], modes[N148_INTRA_MODE_SLOTS_PER_BLOCK];
        short coefficients[64];
        float ideal[64];
        memset(modes, mode, sizeof(modes));
        double mode_rate = estimate_mode_bits(rate_model, 0, committed_modes,
                                              block, modes, 1, blocks_x);
        /* Distortion and coefficient rate are nonnegative. Later mode ties
           keep the earlier mode, so this bound preserves the full search. */
        if (lambda * mode_rate >= best_cost) continue;
        if (mode >= 4) memcpy(trial, extra_prediction[mode-4], 64);
        else predict_square_prepared(&references, 8, mode, neutral, trial);
        if (!quantize8(source, x0, y0, trial, quant, coefficients, ideal))
            return -1;
        double distortion = quantized_error(ideal, coefficients,
            quant->unit_energy, 64, lambda * mode_rate, best_cost);
        if (distortion + lambda * mode_rate >= best_cost) continue;
        double rate = cached_coefficient8_bits(
            rate_model, neighbor_mask, previous_dc_category, coefficients) + mode_rate;
        double cost = distortion + lambda * rate;
        if (cost < best_cost) {
            best_cost = cost;
            best_mode = mode;
            memcpy(prediction, trial, 64);
            memcpy(best_coefficients, coefficients, sizeof(coefficients));
            memcpy(best_ideal, ideal, sizeof(ideal));
        }
    }
    return best_mode;
}

static int make_unsplit_rdo_candidate(
    const Plane *source, Plane *reconstructed, int x0, int y0,
    uint8_t neutral, int mode_count, int causal_right,
    const IntraQuant8 *quant, int effort,
    int trellis_policy,
    const IntraRateModel *rate_model, const N148CoeffPlane *coefficient_plane,
    const uint8_t *committed_modes, long block, int blocks_x,
    int plane_class, int previous_dc_category,
    const N148PartitionMap *partition_map, size_t map_index,
    IntraBlockCandidate *candidate) {
    uint8_t saved[64];
    copy_block_from_plane(reconstructed, x0, y0, saved);
    int shortlist_mode = -1;
    int runner_up = -1;
    uint64_t prediction_score = 0;
    uint8_t shortlist_prediction[64];
    short shortlist_coefficients[64];
    float shortlist_ideal[64];
    int quantized_shortlist = effort == 3 && plane_class == 0 &&
        (fidelity_tools & N148_FIDELITY_STRUCTURAL_LUMA_QUANT) &&
        (fidelity_tools & N148_FIDELITY_FAST_MODE_SEARCH);
    if (quantized_shortlist) {
        shortlist_mode = choose_quantized_mode8(
            source, reconstructed, x0, y0, neutral, mode_count, causal_right,
            quant, rate_model, coefficient_plane, committed_modes, block,
            blocks_x, previous_dc_category, shortlist_prediction,
            shortlist_coefficients, shortlist_ideal);
        if (shortlist_mode < 0) return 0;
    } else if (effort < 5) {
        int refined_effort3 = effort == 3 &&
            (fidelity_tools & N148_FIDELITY_REFINED_SPECTRAL_LUMA_QUANT);
        int effort4_selective = effort == 4;
        int selective = (effort4_selective || refined_effort3) &&
            plane_class == 0 &&
            (fidelity_tools & N148_FIDELITY_FAST_MODE_SEARCH) &&
            (fidelity_tools & N148_FIDELITY_QUALITY_LAMBDA);
        shortlist_mode = choose_mode(source, reconstructed, x0, y0, 8,
                                     neutral, mode_count, causal_right,
                                     plane_class == 0,
                                     shortlist_prediction,
                                     effort4_selective && selective ?
                                         &runner_up : NULL,
                                     selective ? &prediction_score : NULL);
        /* Effort four spends a second full mode trial only when the fast
           predictor leaves more than three quantizer-sized MSE units. The
           refined effort-three profile uses a higher threshold so its
           small quality correction stays in the standard speed class. */
        if (selective) {
            uint64_t threshold = (refined_effort3 ? 640ull : 192ull) *
                (uint64_t) quant->dc_step * (uint64_t) quant->dc_step;
            if (prediction_score <= threshold) {
                runner_up = -1;
            } else if (refined_effort3) {
                shortlist_mode = choose_mode(
                    source, reconstructed, x0, y0, 8, neutral, mode_count,
                    causal_right, plane_class == 0, shortlist_prediction,
                    &runner_up, NULL);
            }
        }
    }
    double best_cost = DBL_MAX;
    uint64_t nearest_reference_distortion = UINT64_MAX;
    for (int mode = 0; mode < mode_count; mode++) {
        if (shortlist_mode >= 0 && mode != shortlist_mode &&
            mode != runner_up) continue;
        uint8_t prediction[64];
        if (shortlist_mode == mode) memcpy(prediction, shortlist_prediction, 64);
        else predict_square(reconstructed, x0, y0, 8, mode, neutral,
                            causal_right, plane_class == 0, prediction);
        short coefficients[64];
        float ideal_levels[64];
        if (quantized_shortlist) {
            memcpy(coefficients, shortlist_coefficients, sizeof(coefficients));
            memcpy(ideal_levels, shortlist_ideal, sizeof(ideal_levels));
        } else if (!quantize8(source, x0, y0, prediction, quant, coefficients,
                              ideal_levels)) {
            restore_valid_block(reconstructed, x0, y0, saved);
            return 0;
        }
        if (effort >= 3) {
            /* The structural profile prices its ordinary spatial SSE with
               the initial frame's contextual run/category rate model. */
            int structural_context = effort == 3 &&
                (plane_class == 0 || n148_fidelity_balanced_reconstruction()) &&
                trellis_policy == N148_TRELLIS_OFF &&
                (fidelity_tools & N148_FIDELITY_STRUCTURAL_LUMA_QUANT);
            int refined = (trellis_policy != N148_TRELLIS_OFF || structural_context) ?
                refine_coefficients_contextually(
                    rate_model, coefficient_plane, block, blocks_x,
                    plane_class, previous_dc_category, ideal_levels,
                    structural_context ? quant->unit_energy : quant->perceptual_energy,
                    0, 64, effort,
                    structural_context ? N148_TRELLIS_LEGACY : trellis_policy,
                    structural_context, coefficients) :
                n148_rdo_refine_coefficients_trusted(
                    ideal_levels, quant->unit_energy,
                    0.85 * quant->unit_energy[0] *
                        BASE_TRELLIS_LAMBDA_SCALE,
                    effort, coefficients, NULL);
            if (!refined) {
                restore_valid_block(reconstructed, x0, y0, saved);
                return 0;
            }
        }
        if (!reconstruct8(coefficients, prediction, quant, reconstructed,
                          x0, y0)) {
            restore_valid_block(reconstructed, x0, y0, saved);
            return 0;
        }
        uint64_t distortion = fidelity_region_error(
            source, reconstructed, x0, y0, 8, plane_class == 0);
        if (mode < N148_DIRECTIONAL_INTRA_MODE_COUNT) {
            if (distortion < nearest_reference_distortion)
                nearest_reference_distortion = distortion;
        } else if (distortion > nearest_reference_distortion) {
            restore_valid_block(reconstructed, x0, y0, saved);
            continue;
        }
        uint8_t candidate_modes[N148_INTRA_MODE_SLOTS_PER_BLOCK];
        for (int part = 0; part < N148_INTRA_MODE_SLOTS_PER_BLOCK; part++)
            candidate_modes[part] = (uint8_t) mode;
        double rate = estimate_coefficient_bits(
            rate_model, coefficient_plane, block, blocks_x, plane_class,
            previous_dc_category, coefficients, 0) +
            estimate_mode_bits(rate_model, plane_class, committed_modes,
                               block, candidate_modes, 1, blocks_x) +
            estimate_partition_bits(rate_model, partition_map, map_index, 0);
        double lambda = fidelity_rdo_lambda(
            quant->dc_step, plane_class == 0);
        double cost = (double) distortion + lambda * rate;
        if (cost < best_cost) {
            best_cost = cost;
            memcpy(candidate->coefficients, coefficients,
                   sizeof(candidate->coefficients));
            memcpy(candidate->modes, candidate_modes,
                   sizeof(candidate->modes));
            candidate->distortion = distortion;
            candidate->proxy_bits = rate;
            copy_block_from_plane(reconstructed, x0, y0,
                                  candidate->pixels);
        }
        restore_valid_block(reconstructed, x0, y0, saved);
    }
    return best_cost < DBL_MAX;
}

/* Evaluate one explicitly selected 8x8 mode. Joint chroma uses this primitive to price
   Cb and Cr together while preserving separate causal reconstruction buffers
   and coefficient contexts for both planes. Mode signaling is deliberately
   excluded from proxy_bits because the pair pays that cost only once. */
static int make_fixed_unsplit_candidate(
    const Plane *source, Plane *reconstructed, int x0, int y0,
    uint8_t neutral, int mode, const IntraQuant8 *quant, int effort,
    int trellis_policy, const IntraRateModel *rate_model,
    const N148CoeffPlane *coefficient_plane, long block, int blocks_x,
    int previous_dc_category, const uint8_t *precomputed_prediction,
    IntraBlockCandidate *candidate) {
    if (!source || !reconstructed || !quant || !coefficient_plane ||
        !candidate || mode < 0 || mode >= N148_DIRECTIONAL_INTRA_MODE_COUNT ||
        effort < 0 || effort > 9 ||
        (trellis_policy != N148_TRELLIS_OFF && !rate_model)) return 0;
    uint8_t saved[64];
    uint8_t prediction[64];
    float ideal_levels[64];
    copy_block_from_plane(reconstructed, x0, y0, saved);
    if (precomputed_prediction)
        memcpy(prediction, precomputed_prediction, sizeof(prediction));
    else
        predict_square(reconstructed, x0, y0, 8, mode, neutral, -1, 0,
                       prediction);
    if (!quantize8(source, x0, y0, prediction, quant,
                   candidate->coefficients, ideal_levels)) {
        restore_valid_block(reconstructed, x0, y0, saved);
        return 0;
    }
    if (effort >= 3) {
        int refined = rate_model && trellis_policy != N148_TRELLIS_OFF ?
            refine_coefficients_contextually(
                rate_model, coefficient_plane, block, blocks_x, 1,
                previous_dc_category, ideal_levels,
                quant->perceptual_energy, 0, 64, effort, trellis_policy, 0,
                candidate->coefficients) :
            n148_rdo_refine_coefficients_trusted(
                ideal_levels, quant->unit_energy,
                0.85 * quant->unit_energy[0] * BASE_TRELLIS_LAMBDA_SCALE,
                effort, candidate->coefficients, NULL);
        if (!refined) {
            restore_valid_block(reconstructed, x0, y0, saved);
            return 0;
        }
    }
    if (!reconstruct8(candidate->coefficients, prediction, quant,
                      reconstructed, x0, y0)) {
        restore_valid_block(reconstructed, x0, y0, saved);
        return 0;
    }
    for (int part = 0; part < N148_INTRA_MODE_SLOTS_PER_BLOCK; part++)
        candidate->modes[part] = (uint8_t) mode;
    candidate->distortion = region_error(
        source, reconstructed, x0, y0, 8);
    candidate->proxy_bits = rate_model ? estimate_coefficient_bits(
        rate_model, coefficient_plane, block, blocks_x, 1,
        previous_dc_category, candidate->coefficients, 0) :
        n148_rdo_estimate_block_bits(candidate->coefficients);
    copy_block_from_plane(reconstructed, x0, y0, candidate->pixels);
    restore_valid_block(reconstructed, x0, y0, saved);
    return 1;
}

/* Approximate the RGB impact of simultaneous Cb/Cr residual error. The
   coefficients come from the established BT.601 inverse matrix and are
   normalized so the two diagonal weights average to one. Keeping the cross
   term matters when both chroma residuals move the reconstructed green
   channel in the same direction. */
static double joint_chroma_distortion(
    const Plane *cb, const Plane *cr,
    const IntraBlockCandidate candidate[2], int x0, int y0) {
    int max_x = cb->width - x0;
    int max_y = cb->height - y0;
    if (max_x > 8) max_x = 8;
    if (max_y > 8) max_y = 8;
    double error = 0.0;
    for (int row = 0; row < max_y; row++) {
        for (int column = 0; column < max_x; column++) {
            int offset = row * 8 + column;
            int cb_error = sample_clamped(cb, x0 + column, y0 + row) -
                candidate[0].pixels[offset];
            int cr_error = sample_clamped(cr, x0 + column, y0 + row) -
                candidate[1].pixels[offset];
            error += 1.1364 * cb_error * cb_error +
                0.8636 * cr_error * cr_error +
                0.1715 * cb_error * cr_error;
        }
    }
    return error;
}

/* Native 4x4 predictor ranking by quantized spatial error and native syntax rate.
   The coefficient DP still runs only on the selected predictor. */
static double cached_coefficient4_bits(
    const IntraRateModel *rate_model, uint64_t neighbor_mask,
    int previous_dc_category, const short values[16]) {
    const short *unit = values;
    const int plane_class = 0, length = 16;
    int category = coefficient_category(unit[0]);
    int model = rate_dc_model(plane_class, previous_dc_category);
    double bits = rate_model->bits[model][category] + category;
    int next_position = 1;
    int previous_ac_category = 0;
    uint64_t active = coefficient_unit_mask(unit, length) & ~1ull;
    while (active) {
#if defined(__GNUC__) || defined(__clang__)
        int position = __builtin_ctzll(active);
#else
        int position = 0;
        uint64_t probe = active;
        while (!(probe & 1u)) { position++; probe >>= 1; }
#endif
        active &= active - 1;
        int run = position - next_position;
        while (run > 15) {
            model = (INTRA_RATE_DC_MODELS + rate_band(next_position) *
                INTRA_RATE_ACTIVITY_BUCKETS +
                (previous_ac_category >= 3 || ((neighbor_mask >> next_position) & 1u)));
            bits += rate_model->bits[model][0xf0];
            next_position += 16;
            previous_ac_category = 0;
            run -= 16;
        }
        category = coefficient_category(unit[position]);
        model = (INTRA_RATE_DC_MODELS + rate_band(next_position) *
                INTRA_RATE_ACTIVITY_BUCKETS +
                (previous_ac_category >= 3 || ((neighbor_mask >> next_position) & 1u)));
        bits += rate_model->bits[model][(run << 4) | category] + category;
        next_position = position + 1;
        previous_ac_category = category;
    }
    if (next_position < length) {
        model = (INTRA_RATE_DC_MODELS + rate_band(next_position) *
                INTRA_RATE_ACTIVITY_BUCKETS +
                (previous_ac_category >= 3 || ((neighbor_mask >> next_position) & 1u)));
        bits += rate_model->bits[model][0];
    }
    return bits;
}

static int choose_quantized_mode4(
    const Plane *source, const Plane *reconstructed, int x0, int y0,
    uint8_t neutral, int mode_count, int causal_right, const IntraQuant4 *quant,
    const IntraRateModel *rate_model, const N148CoeffPlane *coefficient_plane,
    const uint8_t *committed_modes, long block, int blocks_x, int previous_dc_category,
    int part, const IntraBlockCandidate *committed, uint8_t prediction[16],
    short best_coefficients[16], float best_ideal[16]) {
    N148PreparedSquare references;
    prepare_square_references(reconstructed, x0, y0, 4, neutral,
                              causal_right, fidelity_tools, 0, &references);
    if (mode_count > 4) mode_count = 4;
    uint8_t extra_prediction[6][16];
    int first_extra = -1, second_extra = -1;
    uint64_t first_sse = UINT64_MAX, second_sse = UINT64_MAX;
    for (int mode = 4; mode < mode_count; mode++) {
        predict_square_prepared(&references, 4, mode, neutral, extra_prediction[mode-4]);
        uint64_t score = prediction_sse(source, x0, y0, 4,
                                       extra_prediction[mode-4], second_sse);
        if (score < first_sse) {
            second_sse = first_sse; second_extra = first_extra;
            first_sse = score; first_extra = mode;
        } else if (score < second_sse) {
            second_sse = score; second_extra = mode;
        }
    }
    short values[64];
    uint8_t modes[N148_INTRA_MODE_SLOTS_PER_BLOCK];
    uint64_t neighbor_mask = coefficient_neighbor_mask(coefficient_plane, block, blocks_x) >> (part*16);
    memcpy(values, committed->coefficients, sizeof(values));
    memcpy(modes, committed->modes, sizeof(modes));
    double best_cost = DBL_MAX;
    int best_mode = -1;
    double lambda = fidelity_rdo_lambda(quant->dc_step, 1);
    for (int mode = 0; mode < mode_count; mode++) {
        if (mode >= 4 && mode != first_extra && mode != second_extra) continue;
        modes[part] = (uint8_t)mode;
        double mode_rate = estimate_mode_bits_from(rate_model, 0, committed_modes,
                                                   block, modes, part, part+1, blocks_x, 0.0);
        if (lambda * mode_rate >= best_cost) continue;
        uint8_t trial[16];
        short coefficients[16];
        float ideal[16];
        if (mode >= 4) memcpy(trial, extra_prediction[mode-4], 16);
        else predict_square_prepared(&references, 4, mode, neutral, trial);
        if (!quantize4(source, x0, y0, trial, quant, coefficients, ideal)) return -1;
        double distortion = quantized_error(ideal, coefficients,
            quant->unit_energy, 16, lambda * mode_rate, best_cost);
        if (distortion + lambda * mode_rate >= best_cost) continue;
        memcpy(values + part*16, coefficients, sizeof(coefficients));
        double rate = cached_coefficient4_bits(rate_model, neighbor_mask, previous_dc_category, coefficients) + mode_rate;
        double cost = distortion + lambda * rate;
        if (cost < best_cost) {
            best_cost = cost;
            best_mode = mode;
            memcpy(prediction, trial, 16);
            memcpy(best_coefficients, coefficients, sizeof(coefficients));
            memcpy(best_ideal, ideal, sizeof(ideal));
        }
    }
    return best_mode;
}


static int make_split_rdo_candidate(
    const Plane *source, Plane *reconstructed, int x0, int y0,
    uint8_t neutral, int mode_count, int causal_right,
    const IntraQuant4 *quant, int effort,
    int trellis_policy,
    const IntraRateModel *rate_model, const N148CoeffPlane *coefficient_plane,
    const uint8_t *committed_modes, long block, int blocks_x,
    int plane_class, int previous_dc_category,
    const N148PartitionMap *partition_map, size_t map_index,
    double competing_cost, double decision_lambda,
    IntraBlockCandidate *candidate) {
    uint8_t original[64], committed[64];
    copy_block_from_plane(reconstructed, x0, y0, original);
    memcpy(committed, original, sizeof(committed));
    memset(candidate->coefficients, 0, sizeof(candidate->coefficients));
    memset(candidate->modes, 0, sizeof(candidate->modes));
    /* Later 4x4 trials leave the already committed regions unchanged. */
    uint64_t committed_distortion = 0;
    double committed_coefficient_bits = 0.0;
    double committed_mode_bits = 0.0;
    uint64_t committed_sse = 0;
    int committed_dc_category = previous_dc_category;
    double partition_bits = estimate_partition_bits(
        rate_model, partition_map, map_index, 1);
    double lambda = fidelity_rdo_lambda(
        quant->dc_step, plane_class == 0);
    for (int part = 0; part < 4; part++) {
        int part_x = x0 + (part & 1) * 4;
        int part_y = y0 + (part >> 1) * 4;
        int shortlist_mode = -1;
        uint8_t shortlist_prediction[16];
        short shortlist_coefficients[16];
        float shortlist_ideal[16];
        int quantized_shortlist = effort == 3 && plane_class == 0 &&
            n148_fidelity_detail_reconstruction();
        if (quantized_shortlist) {
            shortlist_mode = choose_quantized_mode4(
                source, reconstructed, part_x, part_y, neutral, mode_count,
                causal_right, quant, rate_model, coefficient_plane,
                committed_modes, block, blocks_x, committed_dc_category,
                part, candidate, shortlist_prediction, shortlist_coefficients, shortlist_ideal);
            if (shortlist_mode < 0) {
                restore_valid_block(reconstructed, x0, y0, original);
                return 0;
            }
        } else if (effort < 5) {
            shortlist_mode = choose_mode(
                source, reconstructed, part_x, part_y, 4, neutral,
                mode_count, causal_right, plane_class == 0,
                shortlist_prediction, NULL, NULL);
        }
        double best_cost = DBL_MAX;
        uint64_t best_part_distortion = 0;
        double best_coefficient_bits = 0.0;
        double best_mode_bits = 0.0;
        int best_dc_category = 0;
        short best_coefficients[16];
        uint8_t best_pixels[64];
        int best_mode = -1;
        for (int mode = 0; mode < mode_count; mode++) {
            if (shortlist_mode >= 0 && mode != shortlist_mode) continue;
            /* Effort 3 evaluates exactly the shortlisted mode. Its trial is
               therefore the committed reconstruction and can stay in place.
               Higher efforts still restore the full block between modes. */
            if (shortlist_mode < 0)
                restore_valid_block(reconstructed, x0, y0, committed);
            uint8_t prediction[16];
            if (shortlist_mode == mode) memcpy(prediction, shortlist_prediction, 16);
            else predict_square(reconstructed, part_x, part_y, 4, mode,
                                neutral, causal_right, plane_class == 0,
                                prediction);
            short coefficients[16];
            float ideal_levels[16];
            if (quantized_shortlist) {
                memcpy(coefficients, shortlist_coefficients, sizeof(coefficients));
                memcpy(ideal_levels, shortlist_ideal, sizeof(ideal_levels));
            } else if (!quantize4(source, part_x, part_y, prediction, quant,
                           coefficients, ideal_levels)) {
                restore_valid_block(reconstructed, x0, y0, original);
                return 0;
            }
            short trial_storage[64];
            short *trial_coefficients;
            if (shortlist_mode >= 0) {
                memcpy(candidate->coefficients + part * 16, coefficients,
                       sizeof(coefficients));
                trial_coefficients = candidate->coefficients;
            } else {
                memcpy(trial_storage, candidate->coefficients,
                       sizeof(trial_storage));
                memcpy(trial_storage + part * 16, coefficients,
                       sizeof(coefficients));
                trial_coefficients = trial_storage;
            }
            int structural_context = effort == 3 &&
                n148_fidelity_detail_reconstruction() &&
                trellis_policy == N148_TRELLIS_OFF;
            if (trellis_policy != N148_TRELLIS_OFF || structural_context) {
                int unit_previous_dc = part == 0 ? previous_dc_category :
                    coefficient_category(
                        candidate->coefficients[(part - 1) * 16]);
                if (!refine_coefficients_contextually(
                        rate_model, coefficient_plane, block, blocks_x,
                        plane_class, unit_previous_dc, ideal_levels,
                        structural_context ? quant->unit_energy : quant->perceptual_energy,
                        part * 16, 16, effort,
                        structural_context ? N148_TRELLIS_LEGACY : trellis_policy,
                        structural_context,
                        trial_coefficients)) {
                    restore_valid_block(reconstructed, x0, y0, original);
                    return 0;
                }
                memcpy(coefficients, trial_coefficients + part * 16,
                       sizeof(coefficients));
            }
            if (!reconstruct4(coefficients, prediction, quant, reconstructed,
                              part_x, part_y)) {
                restore_valid_block(reconstructed, x0, y0, original);
                return 0;
            }
            uint8_t trial_mode_storage[N148_INTRA_MODE_SLOTS_PER_BLOCK];
            uint8_t *trial_modes;
            if (shortlist_mode >= 0) {
                candidate->modes[part] = (uint8_t) mode;
                trial_modes = candidate->modes;
            } else {
                memcpy(trial_mode_storage, candidate->modes,
                       sizeof(trial_mode_storage));
                trial_mode_storage[part] = (uint8_t) mode;
                trial_modes = trial_mode_storage;
            }
            uint64_t part_distortion = fidelity_region_error(
                source, reconstructed, part_x, part_y, 4,
                plane_class == 0);
            uint64_t distortion = committed_distortion + part_distortion;
            double coefficient_bits = committed_coefficient_bits;
            int dc_category = committed_dc_category;
            double selected_coefficient_bits = 0.0;
            int selected_dc_category = 0;
            /* A shortlisted search has exactly one mode at this part.
               Suffix units cannot affect that choice; their rates are
               evaluated after the next part is committed. */
            int last_unit = shortlist_mode >= 0 ? part + 1 : 4;
            for (int unit = part; unit < last_unit; unit++) {
                coefficient_bits += estimate_coefficient_unit_bits(
                    rate_model, coefficient_plane, block, blocks_x,
                    plane_class, dc_category, trial_coefficients,
                    unit * 16, 16, &dc_category);
                if (unit == part) {
                    selected_coefficient_bits = coefficient_bits;
                    selected_dc_category = dc_category;
                }
            }
            double mode_bits = estimate_mode_bits_from(
                rate_model, plane_class, committed_modes, block,
                trial_modes, part, part + 1, blocks_x,
                committed_mode_bits);
            double rate = coefficient_bits + mode_bits + partition_bits;
            double cost = (double) distortion + lambda * rate;
            if (cost < best_cost) {
                best_cost = cost;
                best_part_distortion = part_distortion;
                best_coefficient_bits = selected_coefficient_bits;
                best_mode_bits = mode_bits;
                best_dc_category = selected_dc_category;
                best_mode = mode;
                if (shortlist_mode < 0)
                    memcpy(best_coefficients, coefficients,
                           sizeof(best_coefficients));
                if (shortlist_mode < 0)
                    copy_block_from_plane(reconstructed, x0, y0, best_pixels);
            }
        }
        if (best_mode < 0) {
            restore_valid_block(reconstructed, x0, y0, original);
            return 0;
        }
        candidate->modes[part] = (uint8_t) best_mode;
        if (shortlist_mode < 0)
            memcpy(candidate->coefficients + part * 16, best_coefficients,
                   sizeof(best_coefficients));
        if (shortlist_mode < 0) {
            memcpy(committed, best_pixels, sizeof(committed));
            restore_valid_block(reconstructed, x0, y0, committed);
        }
        committed_distortion += best_part_distortion;
        committed_coefficient_bits = best_coefficient_bits;
        committed_mode_bits = best_mode_bits;
        committed_dc_category = best_dc_category;
        if (competing_cost < DBL_MAX && part < 3) {
            /* The structural penalty and all remaining SSE/rate are
               nonnegative. Completed 4x4 pixels cannot change in later
               trials, so this is a lower bound on the final 8x8 cost. */
            committed_sse += plane_class == 0 &&
                (fidelity_tools & N148_FIDELITY_STRUCTURAL_RDO) ?
                region_error(source, reconstructed, part_x, part_y, 4) :
                best_part_distortion;
            double lower_bound = (double) committed_sse +
                decision_lambda * (partition_bits +
                    committed_coefficient_bits + committed_mode_bits);
            if (lower_bound > competing_cost + 1.0) {
                candidate->proxy_bits = DBL_MAX;
                restore_valid_block(reconstructed, x0, y0, original);
                return 1;
            }
        }
    }
    candidate->distortion = plane_class == 0 &&
        (fidelity_tools & N148_FIDELITY_STRUCTURAL_RDO) ?
        fidelity_region_error(source, reconstructed, x0, y0, 8, 1) :
        committed_distortion;
    candidate->proxy_bits = estimate_coefficient_bits(
        rate_model, coefficient_plane, block, blocks_x, plane_class,
        previous_dc_category, candidate->coefficients, 1) +
        estimate_mode_bits(rate_model, plane_class, committed_modes, block,
                           candidate->modes, 4, blocks_x) +
        estimate_partition_bits(rate_model, partition_map, map_index, 1);
    copy_block_from_plane(reconstructed, x0, y0, candidate->pixels);
    restore_valid_block(reconstructed, x0, y0, original);
    return 1;
}

static int make_unsplit_candidate(
    const Plane *source, Plane *reconstructed, int x0, int y0,
    uint8_t neutral, int mode_count, const IntraQuant8 *quant, int effort,
    int apply_fidelity,
    IntraBlockCandidate *candidate) {
    uint8_t prediction[64];
    float ideal_levels[64];
    int mode = choose_mode(source, reconstructed, x0, y0, 8, neutral,
                                mode_count, -1, apply_fidelity, prediction,
                                NULL, NULL);
    if (!quantize8(source, x0, y0, prediction, quant,
                   candidate->coefficients, ideal_levels)) return 0;
    if (effort >= 3 && !n148_rdo_refine_coefficients_trusted(
            ideal_levels, quant->unit_energy,
            0.85 * quant->unit_energy[0] * BASE_TRELLIS_LAMBDA_SCALE,
            effort, candidate->coefficients, NULL)) return 0;
    for (int slot = 0; slot < N148_INTRA_MODE_SLOTS_PER_BLOCK; slot++)
        candidate->modes[slot] = (uint8_t) mode;
    uint8_t saved[64];
    copy_block_from_plane(reconstructed, x0, y0, saved);
    if (!reconstruct8(candidate->coefficients, prediction, quant,
                      reconstructed, x0, y0)) return 0;
    candidate->distortion = block_error(source, reconstructed, x0, y0);
    candidate->proxy_bits =
        n148_rdo_estimate_block_bits(candidate->coefficients) + 3.0;
    copy_block_from_plane(reconstructed, x0, y0, candidate->pixels);
    restore_valid_block(reconstructed, x0, y0, saved);
    return 1;
}

static int make_split_candidate(
    const Plane *source, Plane *reconstructed, int x0, int y0,
    uint8_t neutral, int mode_count, const IntraQuant4 *quant,
    int apply_fidelity,
    IntraBlockCandidate *candidate) {
    uint8_t saved[64];
    copy_block_from_plane(reconstructed, x0, y0, saved);
    memset(candidate->coefficients, 0, sizeof(candidate->coefficients));
    candidate->proxy_bits = 1.0;
    for (int part = 0; part < 4; part++) {
        int part_x = x0 + (part & 1) * 4;
        int part_y = y0 + (part >> 1) * 4;
        uint8_t prediction[16];
        int mode = choose_mode(source, reconstructed, part_x, part_y, 4,
                                    neutral, mode_count, -1,
                                    apply_fidelity, prediction, NULL, NULL);
        candidate->modes[part] = (uint8_t) mode;
        if (!quantize4(source, part_x, part_y, prediction, quant,
                       candidate->coefficients + part * 16, NULL) ||
            !reconstruct4(candidate->coefficients + part * 16, prediction,
                          quant, reconstructed, part_x, part_y)) {
            restore_valid_block(reconstructed, x0, y0, saved);
            return 0;
        }
        short packed[64] = {0};
        memcpy(packed, candidate->coefficients + part * 16,
               16 * sizeof(*packed));
        candidate->proxy_bits += n148_rdo_estimate_block_bits(packed) + 3.0;
    }
    candidate->distortion = block_error(source, reconstructed, x0, y0);
    copy_block_from_plane(reconstructed, x0, y0, candidate->pixels);
    restore_valid_block(reconstructed, x0, y0, saved);
    return 1;
}

static int choose_split(const IntraBlockCandidate *unsplit,
                        const IntraBlockCandidate *split, int quality) {
    /* Directional intra deliberately uses a coarse rate proxy. Contextual RDO replaces this
       gate and mode selection with contextual rate-distortion costs. */
    double quantizer = quality < 50 ? (double)(101 - quality) :
        (double)(202 - 2 * quality);
    double lambda = 0.14 * quantizer * quantizer;
    double unsplit_cost = (double) unsplit->distortion +
        lambda * unsplit->proxy_bits;
    double split_cost = (double) split->distortion +
        lambda * split->proxy_bits;
    return split_cost < unsplit_cost;
}

static int filter_reconstructed_block(
    Plane *plane, int x0, int y0, int quality, int plane_index,
    int loop_filter_policy, uint8_t segment,
    const N148SegmentationMap *segmentation_map) {
    if (loop_filter_policy == N148_LOOP_FILTER_OFF) return 1;
    uint8_t filter_level = 1;
    if (loop_filter_policy == N148_LOOP_FILTER_LEGACY &&
        plane_index == 0 && segmentation_map &&
        segmentation_map->adaptive_filter &&
        !n148_segmentation_filter_level(
            segmentation_map, segment, &filter_level)) return 0;
    if (loop_filter_policy == N148_LOOP_FILTER_QUANT_ADAPTIVE_LUMA)
        return n148_loop_filter_quant_luma_block(
            plane, x0, y0, 8, quality, plane_index, NULL);
    return n148_loop_filter_block(
        plane, x0, y0, 8, quality, plane_index, filter_level, NULL);
}

static int filter_reconstructed_macro(
    Plane *plane, int x0, int y0, int quality, int loop_filter_policy,
    uint8_t segment, const N148SegmentationMap *segmentation_map) {
    if (loop_filter_policy == N148_LOOP_FILTER_OFF) return 1;
    uint8_t filter_level = 1;
    if (loop_filter_policy == N148_LOOP_FILTER_LEGACY && segmentation_map &&
        segmentation_map->adaptive_filter &&
        !n148_segmentation_filter_level(
            segmentation_map, segment, &filter_level)) return 0;
    if (loop_filter_policy == N148_LOOP_FILTER_QUANT_ADAPTIVE_LUMA)
        return n148_loop_filter_quant_luma_block(
            plane, x0, y0, 16, quality, 0, NULL);
    return n148_loop_filter_block(
        plane, x0, y0, 16, quality, 0, filter_level, NULL);
}

static int filter_reconstructed_super(
    Plane *plane, int x0, int y0, int quality, int loop_filter_policy,
    uint8_t segment, const N148SegmentationMap *segmentation_map) {
    if (loop_filter_policy == N148_LOOP_FILTER_OFF) return 1;
    uint8_t filter_level = 1;
    if (loop_filter_policy == N148_LOOP_FILTER_LEGACY && segmentation_map &&
        segmentation_map->adaptive_filter &&
        !n148_segmentation_filter_level(
            segmentation_map, segment, &filter_level)) return 0;
    if (loop_filter_policy == N148_LOOP_FILTER_QUANT_ADAPTIVE_LUMA)
        return n148_loop_filter_quant_luma_block(
            plane, x0, y0, 32, quality, 0, NULL);
    return n148_loop_filter_block(
        plane, x0, y0, 32, quality, 0, filter_level, NULL);
}

static int prepare_reconstruction_filters(
    int quality, int plane_index, int policy,
    const N148SegmentationMap *segmentation_map,
    N148LoopFilterPrepared filters[N148_SEGMENT_COUNT]) {
    if (policy == N148_LOOP_FILTER_OFF) return 1;
    int levels = segmentation_map ? N148_SEGMENT_COUNT : 1;
    for (int segment = 0; segment < levels; segment++) {
        uint8_t adaptive_level = 1;
        if (policy == N148_LOOP_FILTER_LEGACY && plane_index == 0 &&
            segmentation_map && segmentation_map->adaptive_filter &&
            !n148_segmentation_filter_level(
                segmentation_map, (uint8_t) segment, &adaptive_level))
            return 0;
        if (!n148_loop_filter_prepare(
                quality, plane_index, adaptive_level,
                policy == N148_LOOP_FILTER_QUANT_ADAPTIVE_LUMA,
                &filters[segment])) return 0;
    }
    return 1;
}

static int filter_reconstructed_prepared(
    Plane *plane, int x0, int y0, int size, int policy, uint8_t segment,
    const N148LoopFilterPrepared filters[N148_SEGMENT_COUNT]) {
    if (policy == N148_LOOP_FILTER_OFF) return 1;
    return n148_loop_filter_block_prepared(
        plane, x0, y0, size, &filters[segment], NULL);
}

static void accumulate_luma_coefficient(int transform, int mode,
                                        int position, double value) {
    N148LumaStatistics *stats = luma_stats_sink;
    stats->sum[transform][mode][position] += value;
    stats->sum_squares[transform][mode][position] += value * value;
    stats->sum_absolute[transform][mode][position] += fabs(value);
}

/* Replay the selected block against the pre-block causal reconstruction.
   DCT4 needs replay because each sub-block predicts from the earlier selected
   sub-blocks. The caller subsequently installs the already saved candidate,
   so this diagnostic path cannot perturb the normative reconstruction. */
static int collect_luma_block_statistics(
    const Plane *source, Plane *reconstructed, int x0, int y0,
    int use_split, const IntraBlockCandidate *chosen,
    const IntraQuant4 *quant4) {
    if (!luma_stats_sink) return 1;
    if (!source || !reconstructed || !chosen || !quant4) return 0;
    if (!use_split) {
        int mode = chosen->modes[0];
        int base_mode = n148_intra_base_mode(mode);
        uint8_t prediction[64];
        float block[64], transformed[64];
        predict_square(reconstructed, x0, y0, 8, mode, 128, -1, 1,
                       prediction);
        for (int row = 0; row < 8; row++) {
            for (int column = 0; column < 8; column++) {
                int position = row * 8 + column;
                block[position] = (float)(sample_clamped(
                    source, x0 + column, y0 + row) -
                    prediction[position] + 128);
            }
        }
        dct_block_fast(block, transformed);
        luma_stats_sink->block_count[N148_LUMA_STATS_DCT8][base_mode]++;
        for (int natural = 0; natural < 64; natural++) {
            double value = transformed[natural] /
                aan_scale_factor(natural / 8, natural % 8);
            accumulate_luma_coefficient(
                N148_LUMA_STATS_DCT8, base_mode, natural, value);
        }
        return 1;
    }

    for (int part = 0; part < 4; part++) {
        int mode = chosen->modes[part];
        int base_mode = n148_intra_base_mode(mode);
        int part_x = x0 + (part & 1) * 4;
        int part_y = y0 + (part >> 1) * 4;
        uint8_t prediction[16];
        int32_t residual[16], transformed[16];
        predict_square(reconstructed, part_x, part_y, 4, mode, 128, -1, 1,
                       prediction);
        for (int row = 0; row < 4; row++) {
            for (int column = 0; column < 4; column++) {
                int position = row * 4 + column;
                residual[position] = sample_clamped(
                    source, part_x + column, part_y + row) -
                    prediction[position];
            }
        }
        if (!n148_variable_forward(residual, 4, transformed)) return 0;
        luma_stats_sink->block_count[N148_LUMA_STATS_DCT4][base_mode]++;
        for (int natural = 0; natural < 16; natural++)
            accumulate_luma_coefficient(
                N148_LUMA_STATS_DCT4, base_mode, natural,
                (double) transformed[natural]);
        if (!reconstruct4(chosen->coefficients + part * 16, prediction,
                          quant4, reconstructed, part_x, part_y)) return 0;
    }
    return 1;
}


static int quantize_plane(
    const Plane *source, int quality, int plane_index, int extended_modes,
    int split_4x4, int effort, int trellis_policy, int loop_filter,
    int calibrated_quant, int subsample_x, int subsample_y,
    const IntraRateModel *rate_model,
    N148PartitionMap *partition_map, N148CoeffPlane *coefficients,
    uint8_t *modes, const N148SegmentationMap *segmentation_map, Plane *capture) {
    size_t count;
    if (!source || !source->data || !partition_map || !modes ||
        plane_index < 0 || plane_index > 2 || quality < 1 || quality > 100 ||
        (calibrated_quant != 0 && calibrated_quant != 1) ||
        (extended_modes != 0 && extended_modes != 1) ||
        (split_4x4 != 0 && split_4x4 != 1) ||
        trellis_policy < N148_TRELLIS_OFF ||
        trellis_policy > N148_TRELLIS_PERCEPTUAL_LUMA ||
        (subsample_x != 0 && subsample_x != 1) ||
        (subsample_y != 0 && subsample_y != 1) ||
        effort < 0 || effort > 9 ||
        loop_filter < N148_LOOP_FILTER_OFF ||
        loop_filter > N148_LOOP_FILTER_QUANT_ADAPTIVE_LUMA ||
        (segmentation_map &&
         !n148_segmentation_map_validate(segmentation_map)) ||
        !checked_block_count(source->width, source->height, &count) ||
        !allocate_coefficients(count, coefficients)) return 0;
    int blocks_x = source->width / 8 + (source->width % 8 != 0);
    int blocks_y = source->height / 8 + (source->height % 8 != 0);
    if (partition_map->blocks_x[plane_index] != blocks_x ||
        partition_map->blocks_y[plane_index] != blocks_y) {
        n148_free_coeff_plane(coefficients);
        return 0;
    }
    Plane reconstructed = create_plane(source->width, source->height);
    if (!reconstructed.data) {
        n148_free_coeff_plane(coefficients);
        return 0;
    }
    IntraQuant8 quant8[N148_SEGMENT_COUNT];
    IntraQuant4 quant4[N148_SEGMENT_COUNT];
    const int (*base)[8] = plane_index ?
        (calibrated_quant ? FORMAT_4_CHROMA_QUANT_BASE : Q_CHROMA_BASE) :
        luma_quant_base(calibrated_quant);
    if (!build_segment_quantizers(base, quality, plane_index,
                                  segmentation_map, quant8, quant4)) {
        free_plane(&reconstructed);
        n148_free_coeff_plane(coefficients);
        return 0;
    }
    uint8_t neutral = 128;
    int unsplit_mode_count = plane_index == 0 && rate_model ?
        luma_mode_count(extended_modes, 8, effort) :
        (extended_modes ? N148_DIRECTIONAL_INTRA_MODE_COUNT : 4);
    int split_mode_count = extended_modes ? N148_DIRECTIONAL_INTRA_MODE_COUNT : 4;
    int can_split = split_4x4 && plane_index == 0;
    int success = 1;
    int previous_dc_category = 0;
    for (int block_y = 0; block_y < blocks_y && success; block_y++) {
        for (int block_x = 0; block_x < blocks_x; block_x++) {
            long block = (long) block_y * blocks_x + block_x;
            int x0 = block_x * 8;
            int y0 = block_y * 8;
            uint8_t segment = 0;
            if (segmentation_map && !segmentation_level_prevalidated(
                    segmentation_map, block_x, block_y,
                    subsample_x, subsample_y, &segment)) {
                success = 0;
                break;
            }
            int quant_level = plane_index == 0 ? segment : 0;
            const IntraQuant8 *block_quant8 = &quant8[quant_level];
            const IntraQuant4 *block_quant4 = &quant4[quant_level];
            IntraBlockCandidate unsplit, split;
            memset(&unsplit, 0, sizeof(unsplit));
            memset(&split, 0, sizeof(split));
            size_t map_index = partition_map->plane_offsets[plane_index] +
                (size_t) block;
            int candidate_ok = rate_model ? make_unsplit_rdo_candidate(
                source, &reconstructed, x0, y0, neutral,
                unsplit_mode_count, -1, block_quant8,
                effort, trellis_policy, rate_model, coefficients, modes,
                block, blocks_x,
                plane_index == 0 ? 0 : 1, previous_dc_category,
                partition_map, map_index, &unsplit) :
                make_unsplit_candidate(source, &reconstructed, x0, y0,
                                       neutral, unsplit_mode_count,
                                       block_quant8,
                                       effort, plane_index == 0,
                                       &unsplit);
            if (!candidate_ok) {
                success = 0;
                break;
            }
            int use_split = 0;
            if (can_split) {
                candidate_ok = rate_model ? make_split_rdo_candidate(
                    source, &reconstructed, x0, y0, neutral,
                    split_mode_count, -1, block_quant4, effort,
                    trellis_policy,
                    rate_model, coefficients, modes, block,
                    blocks_x, plane_index == 0 ? 0 : 1,
                    previous_dc_category, partition_map, map_index,
                    DBL_MAX, 0.0, &split) :
                    make_split_candidate(source, &reconstructed, x0, y0,
                                         neutral, split_mode_count,
                                         block_quant4,
                                         plane_index == 0,
                                         &split);
                if (!candidate_ok) {
                    success = 0;
                    break;
                }
                if (rate_model) {
                    double lambda = fidelity_rdo_lambda(
                        block_quant8->dc_step, plane_index == 0);
                    use_split = (double) split.distortion +
                        lambda * split.proxy_bits <
                        (double) unsplit.distortion +
                        lambda * unsplit.proxy_bits;
                } else {
                    use_split = choose_split(&unsplit, &split, quality);
                }
            }
            const IntraBlockCandidate *chosen = use_split ? &split : &unsplit;
            if (plane_index == 0 && rate_model && luma_stats_sink &&
                !collect_luma_block_statistics(
                    source, &reconstructed, x0, y0, use_split, chosen,
                    block_quant4)) {
                success = 0;
                break;
            }
            memcpy(coefficients->coefficients + block * 64,
                   chosen->coefficients, sizeof(chosen->coefficients));
            memcpy(modes + block * N148_INTRA_MODE_SLOTS_PER_BLOCK,
                   chosen->modes, sizeof(chosen->modes));
            coefficients->nonzero_masks[block] =
                coefficient_mask(chosen->coefficients);
            restore_valid_block(&reconstructed, x0, y0, chosen->pixels);
            partition_map->split[map_index] = (uint8_t) use_split;
            previous_dc_category =
                coefficient_category(chosen->coefficients[
                    use_split ? 3 * 16 : 0]);
            if (!filter_reconstructed_block(
                    &reconstructed, x0, y0, quality, plane_index,
                    loop_filter, segment, segmentation_map)) {
                success = 0;
                break;
            }
        }
    }
    if (success && capture) {
        *capture = reconstructed;
        reconstructed = (Plane){0};
    }
    free_plane(&reconstructed);
    if (!success) n148_free_coeff_plane(coefficients);
    return success;
}

static double estimate_transform_bits(
    const IntraRateModel *rate_model, const N148TransformMap *transform_map,
    size_t map_index, uint8_t strategy) {
    uint8_t prediction = n148_transform_map_predict(
        transform_map, map_index);
    int symbol = (strategy + N148_TRANSFORM_STRATEGY_COUNT - prediction) %
        N148_TRANSFORM_STRATEGY_COUNT;
    return rate_model->bits[INTRA_RATE_TRANSFORM_MODEL][symbol];
}

static void clear_macro_syntax(
    int first_block_x, int first_block_y, int blocks_x, int blocks_y,
    N148CoeffPlane *coefficients, uint8_t *modes,
    N148PartitionMap *partition_map) {
    for (int cell_y = 0; cell_y < 2; cell_y++) {
        int block_y = first_block_y + cell_y;
        if (block_y >= blocks_y) continue;
        for (int cell_x = 0; cell_x < 2; cell_x++) {
            int block_x = first_block_x + cell_x;
            if (block_x >= blocks_x) continue;
            long block = (long) block_y * blocks_x + block_x;
            memset(coefficients->coefficients + block * 64, 0,
                   64 * sizeof(*coefficients->coefficients));
            coefficients->nonzero_masks[block] = 0;
            memset(modes + block * N148_INTRA_MODE_SLOTS_PER_BLOCK, 0,
                   N148_INTRA_MODE_SLOTS_PER_BLOCK);
            partition_map->split[block] = 0;
        }
    }
}

static void install_macro_candidate(
    const IntraMacroCandidate *candidate,
    int first_block_x, int first_block_y, int blocks_x, int blocks_y,
    N148CoeffPlane *coefficients, uint8_t *modes,
    N148PartitionMap *partition_map, Plane *reconstructed) {
    for (int cell_y = 0; cell_y < 2; cell_y++) {
        int block_y = first_block_y + cell_y;
        if (block_y >= blocks_y) continue;
        for (int cell_x = 0; cell_x < 2; cell_x++) {
            int block_x = first_block_x + cell_x;
            if (block_x >= blocks_x) continue;
            int cell = cell_y * 2 + cell_x;
            long block = (long) block_y * blocks_x + block_x;
            memcpy(coefficients->coefficients + block * 64,
                   candidate->coefficients[cell],
                   sizeof(candidate->coefficients[cell]));
            coefficients->nonzero_masks[block] =
                coefficient_mask(candidate->coefficients[cell]);
            memcpy(modes + block * N148_INTRA_MODE_SLOTS_PER_BLOCK,
                   candidate->modes[cell], sizeof(candidate->modes[cell]));
            partition_map->split[block] = candidate->splits[cell];
        }
    }
    restore_macro_snapshot(reconstructed, &candidate->reconstruction);
}

static void clear_super_syntax(
    int first_block_x, int first_block_y, int blocks_x, int blocks_y,
    N148CoeffPlane *coefficients, uint8_t *modes,
    N148PartitionMap *partition_map) {
    for (int cell_y = 0; cell_y < 4; cell_y++) {
        int block_y = first_block_y + cell_y;
        if (block_y >= blocks_y) continue;
        for (int cell_x = 0; cell_x < 4; cell_x++) {
            int block_x = first_block_x + cell_x;
            if (block_x >= blocks_x) continue;
            long block = (long) block_y * blocks_x + block_x;
            memset(coefficients->coefficients + block * 64, 0,
                   64 * sizeof(*coefficients->coefficients));
            coefficients->nonzero_masks[block] = 0;
            memset(modes + block * N148_INTRA_MODE_SLOTS_PER_BLOCK, 0,
                   N148_INTRA_MODE_SLOTS_PER_BLOCK);
            partition_map->split[block] = 0;
        }
    }
}

static void install_super_candidate(
    const IntraSuperCandidate *candidate, int first_macro_x, int first_macro_y,
    int blocks_x, N148CoeffPlane *coefficients, uint8_t *modes,
    N148PartitionMap *partition_map, N148TransformMap *transform_map,
    Plane *reconstructed) {
    int first_block_x = first_macro_x * 2;
    int first_block_y = first_macro_y * 2;
    for (int cell = 0; cell < 16; cell++) {
        int block_x = first_block_x + (cell & 3);
        int block_y = first_block_y + (cell >> 2);
        long block = (long) block_y * blocks_x + block_x;
        memcpy(coefficients->coefficients + block * 64,
               candidate->coefficients[cell],
               sizeof(candidate->coefficients[cell]));
        coefficients->nonzero_masks[block] =
            coefficient_mask(candidate->coefficients[cell]);
        memcpy(modes + block * N148_INTRA_MODE_SLOTS_PER_BLOCK,
               candidate->modes[cell], sizeof(candidate->modes[cell]));
        partition_map->split[block] = candidate->splits[cell];
    }
    for (int macro = 0; macro < 4; macro++) {
        size_t index = (size_t)(first_macro_y + (macro >> 1)) *
            (size_t) transform_map->columns[0] +
            (size_t)(first_macro_x + (macro & 1));
        transform_map->strategies[index] = candidate->strategies[macro];
    }
    restore_super_snapshot(reconstructed, &candidate->reconstruction);
}

static int make_small_macro_candidate(
    const Plane *source, Plane *reconstructed, int quality,
    int extended_modes, int split_4x4, int effort, int trellis_policy,
    int loop_filter, const IntraQuant8 quant8[N148_SEGMENT_COUNT],
    const IntraQuant4 quant4[N148_SEGMENT_COUNT],
    const IntraRateModel *rate_model, int first_block_x, int first_block_y,
    int blocks_x, int blocks_y, int previous_dc_category,
    N148CoeffPlane *coefficients, uint8_t *modes,
    N148PartitionMap *partition_map,
    const N148SegmentationMap *segmentation_map,
    const N148TransformMap *transform_map, size_t transform_index,
    IntraMacroCandidate *candidate) {
    IntraMacroSnapshot original;
    take_macro_snapshot(reconstructed, first_block_x * 8,
                        first_block_y * 8, &original);
    memset(candidate, 0, sizeof(*candidate));
    int unsplit_mode_count = luma_mode_count(extended_modes, 8, effort);
    int split_mode_count = extended_modes ? N148_DIRECTIONAL_INTRA_MODE_COUNT : 4;
    int local_dc_category = previous_dc_category;
    int success = 1;
    for (int cell_y = 0; cell_y < 2 && success; cell_y++) {
        int block_y = first_block_y + cell_y;
        if (block_y >= blocks_y) continue;
        for (int cell_x = 0; cell_x < 2; cell_x++) {
            int block_x = first_block_x + cell_x;
            if (block_x >= blocks_x) continue;
            int cell = cell_y * 2 + cell_x;
            long block = (long) block_y * blocks_x + block_x;
            int x0 = block_x * 8;
            int y0 = block_y * 8;
            uint8_t segment = 0;
            if (segmentation_map && !segmentation_level_prevalidated(
                    segmentation_map, block_x, block_y, 0, 0, &segment)) {
                success = 0;
                break;
            }
            size_t map_index = (size_t) block;
            IntraBlockCandidate unsplit = {0}, split = {0};
            if (!make_unsplit_rdo_candidate(
                    source, reconstructed, x0, y0, 128, unsplit_mode_count,
                    first_block_x * 8 + 15, &quant8[segment], effort,
                    trellis_policy,
                    rate_model, coefficients, modes, block, blocks_x, 0,
                    local_dc_category, partition_map, map_index, &unsplit)) {
                success = 0;
                break;
            }
            int use_split = 0;
            if (split_4x4) {
                if (!make_split_rdo_candidate(
                        source, reconstructed, x0, y0, 128, split_mode_count,
                        first_block_x * 8 + 15, &quant4[segment], effort,
                        trellis_policy,
                        rate_model, coefficients, modes, block, blocks_x, 0,
                        local_dc_category, partition_map, map_index,
                        (double) unsplit.distortion +
                            fidelity_rdo_lambda(quant8[segment].dc_step, 1) *
                            unsplit.proxy_bits,
                        fidelity_rdo_lambda(quant8[segment].dc_step, 1),
                        &split)) {
                    success = 0;
                    break;
                }
                double lambda = fidelity_rdo_lambda(
                    quant8[segment].dc_step, 1);
                use_split = (double) split.distortion +
                    lambda * split.proxy_bits <
                    (double) unsplit.distortion +
                    lambda * unsplit.proxy_bits;
            }
            const IntraBlockCandidate *chosen = use_split ? &split : &unsplit;
            memcpy(coefficients->coefficients + block * 64,
                   chosen->coefficients, sizeof(chosen->coefficients));
            coefficients->nonzero_masks[block] =
                coefficient_mask(chosen->coefficients);
            memcpy(modes + block * N148_INTRA_MODE_SLOTS_PER_BLOCK,
                   chosen->modes, sizeof(chosen->modes));
            partition_map->split[map_index] = (uint8_t) use_split;
            restore_valid_block(reconstructed, x0, y0, chosen->pixels);
            if (!filter_reconstructed_block(
                    reconstructed, x0, y0, quality, 0, loop_filter,
                    segment, segmentation_map)) {
                success = 0;
                break;
            }
            memcpy(candidate->coefficients[cell], chosen->coefficients,
                   sizeof(candidate->coefficients[cell]));
            memcpy(candidate->modes[cell], chosen->modes,
                   sizeof(candidate->modes[cell]));
            candidate->splits[cell] = (uint8_t) use_split;
            candidate->proxy_bits += chosen->proxy_bits;
            local_dc_category = coefficient_category(chosen->coefficients[
                use_split ? 3 * 16 : 0]);
        }
    }
    if (success) {
        candidate->distortion = fidelity_region_error(
            source, reconstructed, first_block_x * 8,
            first_block_y * 8, 16, 1);
        candidate->proxy_bits += estimate_transform_bits(
            rate_model, transform_map, transform_index,
            N148_TRANSFORM_DCT8);
        candidate->ending_dc_category = local_dc_category;
        take_macro_snapshot(reconstructed, first_block_x * 8,
                            first_block_y * 8,
                            &candidate->reconstruction);
    }
    clear_macro_syntax(first_block_x, first_block_y, blocks_x, blocks_y,
                       coefficients, modes, partition_map);
    restore_macro_snapshot(reconstructed, &original);
    return success;
}

static int make_large_macro_candidate(
    const Plane *source, Plane *reconstructed, int quality,
    int extended_modes, int effort, int loop_filter,
    const IntraQuant16 *quant, const IntraRateModel *rate_model,
    int first_block_x, int first_block_y, int blocks_x,
    int previous_dc_category, N148CoeffPlane *coefficients, uint8_t *modes,
    N148PartitionMap *partition_map,
    const N148SegmentationMap *segmentation_map,
    const N148TransformMap *transform_map, size_t transform_index,
    uint8_t segment, double competing_cost,
    IntraMacroCandidate *candidate) {
    IntraMacroSnapshot original;
    int x0 = first_block_x * 8;
    int y0 = first_block_y * 8;
    take_macro_snapshot(reconstructed, x0, y0, &original);
    memset(candidate, 0, sizeof(*candidate));
    int mode_count = luma_mode_count(extended_modes, 16, effort);
    int shortlist_mode = -1;
    uint8_t shortlist_prediction[16 * 16];
    if (effort < 5)
        shortlist_mode = choose_mode(source, reconstructed, x0, y0, 16,
                                     128, mode_count, -1,
                                     1,
                                     shortlist_prediction, NULL, NULL);
    double best_cost = DBL_MAX;
    uint64_t nearest_reference_distortion = UINT64_MAX;
    int pruned = 0;
    int tried_mode = 0;
    for (int mode = 0; mode < mode_count; mode++) {
        if (shortlist_mode >= 0 && mode != shortlist_mode) continue;
        if (tried_mode) restore_macro_snapshot(reconstructed, &original);
        tried_mode = 1;
        uint8_t prediction[16 * 16];
        if (shortlist_mode == mode)
            memcpy(prediction, shortlist_prediction, sizeof(prediction));
        else
            predict_square(reconstructed, x0, y0, 16, mode, 128,
                           -1, 1, prediction);
        short sequence[16 * 16];
        if (!quantize16(source, x0, y0, prediction, quant, sequence)) {
            restore_macro_snapshot(reconstructed, &original);
            return 0;
        }
        /* The rate estimator reads the local sequence and candidate mode;
           it only consults committed modes outside this macroblock. Keep
           trial syntax local until install_macro_candidate() commits it. */
        double rate = estimate_transform_bits(
            rate_model, transform_map, transform_index,
            N148_TRANSFORM_DCT16);
        rate += estimate_large_coefficient_bits(
            rate_model, 0, previous_dc_category, sequence, 16 * 16);
        long first_block = (long) first_block_y * blocks_x + first_block_x;
        uint8_t large_modes[N148_INTRA_MODE_SLOTS_PER_BLOCK];
        for (int part = 0; part < N148_INTRA_MODE_SLOTS_PER_BLOCK; part++)
            large_modes[part] = (uint8_t) mode;
        rate += estimate_mode_bits(
            rate_model, 0, modes, first_block, large_modes, 1, blocks_x);
        double lambda = fidelity_rdo_lambda(quant->dc_step, 1);
        /* Distortion cannot be negative, so the rate term alone can reject
           a 16x16 candidate that cannot beat the current best. */
        if ((effort == 3 || effort == 4) &&
            lambda * rate >= competing_cost) {
            pruned = 1;
            continue;
        }
        if (!reconstruct16(sequence, prediction, quant, reconstructed,
                           x0, y0, 0, NULL) ||
            !filter_reconstructed_macro(reconstructed, x0, y0, quality,
                                        loop_filter, segment,
                                        segmentation_map)) {
            restore_macro_snapshot(reconstructed, &original);
            return 0;
        }
        int local_dc_category = coefficient_category(sequence[0]);
        uint64_t distortion = fidelity_region_error(
            source, reconstructed, x0, y0, 16, 1);
        if (mode < N148_DIRECTIONAL_INTRA_MODE_COUNT) {
            if (distortion < nearest_reference_distortion)
                nearest_reference_distortion = distortion;
        } else if (distortion > nearest_reference_distortion) {
            continue;
        }
        double cost = (double) distortion + lambda * rate;
        if (cost < best_cost) {
            best_cost = cost;
            for (int cell = 0; cell < 4; cell++) {
                memcpy(candidate->coefficients[cell],
                       sequence + cell * 64,
                       sizeof(candidate->coefficients[cell]));
                for (int part = 0;
                     part < N148_INTRA_MODE_SLOTS_PER_BLOCK; part++)
                    candidate->modes[cell][part] = (uint8_t) mode;
            }
            candidate->distortion = distortion;
            candidate->proxy_bits = rate;
            candidate->ending_dc_category = local_dc_category;
            take_macro_snapshot(reconstructed, x0, y0,
                                &candidate->reconstruction);
        }
    }
    restore_macro_snapshot(reconstructed, &original);
    if (best_cost == DBL_MAX && pruned) {
        candidate->proxy_bits = DBL_MAX;
        return 1;
    }
    return best_cost < DBL_MAX;
}

static int make_baseline_super_candidate(
    const Plane *source, Plane *reconstructed, int quality,
    int extended_modes, int split_4x4, int effort, int trellis_policy,
    int loop_filter, const IntraQuant8 quant8[N148_SEGMENT_COUNT],
    const IntraQuant4 quant4[N148_SEGMENT_COUNT],
    const IntraQuant16 quant16[N148_SEGMENT_COUNT],
    const IntraRateModel *rate_model, int first_macro_x, int first_macro_y,
    int blocks_x, int blocks_y, int previous_dc_category,
    N148CoeffPlane *coefficients, uint8_t *modes,
    N148PartitionMap *partition_map,
    const N148SegmentationMap *segmentation_map,
    N148TransformMap *transform_map, IntraSuperCandidate *candidate) {
    int first_block_x = first_macro_x * 2;
    int first_block_y = first_macro_y * 2;
    IntraSuperSnapshot original;
    uint8_t original_strategies[4];
    take_super_snapshot(reconstructed, first_block_x * 8,
                        first_block_y * 8, &original);
    for (int macro = 0; macro < 4; macro++) {
        size_t index = (size_t)(first_macro_y + (macro >> 1)) *
            (size_t) transform_map->columns[0] +
            (size_t)(first_macro_x + (macro & 1));
        original_strategies[macro] = transform_map->strategies[index];
    }
    memset(candidate, 0, sizeof(*candidate));
    int local_dc_category = previous_dc_category;
    int success = 1;
    for (int macro_y = 0; macro_y < 2 && success; macro_y++) {
        for (int macro_x = 0; macro_x < 2; macro_x++) {
            int current_macro_x = first_macro_x + macro_x;
            int current_macro_y = first_macro_y + macro_y;
            int block_x = current_macro_x * 2;
            int block_y = current_macro_y * 2;
            size_t transform_index = (size_t) current_macro_y *
                (size_t) transform_map->columns[0] +
                (size_t) current_macro_x;
            IntraMacroCandidate small, large;
            if (!make_small_macro_candidate(
                    source, reconstructed, quality, extended_modes,
                    split_4x4, effort, trellis_policy, loop_filter,
                    quant8, quant4, rate_model, block_x, block_y,
                    blocks_x, blocks_y, local_dc_category, coefficients,
                    modes, partition_map, segmentation_map, transform_map,
                    transform_index, &small)) {
                success = 0;
                break;
            }
            uint8_t segment = 0;
            if (segmentation_map && !segmentation_level_prevalidated(
                    segmentation_map, block_x, block_y, 0, 0, &segment)) {
                success = 0;
                break;
            }
            double lambda = fidelity_rdo_lambda(
                quant16[segment].dc_step, 1);
            double small_cost = (double) small.distortion +
                lambda * small.proxy_bits;
            if (!make_large_macro_candidate(
                    source, reconstructed, quality, extended_modes, effort,
                    loop_filter, &quant16[segment], rate_model, block_x,
                    block_y, blocks_x, local_dc_category, coefficients,
                    modes, partition_map, segmentation_map, transform_map,
                    transform_index, segment, small_cost, &large)) {
                success = 0;
                break;
            }
            int use_large = (double) large.distortion +
                lambda * large.proxy_bits < small_cost;
            const IntraMacroCandidate *chosen = use_large ? &large : &small;
            transform_map->strategies[transform_index] = use_large ?
                N148_TRANSFORM_DCT16 : N148_TRANSFORM_DCT8;
            install_macro_candidate(
                chosen, block_x, block_y, blocks_x, blocks_y,
                coefficients, modes, partition_map, reconstructed);
            candidate->proxy_bits += chosen->proxy_bits;
            local_dc_category = chosen->ending_dc_category;
        }
    }
    if (success) {
        for (int cell = 0; cell < 16; cell++) {
            int block_x = first_block_x + (cell & 3);
            int block_y = first_block_y + (cell >> 2);
            long block = (long) block_y * blocks_x + block_x;
            memcpy(candidate->coefficients[cell],
                   coefficients->coefficients + block * 64,
                   sizeof(candidate->coefficients[cell]));
            memcpy(candidate->modes[cell],
                   modes + block * N148_INTRA_MODE_SLOTS_PER_BLOCK,
                   sizeof(candidate->modes[cell]));
            candidate->splits[cell] = partition_map->split[block];
        }
        for (int macro = 0; macro < 4; macro++) {
            size_t index = (size_t)(first_macro_y + (macro >> 1)) *
                (size_t) transform_map->columns[0] +
                (size_t)(first_macro_x + (macro & 1));
            candidate->strategies[macro] =
                transform_map->strategies[index];
        }
        candidate->distortion = fidelity_region_error(
            source, reconstructed, first_block_x * 8,
            first_block_y * 8, 32, 1);
        candidate->ending_dc_category = local_dc_category;
        take_super_snapshot(reconstructed, first_block_x * 8,
                            first_block_y * 8,
                            &candidate->reconstruction);
    }
    clear_super_syntax(first_block_x, first_block_y, blocks_x, blocks_y,
                       coefficients, modes, partition_map);
    for (int macro = 0; macro < 4; macro++) {
        size_t index = (size_t)(first_macro_y + (macro >> 1)) *
            (size_t) transform_map->columns[0] +
            (size_t)(first_macro_x + (macro & 1));
        transform_map->strategies[index] = original_strategies[macro];
    }
    restore_super_snapshot(reconstructed, &original);
    return success;
}

static int make_dct32_super_candidate(
    const Plane *source, Plane *reconstructed, int quality,
    int extended_modes, int effort, int loop_filter,
    const IntraQuant32 *quant, const IntraRateModel *rate_model,
    int first_macro_x, int first_macro_y, int blocks_x, int blocks_y,
    int previous_dc_category, N148CoeffPlane *coefficients, uint8_t *modes,
    N148PartitionMap *partition_map,
    const N148SegmentationMap *segmentation_map,
    N148TransformMap *transform_map, uint8_t segment,
    IntraSuperCandidate *candidate) {
    int first_block_x = first_macro_x * 2;
    int first_block_y = first_macro_y * 2;
    int x0 = first_block_x * 8;
    int y0 = first_block_y * 8;
    if (first_block_x + 3 >= blocks_x || first_block_y + 3 >= blocks_y)
        return 0;
    IntraSuperSnapshot original;
    uint8_t original_strategies[4];
    take_super_snapshot(reconstructed, x0, y0, &original);
    for (int macro = 0; macro < 4; macro++) {
        size_t index = (size_t)(first_macro_y + (macro >> 1)) *
            (size_t) transform_map->columns[0] +
            (size_t)(first_macro_x + (macro & 1));
        original_strategies[macro] = transform_map->strategies[index];
        transform_map->strategies[index] = N148_TRANSFORM_DCT4;
    }
    clear_super_syntax(first_block_x, first_block_y, blocks_x, blocks_y,
                       coefficients, modes, partition_map);
    memset(candidate, 0, sizeof(*candidate));
    for (int macro = 0; macro < 4; macro++)
        candidate->strategies[macro] = N148_TRANSFORM_DCT4;
    int mode_count = luma_mode_count(extended_modes, 32, effort);
    int shortlist_mode = -1;
    uint8_t shortlist_prediction[32 * 32];
    if (effort < 5)
        shortlist_mode = choose_mode(source, reconstructed, x0, y0, 32,
                                     128, mode_count, -1, 1,
                                     shortlist_prediction, NULL, NULL);
    double best_cost = DBL_MAX;
    uint64_t nearest_reference_distortion = UINT64_MAX;
    for (int mode = 0; mode < mode_count; mode++) {
        if (shortlist_mode >= 0 && mode != shortlist_mode) continue;
        restore_super_snapshot(reconstructed, &original);
        clear_super_syntax(first_block_x, first_block_y, blocks_x, blocks_y,
                           coefficients, modes, partition_map);
        uint8_t prediction[32 * 32];
        if (shortlist_mode == mode)
            memcpy(prediction, shortlist_prediction, sizeof(prediction));
        else
            predict_square(reconstructed, x0, y0, 32, mode, 128,
                           -1, 1, prediction);
        short sequence[32 * 32];
        if (!quantize32(source, x0, y0, prediction, quant, sequence)) {
            restore_super_snapshot(reconstructed, &original);
            return 0;
        }
        for (int cell = 0; cell < 16; cell++) {
            int block_x = first_block_x + (cell & 3);
            int block_y = first_block_y + (cell >> 2);
            long block = (long) block_y * blocks_x + block_x;
            memcpy(coefficients->coefficients + block * 64,
                   sequence + cell * 64, 64 * sizeof(*sequence));
            coefficients->nonzero_masks[block] =
                coefficient_mask(sequence + cell * 64);
            for (int part = 0;
                 part < N148_INTRA_MODE_SLOTS_PER_BLOCK; part++)
                modes[block * N148_INTRA_MODE_SLOTS_PER_BLOCK + part] =
                    (uint8_t) mode;
            partition_map->split[block] = 0;
        }
        if (!reconstruct32(sequence, prediction, quant, reconstructed,
                           x0, y0) ||
            !filter_reconstructed_super(reconstructed, x0, y0, quality,
                                        loop_filter, segment,
                                        segmentation_map)) {
            restore_super_snapshot(reconstructed, &original);
            return 0;
        }
        double rate = estimate_large_coefficient_bits(
            rate_model, 0, previous_dc_category, sequence, 32 * 32);
        for (int macro = 0; macro < 4; macro++) {
            size_t index = (size_t)(first_macro_y + (macro >> 1)) *
                (size_t) transform_map->columns[0] +
                (size_t)(first_macro_x + (macro & 1));
            rate += estimate_transform_bits(
                rate_model, transform_map, index, N148_TRANSFORM_DCT4);
        }
        long first_block = (long) first_block_y * blocks_x + first_block_x;
        uint8_t large_modes[N148_INTRA_MODE_SLOTS_PER_BLOCK];
        for (int part = 0; part < N148_INTRA_MODE_SLOTS_PER_BLOCK; part++)
            large_modes[part] = (uint8_t) mode;
        rate += estimate_mode_bits(rate_model, 0, modes, first_block,
                                   large_modes, 1, blocks_x);
        uint64_t distortion = fidelity_region_error(
            source, reconstructed, x0, y0, 32, 1);
        if (mode < N148_DIRECTIONAL_INTRA_MODE_COUNT) {
            if (distortion < nearest_reference_distortion)
                nearest_reference_distortion = distortion;
        } else if (distortion > nearest_reference_distortion) {
            continue;
        }
        double lambda = fidelity_rdo_lambda(quant->dc_step, 1);
        double cost = (double) distortion + lambda * rate;
        if (cost < best_cost) {
            best_cost = cost;
            for (int cell = 0; cell < 16; cell++) {
                memcpy(candidate->coefficients[cell],
                       sequence + cell * 64,
                       sizeof(candidate->coefficients[cell]));
                for (int part = 0;
                     part < N148_INTRA_MODE_SLOTS_PER_BLOCK; part++)
                    candidate->modes[cell][part] = (uint8_t) mode;
            }
            candidate->distortion = distortion;
            candidate->proxy_bits = rate;
            candidate->ending_dc_category =
                coefficient_category(sequence[0]);
            take_super_snapshot(reconstructed, x0, y0,
                                &candidate->reconstruction);
        }
    }
    clear_super_syntax(first_block_x, first_block_y, blocks_x, blocks_y,
                       coefficients, modes, partition_map);
    for (int macro = 0; macro < 4; macro++) {
        size_t index = (size_t)(first_macro_y + (macro >> 1)) *
            (size_t) transform_map->columns[0] +
            (size_t)(first_macro_x + (macro & 1));
        transform_map->strategies[index] = original_strategies[macro];
    }
    restore_super_snapshot(reconstructed, &original);
    return best_cost < DBL_MAX;
}

/* Variable-luma selection visits 16x16 regions causally. The small alternative retains the
   mature per-cell 4x4/8x8 RDO; the large alternative uses its own mapped
   quantizer and is selected with reconstructed SSE plus contextual bits. */
static int quantize_variable_luma_plane(
    const Plane *source, int quality, int extended_modes, int split_4x4,
    int effort, int trellis_policy, int loop_filter,
    int calibrated_quant, const IntraRateModel *rate_model,
    N148PartitionMap *partition_map, N148TransformMap *transform_map,
    N148CoeffPlane *coefficients, uint8_t *modes,
    const N148SegmentationMap *segmentation_map) {
    size_t count;
    if (!source || !source->data || !rate_model || !partition_map ||
        !transform_map || !modes || quality < 1 || quality > 100 ||
        !split_4x4 || !fidelity_luma_transform_map_validate(transform_map) ||
        !checked_block_count(source->width, source->height, &count) ||
        !allocate_coefficients(count, coefficients)) return 0;
    int blocks_x = source->width / 8 + (source->width % 8 != 0);
    int blocks_y = source->height / 8 + (source->height % 8 != 0);
    if (partition_map->blocks_x[0] != blocks_x ||
        partition_map->blocks_y[0] != blocks_y ||
        transform_map->blocks_x[0] != blocks_x ||
        transform_map->blocks_y[0] != blocks_y) {
        n148_free_coeff_plane(coefficients);
        return 0;
    }
    Plane reconstructed = create_plane(source->width, source->height);
    if (!reconstructed.data) {
        n148_free_coeff_plane(coefficients);
        return 0;
    }
    /* Macroblock order can request a down-left reference from the not-yet
       visited top half of a later macroblock. Neutral initialization makes
       that legal causal padding explicit and decoder-independent. */
    memset(reconstructed.data, 128,
           (size_t) source->width * (size_t) source->height);
    IntraQuant8 quant8[N148_SEGMENT_COUNT];
    IntraQuant4 quant4[N148_SEGMENT_COUNT];
    IntraQuant16 quant16[N148_SEGMENT_COUNT];
    IntraQuant32 quant32[N148_SEGMENT_COUNT];
    const int (*base)[8] = luma_quant_base(calibrated_quant);
    int search_dct32 =
        (fidelity_tools & N148_FIDELITY_DCT32) != 0 && effort >= 5;
    if (!build_segment_quantizers(base, quality, 0, segmentation_map,
                                  quant8, quant4) ||
        !build_segment_quantizers16(base, quality, segmentation_map,
                                    quant16) ||
        (search_dct32 && !build_segment_quantizers32(
            base, quality, segmentation_map, quant32))) {
        free_plane(&reconstructed);
        n148_free_coeff_plane(coefficients);
        return 0;
    }
    int previous_dc_category = 0;
    int success = 1;
    for (int macro_y = 0;
         macro_y < transform_map->rows[0] && success; macro_y++) {
        for (int macro_x = 0; macro_x < transform_map->columns[0];
             macro_x++) {
            int first_block_x = macro_x * 2;
            int first_block_y = macro_y * 2;
            size_t transform_index = (size_t) macro_y *
                (size_t) transform_map->columns[0] + (size_t) macro_x;
            if (search_dct32 && n148_luma_transform_dct32_member(
                    transform_map, macro_x, macro_y)) continue;
            int complete_super = search_dct32 && !(macro_x & 1) &&
                !(macro_y & 1) &&
                macro_x + 1 < transform_map->columns[0] &&
                macro_y + 1 < transform_map->rows[0] &&
                first_block_x + 3 < blocks_x &&
                first_block_y + 3 < blocks_y;
            if (complete_super) {
                uint8_t segment = 0;
                IntraSuperCandidate baseline, dct32;
                if (segmentation_map && !segmentation_level_prevalidated(
                        segmentation_map, first_block_x, first_block_y,
                        0, 0, &segment)) {
                    success = 0;
                    break;
                }
                if (!make_baseline_super_candidate(
                        source, &reconstructed, quality, extended_modes,
                        split_4x4, effort, trellis_policy, loop_filter,
                        quant8, quant4, quant16, rate_model, macro_x,
                        macro_y, blocks_x, blocks_y, previous_dc_category,
                        coefficients, modes, partition_map, segmentation_map,
                        transform_map, &baseline) ||
                    !make_dct32_super_candidate(
                        source, &reconstructed, quality, extended_modes,
                        effort, loop_filter, &quant32[segment], rate_model,
                        macro_x, macro_y, blocks_x, blocks_y,
                        previous_dc_category, coefficients, modes,
                        partition_map, segmentation_map, transform_map,
                        segment, &dct32)) {
                    success = 0;
                    break;
                }
                double lambda = fidelity_rdo_lambda(
                    quant32[segment].dc_step, 1);
                int use_dct32 = (double) dct32.distortion +
                    lambda * dct32.proxy_bits <
                    (double) baseline.distortion +
                    lambda * baseline.proxy_bits;
                if (use_dct32) {
                    install_super_candidate(
                        &dct32, macro_x, macro_y, blocks_x, coefficients,
                        modes, partition_map, transform_map, &reconstructed);
                    previous_dc_category = dct32.ending_dc_category;
                    continue;
                }
            }
            IntraMacroCandidate small, large;
            if (!make_small_macro_candidate(
                    source, &reconstructed, quality, extended_modes,
                    split_4x4, effort, trellis_policy, loop_filter,
                    quant8, quant4, rate_model, first_block_x,
                    first_block_y, blocks_x, blocks_y,
                    previous_dc_category, coefficients, modes,
                    partition_map, segmentation_map, transform_map,
                    transform_index, &small)) {
                success = 0;
                break;
            }
            int complete = first_block_x + 1 < blocks_x &&
                first_block_y + 1 < blocks_y;
            int use_large = 0;
            if (complete) {
                uint8_t segment = 0;
                if (segmentation_map && !segmentation_level_prevalidated(
                        segmentation_map, first_block_x, first_block_y,
                        0, 0, &segment)) {
                    success = 0;
                    break;
                }
                double lambda = fidelity_rdo_lambda(
                    quant16[segment].dc_step, 1);
                double small_cost = (double) small.distortion +
                    lambda * small.proxy_bits;
                if (!make_large_macro_candidate(
                        source, &reconstructed, quality, extended_modes,
                        effort, loop_filter, &quant16[segment], rate_model,
                        first_block_x, first_block_y, blocks_x,
                        previous_dc_category, coefficients, modes,
                        partition_map, segmentation_map, transform_map,
                        transform_index, segment, small_cost, &large)) {
                    success = 0;
                    break;
                }
                use_large = (double) large.distortion +
                    lambda * large.proxy_bits < small_cost;
            }
            const IntraMacroCandidate *chosen = use_large ? &large : &small;
            transform_map->strategies[transform_index] = use_large ?
                N148_TRANSFORM_DCT16 : N148_TRANSFORM_DCT8;
            install_macro_candidate(
                chosen, first_block_x, first_block_y, blocks_x, blocks_y,
                coefficients, modes, partition_map, &reconstructed);
            previous_dc_category = chosen->ending_dc_category;
        }
    }
    free_plane(&reconstructed);
    if (!success) n148_free_coeff_plane(coefficients);
    return success;
}

/* Joint chroma prediction selects one predictor for Cb and Cr. The two coefficient
   streams and reconstructed references remain independent; only the decision
   and its entropy symbol are shared. The caller controls whether the four
   baseline or all ten directional modes participate in the search. */
static int quantize_chroma_pair(
    const Plane *cb, const Plane *cr, int quality, int extended_modes,
    int effort, int calibrated_chroma,
    int trellis_policy, int loop_filter,
    const IntraRateModel *rate_model, N148PartitionMap *partition_map,
    N148CoeffPlane coefficients[2], uint8_t *cb_modes, uint8_t *cr_modes,
    int subsample_x, int subsample_y,
    const N148SegmentationMap *segmentation_map) {
    size_t count;
    if (!cb || !cr || !cb->data || !cr->data || !partition_map ||
        !coefficients || !cb_modes || !cr_modes ||
        cb->width != cr->width || cb->height != cr->height ||
        quality < 1 || quality > 100 || effort < 0 || effort > 9 ||
        (extended_modes != 0 && extended_modes != 1) ||
        (calibrated_chroma != 0 && calibrated_chroma != 1) ||
        (trellis_policy != N148_TRELLIS_OFF &&
         trellis_policy != N148_TRELLIS_LEGACY) ||
        loop_filter < N148_LOOP_FILTER_OFF ||
        loop_filter > N148_LOOP_FILTER_QUANT_ADAPTIVE_LUMA ||
        (subsample_x != 0 && subsample_x != 1) ||
        (subsample_y != 0 && subsample_y != 1) ||
        (segmentation_map &&
         !n148_segmentation_map_validate(segmentation_map)) ||
        !checked_block_count(cb->width, cb->height, &count)) return 0;
    memset(coefficients, 0, 2 * sizeof(*coefficients));
    if (!allocate_coefficients(count, &coefficients[0]) ||
        !allocate_coefficients(count, &coefficients[1])) {
        n148_free_coeff_plane(&coefficients[0]);
        n148_free_coeff_plane(&coefficients[1]);
        return 0;
    }
    int blocks_x = cb->width / 8 + (cb->width % 8 != 0);
    int blocks_y = cb->height / 8 + (cb->height % 8 != 0);
    if (partition_map->blocks_x[1] != blocks_x ||
        partition_map->blocks_y[1] != blocks_y ||
        partition_map->blocks_x[2] != blocks_x ||
        partition_map->blocks_y[2] != blocks_y) {
        n148_free_coeff_plane(&coefficients[0]);
        n148_free_coeff_plane(&coefficients[1]);
        return 0;
    }
    Plane reconstructed[2] = {
        create_plane(cb->width, cb->height),
        create_plane(cr->width, cr->height),
    };
    if (!reconstructed[0].data || !reconstructed[1].data) {
        free_plane(&reconstructed[0]);
        free_plane(&reconstructed[1]);
        n148_free_coeff_plane(&coefficients[0]);
        n148_free_coeff_plane(&coefficients[1]);
        return 0;
    }
    const Plane *source[2] = {cb, cr};
    IntraQuant8 quant[N148_SEGMENT_COUNT];
    IntraQuant4 unused_quant4[N148_SEGMENT_COUNT];
    if (!build_segment_quantizers(
            calibrated_chroma ? FORMAT_4_CHROMA_QUANT_BASE : Q_CHROMA_BASE,
            quality, 1, segmentation_map, quant, unused_quant4)) {
        free_plane(&reconstructed[0]);
        free_plane(&reconstructed[1]);
        n148_free_coeff_plane(&coefficients[0]);
        n148_free_coeff_plane(&coefficients[1]);
        return 0;
    }
    int mode_count = extended_modes ? N148_DIRECTIONAL_INTRA_MODE_COUNT : 4;
    int previous_dc_category[2] = {0, 0};
    int success = 1;
    for (int block_y = 0; block_y < blocks_y && success; block_y++) {
        for (int block_x = 0; block_x < blocks_x; block_x++) {
            long block = (long) block_y * blocks_x + block_x;
            int x0 = block_x * 8;
            int y0 = block_y * 8;
            uint8_t segment = 0;
            if (segmentation_map && !segmentation_level_prevalidated(
                    segmentation_map, block_x, block_y,
                    subsample_x, subsample_y, &segment)) {
                success = 0;
                break;
            }
            const IntraQuant8 *block_quant = &quant[0];
            IntraBlockCandidate best[2];
            memset(best, 0, sizeof(best));
            double best_cost = DBL_MAX;
            size_t cb_map = partition_map->plane_offsets[1] + (size_t) block;
            size_t cr_map = partition_map->plane_offsets[2] + (size_t) block;
            int shortlist = effort <= 4 && mode_count == 10 &&
                (fidelity_tools & N148_FIDELITY_FAST_MODE_SEARCH);
            uint8_t predictions[2][N148_DIRECTIONAL_INTRA_MODE_COUNT][64];
            uint8_t selected[N148_DIRECTIONAL_INTRA_MODE_COUNT] = {0};
            if (shortlist) {
                uint64_t scores[N148_DIRECTIONAL_INTRA_MODE_COUNT];
                for (int mode = 0; mode < mode_count; mode++) {
                    for (int plane = 0; plane < 2; plane++) {
                        predict_square(&reconstructed[plane], x0, y0, 8,
                                       mode, 128, -1, 0,
                                       predictions[plane][mode]);
                    }
                    scores[mode] = prediction_sse(
                        cb, x0, y0, 8, predictions[0][mode], UINT64_MAX) +
                        prediction_sse(
                        cr, x0, y0, 8, predictions[1][mode], UINT64_MAX);
                }
                selected[0] = 1;
                for (int rank = 0; rank < 2; rank++) {
                    int chosen = -1;
                    for (int mode = 0; mode < mode_count; mode++) {
                        if (scores[mode] == UINT64_MAX) continue;
                        if (chosen < 0 || scores[mode] < scores[chosen])
                            chosen = mode;
                    }
                    if (chosen < 0) break;
                    selected[chosen] = 1;
                    scores[chosen] = UINT64_MAX;
                }
            }
            for (int mode = 0; mode < mode_count; mode++) {
                if (shortlist && !selected[mode]) continue;
                IntraBlockCandidate trial[2];
                memset(trial, 0, sizeof(trial));
                if (!make_fixed_unsplit_candidate(
                        source[0], &reconstructed[0], x0, y0, 128, mode,
                        block_quant, effort, trellis_policy, rate_model,
                        &coefficients[0], block, blocks_x,
                        previous_dc_category[0],
                        shortlist ? predictions[0][mode] : NULL,
                        &trial[0]) ||
                    !make_fixed_unsplit_candidate(
                        source[1], &reconstructed[1], x0, y0, 128, mode,
                        block_quant, effort, trellis_policy, rate_model,
                        &coefficients[1], block, blocks_x,
                        previous_dc_category[1],
                        shortlist ? predictions[1][mode] : NULL,
                        &trial[1])) {
                    success = 0;
                    break;
                }
                double rate = trial[0].proxy_bits + trial[1].proxy_bits;
                if (rate_model) {
                    rate += estimate_mode_bits(
                        rate_model, 1, cb_modes, block, trial[0].modes,
                        1, blocks_x);
                    rate += estimate_partition_bits(
                        rate_model, partition_map, cb_map, 0);
                    rate += estimate_partition_bits(
                        rate_model, partition_map, cr_map, 0);
                } else {
                    rate += 2.0;
                }
                double lambda = INTRA_RDO_LAMBDA_SCALE *
                    block_quant->dc_step * block_quant->dc_step;
                double cost = joint_chroma_distortion(
                    cb, cr, trial, x0, y0) + lambda * rate;
                if (cost < best_cost) {
                    best_cost = cost;
                    best[0] = trial[0];
                    best[1] = trial[1];
                }
            }
            if (!success || best_cost == DBL_MAX) {
                success = 0;
                break;
            }
            for (int plane = 0; plane < 2; plane++) {
                memcpy(coefficients[plane].coefficients + block * 64,
                       best[plane].coefficients,
                       sizeof(best[plane].coefficients));
                coefficients[plane].nonzero_masks[block] =
                    coefficient_mask(best[plane].coefficients);
                restore_valid_block(&reconstructed[plane], x0, y0,
                                    best[plane].pixels);
                previous_dc_category[plane] =
                    coefficient_category(best[plane].coefficients[0]);
                if (!filter_reconstructed_block(
                        &reconstructed[plane], x0, y0, quality,
                        plane + 1, loop_filter, segment,
                        segmentation_map)) {
                    success = 0;
                    break;
                }
            }
            memcpy(cb_modes + block * N148_INTRA_MODE_SLOTS_PER_BLOCK,
                   best[0].modes, sizeof(best[0].modes));
            memcpy(cr_modes + block * N148_INTRA_MODE_SLOTS_PER_BLOCK,
                   best[0].modes, sizeof(best[0].modes));
            partition_map->split[cb_map] = 0;
            partition_map->split[cr_map] = 0;
            if (!success) break;
        }
    }
    free_plane(&reconstructed[0]);
    free_plane(&reconstructed[1]);
    if (!success) {
        n148_free_coeff_plane(&coefficients[0]);
        n148_free_coeff_plane(&coefficients[1]);
    }
    return success;
}

int n148_directional_intra_quantize_planes(
    const Plane *y, const Plane *cb, const Plane *cr, int quality,
    int chroma_quality, int calibrated_chroma, int calibrated_luma,
    int extended_modes,
    int split_4x4, int contextual_rdo, int effort, int trellis_policy,
    int loop_filter,
    N148PartitionMap *partition_map,
    const N148SegmentationMap *segmentation_map,
    N148TransformMap *transform_map,
    N148CoeffPlane coefficients[3], uint8_t **modes, size_t *mode_count) {
    if (!y || !cb || !cr || !partition_map || !coefficients || !modes ||
        !mode_count || cb->width != cr->width || cb->height != cr->height ||
        quality < 1 || quality > 100 || chroma_quality < 1 ||
        chroma_quality > 100 ||
        (calibrated_chroma != 0 && calibrated_chroma != 1) ||
        (calibrated_luma != 0 && calibrated_luma != 1) ||
        (segmentation_map &&
         !n148_segmentation_map_validate(segmentation_map)) ||
        trellis_policy < N148_TRELLIS_OFF ||
        trellis_policy > N148_TRELLIS_PERCEPTUAL_LUMA ||
        loop_filter < N148_LOOP_FILTER_OFF ||
        loop_filter > N148_LOOP_FILTER_QUANT_ADAPTIVE_LUMA ||
        (trellis_policy != N148_TRELLIS_OFF && !contextual_rdo) ||
        (transform_map &&
         (!contextual_rdo || !split_4x4 ||
          !fidelity_luma_transform_map_validate(transform_map))))
        return 0;
    memset(coefficients, 0, 3 * sizeof(*coefficients));
    *modes = NULL;
    *mode_count = 0;
    int chroma = CHROMA_444;
    if (cb->width < y->width)
        chroma = cb->height < y->height ? CHROMA_420 : CHROMA_422;
    int chroma_subsample_x = chroma != CHROMA_444;
    int chroma_subsample_y = chroma == CHROMA_420;
    int chroma_trellis_policy = trellis_policy == N148_TRELLIS_LEGACY ?
        N148_TRELLIS_LEGACY : N148_TRELLIS_OFF;
    size_t total_modes;
    if (!n148_directional_intra_expected_modes(y->width, y->height, chroma,
                                      &total_modes) ||
        !n148_partition_map_validate(partition_map)) return 0;
    uint8_t *all_modes = (uint8_t *) malloc(total_modes);
    if (!all_modes) return 0;
    size_t y_blocks, chroma_blocks;
    if (!checked_block_count(y->width, y->height, &y_blocks) ||
        !checked_block_count(cb->width, cb->height, &chroma_blocks)) {
        free(all_modes);
        return 0;
    }
    Plane corrected_y = {0};
    const Plane *final_y = y;
    init_dct_tables();
    int analysis_split = effort == 3 &&
        (fidelity_tools & N148_FIDELITY_STRUCTURAL_LUMA_QUANT) ? 0 : split_4x4;
    int success = quantize_plane(
        y, quality, 0, extended_modes, analysis_split, effort,
        0, loop_filter, calibrated_luma, 0, 0, NULL, partition_map,
        &coefficients[0],
        all_modes, segmentation_map, NULL) &&
        quantize_plane(
            cb, chroma_quality, 1, extended_modes, split_4x4,
            effort, 0, loop_filter, calibrated_chroma,
            chroma_subsample_x, chroma_subsample_y, NULL, partition_map,
            &coefficients[1],
            all_modes + y_blocks * N148_INTRA_MODE_SLOTS_PER_BLOCK,
            segmentation_map, NULL) &&
        quantize_plane(
            cr, chroma_quality, 2, extended_modes, split_4x4,
            effort, 0, loop_filter, calibrated_chroma,
            chroma_subsample_x, chroma_subsample_y, NULL, partition_map,
            &coefficients[2],
            all_modes + (y_blocks + chroma_blocks) *
                N148_INTRA_MODE_SLOTS_PER_BLOCK,
            segmentation_map, NULL);
    if (success && contextual_rdo) {
        IntraRateModel rate_model;
        int allowed_modes = luma_mode_count(extended_modes, 8, effort);
        success = build_rate_model(coefficients, all_modes, partition_map,
                                   allowed_modes, 0, NULL, &rate_model);
        for (int plane = 0; plane < 3; plane++)
            n148_free_coeff_plane(&coefficients[plane]);
        memset(all_modes, 0, total_modes);
        memset(partition_map->split, 0, partition_map->count);
        if (success && n148_fidelity_structural_quant() &&
            fidelity_rgb_source.pixels) {
            Plane reconstructed_chroma[2] = {{0},{0}};
            success = quantize_plane(
                cb, chroma_quality, 1, extended_modes, split_4x4, effort,
                chroma_trellis_policy, loop_filter, calibrated_chroma,
                chroma_subsample_x, chroma_subsample_y, &rate_model,
                partition_map, &coefficients[1],
                all_modes + y_blocks * N148_INTRA_MODE_SLOTS_PER_BLOCK,
                segmentation_map, &reconstructed_chroma[0]) &&
                quantize_plane(
                cr, chroma_quality, 2, extended_modes, split_4x4, effort,
                chroma_trellis_policy, loop_filter, calibrated_chroma,
                chroma_subsample_x, chroma_subsample_y, &rate_model,
                partition_map, &coefficients[2],
                all_modes + (y_blocks + chroma_blocks) *
                    N148_INTRA_MODE_SLOTS_PER_BLOCK, segmentation_map, &reconstructed_chroma[1]);
            if (success) success = n148_project_luma_from_chroma(
                &fidelity_rgb_source, y, &reconstructed_chroma[0],
                &reconstructed_chroma[1], &corrected_y);
            if (success) final_y = &corrected_y;
            if (success) success = transform_map ? quantize_variable_luma_plane(
                final_y, quality, extended_modes, split_4x4, effort,
                trellis_policy, loop_filter, calibrated_luma,
                &rate_model, partition_map, transform_map,
                &coefficients[0], all_modes, segmentation_map) :
                quantize_plane(
                    final_y, quality, 0, extended_modes, split_4x4, effort,
                    trellis_policy, loop_filter, calibrated_luma, 0, 0,
                    &rate_model, partition_map, &coefficients[0], all_modes,
                    segmentation_map, NULL);
            free_plane(&reconstructed_chroma[0]);
            free_plane(&reconstructed_chroma[1]);
        }
        else if (success) {
            success = (transform_map ? quantize_variable_luma_plane(
                y, quality, extended_modes, split_4x4, effort,
                trellis_policy, loop_filter, calibrated_luma,
                &rate_model, partition_map, transform_map,
                &coefficients[0], all_modes, segmentation_map) :
                quantize_plane(
                    y, quality, 0, extended_modes, split_4x4, effort,
                    trellis_policy, loop_filter, calibrated_luma, 0, 0,
                    &rate_model, partition_map, &coefficients[0], all_modes,
                    segmentation_map, NULL)) &&
                quantize_plane(
                    cb, chroma_quality, 1, extended_modes, split_4x4, effort,
                    chroma_trellis_policy, loop_filter, calibrated_chroma,
                    chroma_subsample_x, chroma_subsample_y,
                    &rate_model, partition_map,
                    &coefficients[1],
                    all_modes + y_blocks * N148_INTRA_MODE_SLOTS_PER_BLOCK,
                    segmentation_map, NULL) &&
                quantize_plane(
                    cr, chroma_quality, 2, extended_modes, split_4x4, effort,
                    chroma_trellis_policy, loop_filter, calibrated_chroma,
                    chroma_subsample_x, chroma_subsample_y,
                    &rate_model, partition_map,
                    &coefficients[2],
                    all_modes + (y_blocks + chroma_blocks) *
                        N148_INTRA_MODE_SLOTS_PER_BLOCK,
                    segmentation_map, NULL);
        }
        /* The fast search keeps the first causal RDO result. The
           refined model requires a second complete luma reconstruction and
           measured only a small mixed quality change on the release corpus. */
        if (success && transform_map &&
            !(effort <= 4 &&
              (fidelity_tools & N148_FIDELITY_FAST_MODE_SEARCH))) {
            IntraRateModel refined_rate_model;
            success = build_rate_model(
                coefficients, all_modes, partition_map, allowed_modes, 0,
                transform_map, &refined_rate_model);
            n148_free_coeff_plane(&coefficients[0]);
            memset(all_modes, 0, y_blocks *
                   N148_INTRA_MODE_SLOTS_PER_BLOCK);
            memset(partition_map->split, 0,
                   partition_map->plane_offsets[1]);
            memset(transform_map->strategies, N148_TRANSFORM_DCT8,
                   transform_map->count);
            if (success) {
                success = quantize_variable_luma_plane(
                    final_y, quality, extended_modes, split_4x4, effort,
                    trellis_policy, loop_filter, calibrated_luma,
                    &refined_rate_model, partition_map, transform_map,
                    &coefficients[0], all_modes, segmentation_map);
            }
        }
    }
    free_plane(&corrected_y);
    if (!success) {
        for (int plane = 0; plane < 3; plane++)
            n148_free_coeff_plane(&coefficients[plane]);
        free(all_modes);
        return 0;
    }
    *modes = all_modes;
    *mode_count = total_modes;
    return 1;
}

int n148_joint_chroma_intra_quantize_planes(
    const Plane *y, const Plane *cb, const Plane *cr, int quality,
    int chroma_quality, int calibrated_chroma, int calibrated_luma,
    int extended_modes,
    int split_4x4, int contextual_rdo, int effort, int trellis_policy,
    int loop_filter,
    N148PartitionMap *partition_map,
    const N148SegmentationMap *segmentation_map,
    N148TransformMap *transform_map,
    N148CoeffPlane coefficients[3], uint8_t **modes, size_t *mode_count) {
    if (!y || !cb || !cr || !partition_map || !coefficients || !modes ||
        !mode_count || cb->width != cr->width || cb->height != cr->height ||
        quality < 1 || quality > 100 || chroma_quality < 1 ||
        chroma_quality > 100 ||
        (calibrated_chroma != 0 && calibrated_chroma != 1) ||
        (calibrated_luma != 0 && calibrated_luma != 1) ||
        (segmentation_map &&
         !n148_segmentation_map_validate(segmentation_map)) ||
        trellis_policy < N148_TRELLIS_OFF ||
        trellis_policy > N148_TRELLIS_PERCEPTUAL_LUMA ||
        loop_filter < N148_LOOP_FILTER_OFF ||
        loop_filter > N148_LOOP_FILTER_QUANT_ADAPTIVE_LUMA ||
        !contextual_rdo ||
        (trellis_policy != N148_TRELLIS_OFF && !contextual_rdo) ||
        (transform_map &&
         (!split_4x4 ||
          !fidelity_luma_transform_map_validate(transform_map)))) return 0;
    memset(coefficients, 0, 3 * sizeof(*coefficients));
    *modes = NULL;
    *mode_count = 0;
    int chroma = CHROMA_444;
    if (cb->width < y->width)
        chroma = cb->height < y->height ? CHROMA_420 : CHROMA_422;
    int chroma_subsample_x = chroma != CHROMA_444;
    int chroma_subsample_y = chroma == CHROMA_420;
    int chroma_trellis_policy = trellis_policy == N148_TRELLIS_LEGACY ?
        N148_TRELLIS_LEGACY : N148_TRELLIS_OFF;
    size_t total_modes;
    if (!n148_directional_intra_expected_modes(y->width, y->height, chroma,
                                      &total_modes) ||
        !n148_partition_map_validate(partition_map)) return 0;
    uint8_t *all_modes = (uint8_t *) malloc(total_modes);
    if (!all_modes) return 0;
    size_t y_blocks, chroma_blocks;
    if (!checked_block_count(y->width, y->height, &y_blocks) ||
        !checked_block_count(cb->width, cb->height, &chroma_blocks)) {
        free(all_modes);
        return 0;
    }
    size_t y_mode_count = y_blocks * N148_INTRA_MODE_SLOTS_PER_BLOCK;
    size_t chroma_mode_count = chroma_blocks *
        N148_INTRA_MODE_SLOTS_PER_BLOCK;
    uint8_t *cb_modes = all_modes + y_mode_count;
    uint8_t *cr_modes = cb_modes + chroma_mode_count;
    init_dct_tables();
    int success = quantize_plane(
        y, quality, 0, extended_modes, split_4x4, effort,
        0, loop_filter, calibrated_luma, 0, 0, NULL, partition_map,
        &coefficients[0],
        all_modes, segmentation_map, NULL) &&
        quantize_chroma_pair(
            cb, cr, chroma_quality, extended_modes, effort,
            calibrated_chroma, 0, loop_filter, NULL, partition_map,
            &coefficients[1], cb_modes, cr_modes,
            chroma_subsample_x, chroma_subsample_y, segmentation_map);
    if (success) {
        IntraRateModel rate_model;
        int allowed_modes = luma_mode_count(extended_modes, 8, effort);
        success = build_rate_model(coefficients, all_modes, partition_map,
                                   allowed_modes, 1, NULL, &rate_model);
        for (int plane = 0; plane < 3; plane++)
            n148_free_coeff_plane(&coefficients[plane]);
        memset(all_modes, 0, total_modes);
        memset(partition_map->split, 0, partition_map->count);
        if (success) {
            success = (transform_map ? quantize_variable_luma_plane(
                y, quality, extended_modes, split_4x4, effort,
                trellis_policy, loop_filter, calibrated_luma,
                &rate_model, partition_map, transform_map,
                &coefficients[0], all_modes, segmentation_map) :
                quantize_plane(
                    y, quality, 0, extended_modes, split_4x4, effort,
                    trellis_policy, loop_filter, calibrated_luma, 0, 0,
                    &rate_model, partition_map, &coefficients[0], all_modes,
                    segmentation_map, NULL)) &&
                quantize_chroma_pair(
                    cb, cr, chroma_quality, extended_modes, effort,
                    calibrated_chroma, chroma_trellis_policy, loop_filter,
                    &rate_model, partition_map, &coefficients[1],
                    cb_modes, cr_modes, chroma_subsample_x,
                    chroma_subsample_y, segmentation_map);
        }
        if (success && transform_map &&
            !(effort <= 4 &&
              (fidelity_tools & N148_FIDELITY_FAST_MODE_SEARCH))) {
            IntraRateModel refined_rate_model;
            success = build_rate_model(
                coefficients, all_modes, partition_map, allowed_modes, 1,
                transform_map, &refined_rate_model);
            n148_free_coeff_plane(&coefficients[0]);
            memset(all_modes, 0, y_mode_count);
            memset(partition_map->split, 0,
                   partition_map->plane_offsets[1]);
            memset(transform_map->strategies, N148_TRANSFORM_DCT8,
                   transform_map->count);
            if (success) {
                success = quantize_variable_luma_plane(
                    y, quality, extended_modes, split_4x4, effort,
                    trellis_policy, loop_filter, calibrated_luma,
                    &refined_rate_model, partition_map, transform_map,
                    &coefficients[0], all_modes, segmentation_map);
            }
        }
    }
    if (!success) {
        for (int plane = 0; plane < 3; plane++)
            n148_free_coeff_plane(&coefficients[plane]);
        free(all_modes);
        return 0;
    }
    *modes = all_modes;
    *mode_count = total_modes;
    return 1;
}

static int reconstruct_plane(
    const N148CoeffPlane *coefficients, const uint8_t *modes,
    size_t mode_count, int width, int height, int quality, int plane_index,
    int extended_modes, int split_4x4, int loop_filter,
    int calibrated_quant, int subsample_x, int subsample_y,
    const N148PartitionMap *partition_map,
    const N148SegmentationMap *segmentation_map, Plane *output) {
    size_t blocks;
    if (!coefficients || !coefficients->coefficients || !modes || !output ||
        !partition_map || !checked_block_count(width, height, &blocks) ||
        coefficients->count != (long) blocks ||
        mode_count != blocks * N148_INTRA_MODE_SLOTS_PER_BLOCK ||
        (subsample_x != 0 && subsample_x != 1) ||
        (subsample_y != 0 && subsample_y != 1) ||
        (segmentation_map &&
         !n148_segmentation_map_validate(segmentation_map))) return 0;
    int blocks_x = width / 8 + (width % 8 != 0);
    int blocks_y = height / 8 + (height % 8 != 0);
    if (partition_map->blocks_x[plane_index] != blocks_x ||
        partition_map->blocks_y[plane_index] != blocks_y) return 0;
    *output = create_plane(width, height);
    if (!output->data) return 0;
    IntraQuant8 quant8[N148_SEGMENT_COUNT];
    IntraQuant4 quant4[N148_SEGMENT_COUNT];
    N148LoopFilterPrepared filters[N148_SEGMENT_COUNT];
    const int (*base)[8] = plane_index ?
        (calibrated_quant ? FORMAT_4_CHROMA_QUANT_BASE : Q_CHROMA_BASE) :
        luma_quant_base(calibrated_quant);
    if (!build_segment_decode_quantizers(base, quality, plane_index,
                                         segmentation_map, quant8, quant4) ||
        !prepare_reconstruction_filters(
            quality, plane_index, loop_filter, segmentation_map, filters)) {
        free_plane(output);
        return 0;
    }
    int allowed_modes = plane_index == 0 ? luma_allowed_modes(extended_modes) :
        (extended_modes ? N148_DIRECTIONAL_INTRA_MODE_COUNT : 4);
    int split_allowed_modes = extended_modes ? N148_DIRECTIONAL_INTRA_MODE_COUNT : 4;
    for (int block_y = 0; block_y < blocks_y; block_y++) {
        for (int block_x = 0; block_x < blocks_x; block_x++) {
            long block = (long) block_y * blocks_x + block_x;
            const short *values = coefficients->coefficients + block * 64;
            const uint8_t *block_modes = modes +
                block * N148_INTRA_MODE_SLOTS_PER_BLOCK;
            size_t map_index = partition_map->plane_offsets[plane_index] +
                (size_t) block;
            int use_split = partition_map->split[map_index];
            if ((!split_4x4 && use_split) ||
                (plane_index != 0 && use_split) || use_split > 1) {
                free_plane(output);
                return 0;
            }
            int x0 = block_x * 8;
            int y0 = block_y * 8;
            uint8_t segment = 0;
            if (segmentation_map && !segmentation_level_prevalidated(
                    segmentation_map, block_x, block_y,
                    subsample_x, subsample_y, &segment)) {
                free_plane(output);
                return 0;
            }
            if (use_split) {
                for (int part = 0; part < 4; part++) {
                    int mode = block_modes[part];
                    if (mode < 0 || mode >= split_allowed_modes) {
                        free_plane(output);
                        return 0;
                    }
                    int part_x = x0 + (part & 1) * 4;
                    int part_y = y0 + (part >> 1) * 4;
                    uint8_t prediction[16];
                    predict_square(output, part_x, part_y, 4, mode, 128,
                                   -1, plane_index == 0, prediction);
                    int quant_level = plane_index == 0 ? segment : 0;
                    unsigned int mask = coefficients->nonzero_masks ?
                        (unsigned int)((coefficients->nonzero_masks[block] >>
                            (part * 16)) & 0xffffu) : UINT_MAX;
                    if (!reconstruct4_masked(
                            values + part * 16, prediction,
                            &quant4[quant_level], output,
                            part_x, part_y, mask)) {
                        free_plane(output);
                        return 0;
                    }
                }
            } else {
                int mode = block_modes[0];
                if (mode < 0 || mode >= allowed_modes ||
                    block_modes[1] != mode || block_modes[2] != mode ||
                    block_modes[3] != mode) {
                    free_plane(output);
                    return 0;
                }
                uint8_t prediction[64];
                predict_square(output, x0, y0, 8, mode, 128, -1,
                               plane_index == 0,
                               prediction);
                int quant_level = plane_index == 0 ? segment : 0;
                if (!reconstruct8_masked(
                        values, prediction, &quant8[quant_level], output,
                        x0, y0, coefficients->nonzero_masks ?
                            coefficients->nonzero_masks[block] : ~0ull)) {
                    free_plane(output);
                    return 0;
                }
            }
            if (!filter_reconstructed_prepared(
                    output, x0, y0, 8, loop_filter, segment, filters)) {
                free_plane(output);
                return 0;
            }
        }
    }
    return 1;
}

static int reconstruct_variable_luma_plane(
    const N148CoeffPlane *coefficients, const uint8_t *modes,
    size_t mode_count, int width, int height, int quality,
    int extended_modes, int split_4x4, int loop_filter,
    int calibrated_quant, const N148PartitionMap *partition_map,
    const N148SegmentationMap *segmentation_map,
    const N148TransformMap *transform_map, Plane *output) {
    size_t blocks;
    if (!coefficients || !coefficients->coefficients || !modes || !output ||
        !partition_map || !transform_map ||
        !checked_block_count(width, height, &blocks) ||
        coefficients->count != (long) blocks ||
        mode_count != blocks * N148_INTRA_MODE_SLOTS_PER_BLOCK ||
        !split_4x4 || !fidelity_luma_transform_map_validate(transform_map) ||
        (segmentation_map &&
         !n148_segmentation_map_validate(segmentation_map))) return 0;
    int blocks_x = width / 8 + (width % 8 != 0);
    int blocks_y = height / 8 + (height % 8 != 0);
    if (partition_map->blocks_x[0] != blocks_x ||
        partition_map->blocks_y[0] != blocks_y ||
        transform_map->blocks_x[0] != blocks_x ||
        transform_map->blocks_y[0] != blocks_y) return 0;
    *output = create_plane(width, height);
    if (!output->data) return 0;
    memset(output->data, 128, (size_t) width * (size_t) height);
    IntraQuant8 quant8[N148_SEGMENT_COUNT];
    IntraQuant4 quant4[N148_SEGMENT_COUNT];
    IntraQuant16 quant16[N148_SEGMENT_COUNT];
    IntraQuant32 quant32[N148_SEGMENT_COUNT];
    N148LoopFilterPrepared filters[N148_SEGMENT_COUNT];
    const int (*base)[8] = luma_quant_base(calibrated_quant);
    if (!build_segment_decode_quantizers(base, quality, 0, segmentation_map,
                                         quant8, quant4) ||
        !build_segment_quantizers16(base, quality, segmentation_map,
                                    quant16) ||
        ((fidelity_tools & N148_FIDELITY_DCT32) &&
         !build_segment_quantizers32(base, quality, segmentation_map,
                                     quant32)) ||
        !prepare_reconstruction_filters(
            quality, 0, loop_filter, segmentation_map, filters)) {
        free_plane(output);
        return 0;
    }
    int allowed_modes = luma_allowed_modes(extended_modes);
    int split_allowed_modes = extended_modes ? N148_DIRECTIONAL_INTRA_MODE_COUNT : 4;
    for (int macro_y = 0; macro_y < transform_map->rows[0]; macro_y++) {
        for (int macro_x = 0; macro_x < transform_map->columns[0];
             macro_x++) {
            size_t transform_index = (size_t) macro_y *
                (size_t) transform_map->columns[0] + (size_t) macro_x;
            uint8_t strategy = transform_map->strategies[transform_index];
            int first_block_x = macro_x * 2;
            int first_block_y = macro_y * 2;
            int x0 = first_block_x * 8;
            int y0 = first_block_y * 8;
            if (n148_luma_transform_dct32_member(
                    transform_map, macro_x, macro_y)) {
                if (!n148_luma_transform_dct32_origin(
                        transform_map, macro_x, macro_y)) continue;
                short sequence[32 * 32];
                int mode = -1;
                for (int cell = 0; cell < 16; cell++) {
                    int block_x = first_block_x + (cell & 3);
                    int block_y = first_block_y + (cell >> 2);
                    long block = (long) block_y * blocks_x + block_x;
                    if (partition_map->split[block]) {
                        free_plane(output);
                        return 0;
                    }
                    const uint8_t *block_modes = modes +
                        block * N148_INTRA_MODE_SLOTS_PER_BLOCK;
                    if (block_modes[0] >= allowed_modes ||
                        block_modes[1] != block_modes[0] ||
                        block_modes[2] != block_modes[0] ||
                        block_modes[3] != block_modes[0] ||
                        (mode >= 0 && mode != block_modes[0])) {
                        free_plane(output);
                        return 0;
                    }
                    mode = block_modes[0];
                    memcpy(sequence + cell * 64,
                           coefficients->coefficients + block * 64,
                           64 * sizeof(*sequence));
                }
                uint8_t segment = 0;
                if (segmentation_map && !segmentation_level_prevalidated(
                        segmentation_map, first_block_x, first_block_y,
                        0, 0, &segment)) {
                    free_plane(output);
                    return 0;
                }
                uint8_t prediction[32 * 32];
                predict_square(output, x0, y0, 32, mode, 128, -1, 1,
                               prediction);
                if (!reconstruct32(sequence, prediction, &quant32[segment],
                                   output, x0, y0) ||
                    !filter_reconstructed_prepared(
                        output, x0, y0, 32, loop_filter, segment,
                        filters)) {
                    free_plane(output);
                    return 0;
                }
                continue;
            }
            if (strategy == N148_TRANSFORM_DCT16) {
                if (first_block_x + 1 >= blocks_x ||
                    first_block_y + 1 >= blocks_y) {
                    free_plane(output);
                    return 0;
                }
                short sequence[16 * 16];
                int mode = -1;
                for (int cell = 0; cell < 4; cell++) {
                    int block_x = first_block_x + (cell & 1);
                    int block_y = first_block_y + (cell >> 1);
                    long block = (long) block_y * blocks_x + block_x;
                    if (partition_map->split[block]) {
                        free_plane(output);
                        return 0;
                    }
                    const uint8_t *block_modes = modes +
                        block * N148_INTRA_MODE_SLOTS_PER_BLOCK;
                    if (block_modes[0] >= allowed_modes ||
                        block_modes[1] != block_modes[0] ||
                        block_modes[2] != block_modes[0] ||
                        block_modes[3] != block_modes[0] ||
                        (mode >= 0 && mode != block_modes[0])) {
                        free_plane(output);
                        return 0;
                    }
                    mode = block_modes[0];
                    memcpy(sequence + cell * 64,
                           coefficients->coefficients + block * 64,
                           64 * sizeof(*sequence));
                }
                uint8_t segment = 0;
                if (segmentation_map && !segmentation_level_prevalidated(
                        segmentation_map, first_block_x, first_block_y,
                        0, 0, &segment)) {
                    free_plane(output);
                    return 0;
                }
                uint8_t prediction[16 * 16];
                predict_square(output, x0, y0, 16, mode, 128, -1, 1,
                               prediction);
                unsigned long long masks[4];
                const unsigned long long *block_masks = NULL;
                if (coefficients->nonzero_masks) {
                    for (int cell = 0; cell < 4; cell++) {
                        long index = (long)(first_block_y + (cell >> 1)) *
                            blocks_x + first_block_x + (cell & 1);
                        masks[cell] = coefficients->nonzero_masks[index];
                    }
                    block_masks = masks;
                }
                if (!reconstruct16(sequence, prediction, &quant16[segment],
                                   output, x0, y0, 1, block_masks) ||
                    !filter_reconstructed_prepared(
                        output, x0, y0, 16, loop_filter, segment,
                        filters)) {
                    free_plane(output);
                    return 0;
                }
                continue;
            }
            if (strategy != N148_TRANSFORM_DCT8) {
                free_plane(output);
                return 0;
            }
            for (int cell_y = 0; cell_y < 2; cell_y++) {
                int block_y = first_block_y + cell_y;
                if (block_y >= blocks_y) continue;
                for (int cell_x = 0; cell_x < 2; cell_x++) {
                    int block_x = first_block_x + cell_x;
                    if (block_x >= blocks_x) continue;
                    long block = (long) block_y * blocks_x + block_x;
                    const short *values =
                        coefficients->coefficients + block * 64;
                    const uint8_t *block_modes = modes +
                        block * N148_INTRA_MODE_SLOTS_PER_BLOCK;
                    int use_split = partition_map->split[block];
                    if (use_split > 1) {
                        free_plane(output);
                        return 0;
                    }
                    int block_x0 = block_x * 8;
                    int block_y0 = block_y * 8;
                    uint8_t segment = 0;
                    if (segmentation_map &&
                        !segmentation_level_prevalidated(
                            segmentation_map, block_x, block_y, 0, 0,
                            &segment)) {
                        free_plane(output);
                        return 0;
                    }
                    if (use_split) {
                        for (int part = 0; part < 4; part++) {
                            int part_mode = block_modes[part];
                            if (part_mode < 0 ||
                                part_mode >= split_allowed_modes) {
                                free_plane(output);
                                return 0;
                            }
                            int part_x = block_x0 + (part & 1) * 4;
                            int part_y = block_y0 + (part >> 1) * 4;
                            uint8_t prediction[16];
                            predict_square(output, part_x, part_y, 4,
                                           part_mode, 128,
                                           first_block_x * 8 + 15,
                                           1,
                                           prediction);
                            unsigned int mask = coefficients->nonzero_masks ?
                                (unsigned int)(
                                    (coefficients->nonzero_masks[block] >>
                                        (part * 16)) & 0xffffu) : UINT_MAX;
                            if (!reconstruct4_masked(
                                    values + part * 16, prediction,
                                    &quant4[segment], output, part_x,
                                    part_y, mask)) {
                                free_plane(output);
                                return 0;
                            }
                        }
                    } else {
                        int block_mode = block_modes[0];
                        if (block_mode < 0 || block_mode >= allowed_modes ||
                            block_modes[1] != block_mode ||
                            block_modes[2] != block_mode ||
                            block_modes[3] != block_mode) {
                            free_plane(output);
                            return 0;
                        }
                        uint8_t prediction[64];
                        predict_square(output, block_x0, block_y0, 8,
                                       block_mode, 128,
                                       first_block_x * 8 + 15,
                                       1,
                                       prediction);
                        if (!reconstruct8_masked(
                                values, prediction, &quant8[segment], output,
                                block_x0, block_y0,
                                coefficients->nonzero_masks ?
                                    coefficients->nonzero_masks[block] :
                                    ~0ull)) {
                            free_plane(output);
                            return 0;
                        }
                    }
                    if (!filter_reconstructed_prepared(
                            output, block_x0, block_y0, 8, loop_filter,
                            segment, filters)) {
                        free_plane(output);
                        return 0;
                    }
                }
            }
        }
    }
    return 1;
}

int n148_directional_intra_reconstruct_planes(
    const N148CoeffPlane coefficients[3], const uint8_t *modes,
    size_t mode_count, int width, int height, int quality,
    int chroma_quality, int calibrated_chroma, int calibrated_luma, int chroma,
    int extended_modes, int split_4x4, int loop_filter,
    const N148PartitionMap *partition_map,
    const N148SegmentationMap *segmentation_map,
    const N148TransformMap *transform_map,
    Plane *y, Plane *cb, Plane *cr) {
    if (!coefficients || !modes || !partition_map || !y || !cb || !cr ||
        width <= 0 || height <= 0 || quality < 1 || quality > 100 ||
        chroma_quality < 1 || chroma_quality > 100 ||
        (calibrated_chroma != 0 && calibrated_chroma != 1) ||
        (calibrated_luma != 0 && calibrated_luma != 1) ||
        loop_filter < N148_LOOP_FILTER_OFF ||
        loop_filter > N148_LOOP_FILTER_QUANT_ADAPTIVE_LUMA ||
        chroma < CHROMA_444 || chroma > CHROMA_420 ||
        !n148_partition_map_validate(partition_map) ||
        (segmentation_map &&
         !n148_segmentation_map_validate(segmentation_map)) ||
        (transform_map &&
         (!split_4x4 ||
          !fidelity_luma_transform_map_validate(transform_map)))) return 0;
    *y = (Plane){0};
    *cb = (Plane){0};
    *cr = (Plane){0};
    int chroma_width, chroma_height;
    chroma_dimensions(chroma, width, height, &chroma_width, &chroma_height);
    int chroma_subsample_x = chroma != CHROMA_444;
    int chroma_subsample_y = chroma == CHROMA_420;
    size_t y_blocks, chroma_blocks, expected_modes;
    if (!checked_block_count(width, height, &y_blocks) ||
        !checked_block_count(chroma_width, chroma_height, &chroma_blocks) ||
        !n148_directional_intra_expected_modes(width, height, chroma,
                                      &expected_modes) ||
        mode_count != expected_modes) return 0;
    size_t y_modes = y_blocks * N148_INTRA_MODE_SLOTS_PER_BLOCK;
    size_t chroma_modes = chroma_blocks * N148_INTRA_MODE_SLOTS_PER_BLOCK;
    int success = (transform_map ? reconstruct_variable_luma_plane(
        &coefficients[0], modes, y_modes, width, height, quality,
        extended_modes, split_4x4, loop_filter, calibrated_luma,
        partition_map, segmentation_map, transform_map, y) :
        reconstruct_plane(
            &coefficients[0], modes, y_modes, width, height, quality, 0,
            extended_modes, split_4x4, loop_filter, calibrated_luma, 0, 0,
            partition_map, segmentation_map, y)) &&
        reconstruct_plane(
            &coefficients[1], modes + y_modes, chroma_modes,
            chroma_width, chroma_height, chroma_quality, 1, extended_modes,
            split_4x4, loop_filter, calibrated_chroma,
            chroma_subsample_x, chroma_subsample_y, partition_map,
            segmentation_map, cb) &&
        reconstruct_plane(
            &coefficients[2], modes + y_modes + chroma_modes, chroma_modes,
            chroma_width, chroma_height, chroma_quality, 2, extended_modes,
            split_4x4, loop_filter, calibrated_chroma,
            chroma_subsample_x, chroma_subsample_y, partition_map,
            segmentation_map, cr);
    if (!success) {
        free_plane(y);
        free_plane(cb);
        free_plane(cr);
    }
    return success;
}

src/quantize4_avx2.inc

O quantize4_avx2.inc é incluído pelo directional_intra.c e traz as versões em AVX2 do resíduo e da quantização dos blocos de 4x4.

O arquivo completo tem 53 linhas:

#if defined(__x86_64__) || defined(__i386__)
__attribute__((target("avx2")))
static void residual4_avx2(const Plane *source, int x0, int y0,
    const uint8_t prediction[16], int32_t residual[16]) {
    for (int row=0;row<4;row++) {
        uint32_t src,pred;
        memcpy(&src,source->data+(long)(y0+row)*source->width+x0,4);
        memcpy(&pred,prediction+row*4,4);
        __m128i a=_mm_cvtepu8_epi32(_mm_cvtsi32_si128((int)src));
        __m128i b=_mm_cvtepu8_epi32(_mm_cvtsi32_si128((int)pred));
        _mm_storeu_si128((__m128i *)(residual+row*4),_mm_sub_epi32(a,b));
    }
}

/* The uint32 reciprocal and one correction reproduce the scalar integer
   division, including asymmetric signed-short limits. */
__attribute__((target("avx2")))
static int quantize4_avx2(const int32_t transformed[16],
    const IntraQuant4 *quant, short output[16], float ideal_levels[16]) {
    int32_t natural_levels[16];float natural_ideal[16];
    const __m256i signbit=_mm256_set1_epi32(INT32_MIN);
    for (int k=0;k<16;k+=8) {
        __m256i value=_mm256_loadu_si256((const __m256i *)(transformed+k));
        __m256i step=_mm256_loadu_si256((const __m256i *)(quant->step+k));
        __m256i reciprocal=_mm256_loadu_si256((const __m256i *)(quant->reciprocal_q32+k));
        __m256i negative=_mm256_srai_epi32(value,31);
        __m256i absolute=_mm256_abs_epi32(value);
        __m256i rounded=_mm256_add_epi32(absolute,_mm256_srli_epi32(step,1));
        __m256i even=_mm256_srli_epi64(_mm256_mul_epu32(rounded,reciprocal),32);
        __m256i odd=_mm256_mul_epu32(_mm256_srli_epi64(rounded,32),
                                     _mm256_srli_epi64(reciprocal,32));
        __m256i level=_mm256_or_si256(even,_mm256_and_si256(odd,
                                       _mm256_set1_epi64x(-4294967296ll)));
        __m256i remainder=_mm256_sub_epi32(rounded,_mm256_mullo_epi32(level,step));
        __m256i adjust=_mm256_cmpgt_epi32(remainder,_mm256_sub_epi32(step,_mm256_set1_epi32(1)));
        level=_mm256_sub_epi32(level,adjust);
        __m256i limit=_mm256_sub_epi32(_mm256_set1_epi32(32767),negative);
        __m256i overflow=_mm256_cmpgt_epi32(_mm256_xor_si256(level,signbit),
                                          _mm256_xor_si256(limit,signbit));
        if (_mm256_movemask_epi8(overflow)) return 0;
        __m256i signed_level=_mm256_sub_epi32(_mm256_xor_si256(level,negative),negative);
        _mm256_storeu_si256((__m256i *)(natural_levels+k),signed_level);
        if (ideal_levels) _mm256_storeu_ps(natural_ideal+k,
            _mm256_div_ps(_mm256_cvtepi32_ps(value),_mm256_cvtepi32_ps(step)));
    }
    for(int k=0;k<16;k++) {
        int natural=n148_variable_zigzag(4,k);
        output[k]=(short)natural_levels[natural];
        if(ideal_levels)ideal_levels[k]=natural_ideal[natural];
    }
    return 1;
}
#endif

Novos na pasta src: o RDO e as transformadas

src/rdo.h

O rdo.h é a interface das ferramentas de taxa e distorção do artigo 32, como a estimativa de bits de um bloco e o refinamento dos coeficientes.

O arquivo completo tem 45 linhas:

/*
 * N.148i rate-distortion optimization helpers.
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#ifndef N148_RDO_H
#define N148_RDO_H

#include <stdint.h>

typedef struct {
    uint32_t input_nonzeros;
    uint32_t output_nonzeros;
    uint32_t changed_coefficients;
    double input_cost;
    double output_cost;
} N148RdoResult;

/* Estimate the coefficient portion of the existing rANS syntax. The estimate
   includes amplitude bits and inexpensive proxies for AC symbols and EOB. */
double n148_rdo_estimate_block_bits(const short coefficients[64]);

/* Return the proxy minimized by the trellis for AC coefficients. */
double n148_rdo_proxy_cost(const float ideal_levels[64],
                           const double unit_energy[64],
                           const short coefficients[64], double lambda);

/* Refine one quantized block. DC remains fixed because changing it affects
   causal prediction much more strongly than the separable AC proxy models. */
int n148_rdo_refine_coefficients(const float ideal_levels[64],
                                 const double unit_energy[64],
                                 double lambda, int effort,
                                 short coefficients[64],
                                 N148RdoResult *result);

/* Internal encoder path for freshly computed, finite transform data. */
int n148_rdo_refine_coefficients_trusted(const float ideal_levels[64],
                                         const double unit_energy[64],
                                         double lambda, int effort,
                                         short coefficients[64],
                                         N148RdoResult *result);

#endif

src/rdo.c

O rdo.c implementa o trellis, um programa dinâmico pequeno que decide quais coeficientes vale a pena diminuir ou zerar quando os bits economizados pagam o erro a mais.

O arquivo completo tem 336 linhas:

/*
 * N.148i rate-distortion trellis.
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 *
 * This is an original, deliberately small dynamic program over the existing
 * run/category syntax. It is not copied from a reference codec.
 */

#include "rdo.h"

#include <float.h>
#include <limits.h>
#include <math.h>
#include <stddef.h>
#include <string.h>

#define N148_RDO_EOB_BITS 0.75
#define N148_RDO_SYMBOL_BITS 2.25
#define N148_RDO_ZRL_BITS 1.25
#define N148_RDO_RUN_FRACTION 0.08

/* Category one is used for every predecessor comparison. These rounded
   constants match ac_event_bits_category() for each run exactly, including
   its floating-point evaluation order. */
static const double predecessor_run_bits[64] = {
    3.25, 3.33, 3.41, 3.49, 3.57, 3.65, 3.73, 3.81,
    3.89, 3.9699999999999998, 4.05, 4.13, 4.21, 4.29, 4.37, 4.45,
    4.5, 4.58, 4.66, 4.74, 4.82, 4.9, 4.98, 5.0600000000000005,
    5.14, 5.22, 5.3, 5.38, 5.46, 5.54, 5.62, 5.7,
    5.75, 5.83, 5.91, 5.99, 6.07, 6.15, 6.23, 6.3100000000000005,
    6.39, 6.47, 6.55, 6.63, 6.71, 6.79, 6.87, 6.95,
    7, 7.08, 7.16, 7.24, 7.32, 7.4, 7.48, 7.5600000000000005,
    7.64, 7.72, 7.8, 7.88, 7.96, 8.04, 8.120000000000001, 8.2,
};

static int coefficient_category(short value) {
    unsigned int magnitude = value < 0 ?
        0u - (unsigned int)value : (unsigned int)value;
#if defined(__GNUC__) || defined(__clang__)
    return magnitude ? (int)(sizeof(magnitude) * CHAR_BIT) -
        __builtin_clz(magnitude) : 0;
#else
    int bits = 0;
    while (magnitude) { magnitude >>= 1; bits++; }
    return bits;
#endif
}

static double ac_event_bits_category(int zero_run, int category) {
    if (zero_run < 0 || category <= 0) return DBL_MAX;
    int zrl_count = zero_run / 16;
    int residual_run = zero_run & 15;
    return zrl_count * N148_RDO_ZRL_BITS + N148_RDO_SYMBOL_BITS + category +
        residual_run * N148_RDO_RUN_FRACTION;
}

static double ac_event_bits(int zero_run, short value) {
    return ac_event_bits_category(zero_run, coefficient_category(value));
}

static double estimate_ac_bits(const short coefficients[64]) {
    int next_position = 1;
    double bits = 0.0;
    for (int position = 1; position < 64; position++) {
        if (coefficients[position] == 0) continue;
        bits += ac_event_bits(position - next_position,
                              coefficients[position]);
        next_position = position + 1;
    }
    if (next_position < 64) bits += N148_RDO_EOB_BITS;
    return bits;
}

double n148_rdo_estimate_block_bits(const short coefficients[64]) {
    if (!coefficients) return DBL_MAX;
    return N148_RDO_SYMBOL_BITS + coefficient_category(coefficients[0]) +
        estimate_ac_bits(coefficients);
}

static double coefficient_distortion(float ideal, short quantized,
                                     double energy) {
    double difference = (double) ideal - quantized;
    return difference * difference * energy;
}

static double proxy_cost_validated(const float ideal_levels[64],
                                   const double unit_energy[64],
                                   const short coefficients[64],
                                   double lambda) {
    double distortion = 0.0;
    double bits = 0.0;
    int next_position = 1;
    for (int position = 1; position < 64; position++) {
        distortion += coefficient_distortion(
            ideal_levels[position], coefficients[position],
            unit_energy[position]);
        if (coefficients[position] != 0) {
            bits += ac_event_bits(position - next_position,
                                  coefficients[position]);
            next_position = position + 1;
        }
    }
    if (next_position < 64) bits += N148_RDO_EOB_BITS;
    return distortion + lambda * bits;
}

double n148_rdo_proxy_cost(const float ideal_levels[64],
                           const double unit_energy[64],
                           const short coefficients[64], double lambda) {
    if (!ideal_levels || !unit_energy || !coefficients ||
        !isfinite(lambda) || lambda < 0.0) return DBL_MAX;
    for (int position = 1; position < 64; position++) {
        if (!isfinite(ideal_levels[position]) ||
            !isfinite(unit_energy[position]) || unit_energy[position] < 0.0)
            return DBL_MAX;
    }
    return proxy_cost_validated(
        ideal_levels, unit_energy, coefficients, lambda);
}

static int add_candidate(short candidates[3], int count, int value) {
    if (value == 0 || value < SHRT_MIN || value > SHRT_MAX) return count;
    for (int index = 0; index < count; index++)
        if (candidates[index] == value) return count;
    if (count < 3) candidates[count++] = (short) value;
    return count;
}

static int candidates_for_position(float ideal, short rounded, int effort,
                                   short candidates[3]) {
    int count = 0;
    count = add_candidate(candidates, count, rounded);
    if (rounded > 1) count = add_candidate(candidates, count, rounded - 1);
    if (rounded < -1) count = add_candidate(candidates, count, rounded + 1);
    if (effort >= 8) {
        if (rounded > 0)
            count = add_candidate(candidates, count, (int) rounded + 1);
        else if (rounded < 0)
            count = add_candidate(candidates, count, (int) rounded - 1);
        else if (fabsf(ideal) >= 0.35f)
            count = add_candidate(candidates, count, ideal < 0.0f ? -1 : 1);
    }
    return count;
}

static uint32_t nonzero_count(const short coefficients[64]) {
    uint32_t count = 0;
    for (int position = 1; position < 64; position++)
        count += coefficients[position] != 0;
    return count;
}

static int refine_coefficients_core(const float ideal_levels[64],
                                    const double unit_energy[64],
                                    double lambda, int effort,
                                    short coefficients[64],
                                    N148RdoResult *result,
                                    int verify_result) {
    /* At efforts 3 and 4, zero AC coefficients have no nonzero trellis
       candidate. An entirely empty AC block must therefore remain empty;
       avoid building its cost table and predecessor graph. The public path
       still runs its full validation and result accounting. */
    if ((effort == 3 || effort == 4) && !verify_result && !result) {
        int any_ac = 0;
        for (int position = 1; position < 64; position++)
            any_ac |= coefficients[position];
        if (!any_ac) return 1;
    }
    short input[64];
    const short *initial = coefficients;
    if (verify_result || result) {
        memcpy(input, coefficients, sizeof(input));
        initial = input;
    }
    double zero_prefix[65] = {0.0};
    for (int position = 1; position < 64; position++) {
        zero_prefix[position + 1] = zero_prefix[position] +
            coefficient_distortion(ideal_levels[position], 0,
                                   unit_energy[position]);
    }

    int previous_position[64];
    short ending_value[64];
    int active_positions[64];
    double active_best[64];
    double active_zero_after[64];
    double prefix_minimum[64], prefix_magnitude[64];
    int active_count = 0;

    for (int position = 1; position < 64; position++) {
        /* Below effort 8 a zero rounded AC level has no nonzero candidate.
           Keep the predecessor graph restricted to positions that can be
           selected; zero_prefix still accounts for every skipped level. */
        if (effort < 8 && initial[position] == 0) continue;
        short candidates[3];
        int candidate_count = candidates_for_position(
            ideal_levels[position], initial[position], effort, candidates);
        if (candidate_count == 0) continue;
        double best_ending = DBL_MAX;
        previous_position[position] = -1;
        ending_value[position] = 0;
        /* Every candidate at this position adds its own distortion and
           coefficient category to the same predecessor path. Select that
           path once, then evaluate each candidate with its exact rate. */
        int best_predecessor = -1;
        double best_predecessor_cost = DBL_MAX;
        for (int active = active_count-1; active >= 0; active--) {
            double bound = prefix_minimum[active] + zero_prefix[position] + lambda * 3.25;
            double slack = 64.0 * DBL_EPSILON * (prefix_magnitude[active] +
                zero_prefix[position] + fabs(best_predecessor_cost) + lambda * 3.25 + 1.0);
            if (bound > best_predecessor_cost + slack) break;
            int previous = active_positions[active];
            double cost = active_best[active] +
                zero_prefix[position] - active_zero_after[active] +
                lambda * predecessor_run_bits[
                    position - previous - 1];
            if (cost < best_predecessor_cost || (cost == best_predecessor_cost &&
                best_predecessor >= 0 && active < best_predecessor)) {
                best_predecessor_cost = cost;
                best_predecessor = active;
            }
        }
        for (int candidate_index = 0; candidate_index < candidate_count;
             candidate_index++) {
            short value = candidates[candidate_index];
            int category = coefficient_category(value);
            double distortion = coefficient_distortion(
                ideal_levels[position], value, unit_energy[position]);
            double cost = zero_prefix[position] - zero_prefix[1] + distortion +
                lambda * ac_event_bits_category(position - 1, category);
            int predecessor = -1;
            if (best_predecessor >= 0) {
                int previous = active_positions[best_predecessor];
                double candidate_cost = active_best[best_predecessor] +
                    zero_prefix[position] -
                    active_zero_after[best_predecessor] +
                    distortion + lambda * ac_event_bits_category(
                        position - previous - 1, category);
                if (candidate_cost < cost) {
                    cost = candidate_cost;
                    predecessor = previous;
                }
            }
            if (cost < best_ending) {
                best_ending = cost;
                previous_position[position] = predecessor;
                ending_value[position] = value;
            }
        }
        if (best_ending != DBL_MAX) {
            active_positions[active_count] = position;
            active_best[active_count] = best_ending;
            active_zero_after[active_count] = zero_prefix[position + 1];
            double base = best_ending - zero_prefix[position + 1];
            double magnitude = fabs(best_ending) + zero_prefix[position + 1];
            if (active_count) {
                if (prefix_minimum[active_count-1] < base) base = prefix_minimum[active_count-1];
                if (prefix_magnitude[active_count-1] > magnitude) magnitude = prefix_magnitude[active_count-1];
            }
            prefix_minimum[active_count] = base;
            prefix_magnitude[active_count] = magnitude;
            active_count++;
        }
    }

    double best_cost = zero_prefix[64] - zero_prefix[1] +
        lambda * N148_RDO_EOB_BITS;
    int last_position = -1;
    for (int active = 0; active < active_count; active++) {
        int position = active_positions[active];
        double cost = active_best[active] +
            zero_prefix[64] - zero_prefix[position + 1];
        if (position < 63) cost += lambda * N148_RDO_EOB_BITS;
        if (cost < best_cost) {
            best_cost = cost;
            last_position = position;
        }
    }

    memset(coefficients + 1, 0, 63 * sizeof(*coefficients));
    while (last_position >= 1) {
        coefficients[last_position] = ending_value[last_position];
        last_position = previous_position[last_position];
    }

    if (verify_result || result) {
        double input_cost = proxy_cost_validated(
            ideal_levels, unit_energy, input, lambda);
        double output_cost = proxy_cost_validated(
            ideal_levels, unit_energy, coefficients, lambda);
        double tolerance = 1e-9 * (fabs(input_cost) + 1.0);
        if (!isfinite(input_cost) || !isfinite(output_cost) ||
            output_cost > input_cost + tolerance) {
            memcpy(coefficients, input, sizeof(input));
            return 0;
        }
        if (!result) return 1;
        memset(result, 0, sizeof(*result));
        result->input_nonzeros = nonzero_count(input);
        result->output_nonzeros = nonzero_count(coefficients);
        for (int position = 1; position < 64; position++)
            result->changed_coefficients +=
                input[position] != coefficients[position];
        result->input_cost = input_cost;
        result->output_cost = output_cost;
    }
    return 1;
}

int n148_rdo_refine_coefficients_trusted(const float ideal_levels[64],
                                          const double unit_energy[64],
                                          double lambda, int effort,
                                          short coefficients[64],
                                          N148RdoResult *result) {
    return refine_coefficients_core(
        ideal_levels, unit_energy, lambda, effort, coefficients, result,
        result != NULL);
}

int n148_rdo_refine_coefficients(const float ideal_levels[64],
                                  const double unit_energy[64],
                                  double lambda, int effort,
                                  short coefficients[64],
                                  N148RdoResult *result) {
    if (!ideal_levels || !unit_energy || !coefficients || effort < 0 ||
        effort > 9 || !isfinite(lambda) || lambda < 0.0) return 0;
    for (int position = 0; position < 64; position++) {
        if (!isfinite(ideal_levels[position]) ||
            !isfinite(unit_energy[position]) || unit_energy[position] < 0.0)
            return 0;
    }
    return refine_coefficients_core(
        ideal_levels, unit_energy, lambda, effort, coefficients, result, 1);
}

src/variable_transform.h

O variable_transform.h é a interface das transformadas de tamanho variável do artigo 33, com o mapa que guarda o tamanho escolhido em cada região.

O arquivo completo tem 89 linhas:

/*
 * N.148i variable transform strategies.
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#ifndef N148_VARIABLE_TRANSFORM_H
#define N148_VARIABLE_TRANSFORM_H

#include <stddef.h>
#include <stdint.h>

#include "ppm.h"

#define N148_TRANSFORM_REGION_SIZE 16
#define N148_TRANSFORM_STRATEGY_COUNT 3
#define N148_TRANSFORM_INITIAL_STRATEGY N148_TRANSFORM_DCT8

enum {
    N148_TRANSFORM_DCT4 = 0,
    N148_TRANSFORM_DCT8 = 1,
    N148_TRANSFORM_DCT16 = 2,
};

/* Strategies are concatenated in Y, Cb, Cr order. Geometry is retained so
   prediction never crosses a plane boundary and edge DCT16 entries can be
   rejected before coefficient reconstruction. */
typedef struct {
    uint8_t *strategies;
    size_t count;
    size_t plane_offsets[3];
    int columns[3];
    int rows[3];
    int blocks_x[3];
    int blocks_y[3];
} N148TransformMap;

int n148_transform_map_allocate(int width, int height, int chroma,
                                N148TransformMap *map);
int n148_transform_map_build(const Plane *y, const Plane *cb, const Plane *cr,
                             N148TransformMap *map);
int n148_transform_map_validate(const N148TransformMap *map);
/* The variable-luma profile uses DCT8/DCT16 in luma and leaves chroma at DCT8. */
int n148_luma_transform_map_validate(const N148TransformMap *map);
/* Format 6 represents one 32x32 luma transform as a canonical aligned 2x2 group
   of DCT4 map symbols. DCT4 was unreachable in the format 5 luma grammar, so the
   marker extends the existing three-symbol entropy alphabet without changing
   any format 1-5 syntax. */
int n148_luma_transform_map_validate_extended(const N148TransformMap *map,
                                               int allow_dct32);
int n148_luma_transform_dct32_origin(const N148TransformMap *map,
                                     int macro_x, int macro_y);
int n148_luma_transform_dct32_member(const N148TransformMap *map,
                                     int macro_x, int macro_y);
uint8_t n148_transform_map_predict(const N148TransformMap *map,
                                   size_t index);
int n148_transform_strategy_at(const N148TransformMap *map, int plane,
                               int macro_x, int macro_y, uint8_t *strategy);
void n148_transform_map_release(N148TransformMap *map);

/* Normative Q14 integer DCT primitives used by the 4x4, 16x16, and format 6 32x32
   strategies. Input and output arrays are row-major and may alias. */
/* Continuous synthesis energy of the native 4x4 Q14 basis at a positive
   quantizer step. Used only for encoder distortion costs, before rounding. */
double n148_variable_dct4_energy(int natural, int step);
int n148_variable_forward(const int32_t *input, int size, int32_t *output);
int n148_variable_inverse(const int32_t *input, int size, int32_t *output);
/* The caller supplies exact nonzero frequency-row and frequency-column masks
   for the 16x16 input. */
int n148_variable_inverse_sparse16(const int32_t input[16 * 16],
                                   uint32_t active_rows,
                                   uint32_t active_columns,
                                   int32_t output[16 * 16]);
extern const uint16_t N148_ZIGZAG_4[16];
extern const uint16_t N148_ZIGZAG_16[256];
extern const uint16_t N148_ZIGZAG_32[1024];

static inline int n148_variable_zigzag(int size, int position) {
    if ((size != 4 && size != 16 && size != 32) || position < 0 ||
        position >= size * size) return -1;
    if (size == 4) return N148_ZIGZAG_4[position];
    if (size == 16) return N148_ZIGZAG_16[position];
    return N148_ZIGZAG_32[position];
}
uint64_t n148_variable_transform_matrix_hash(void);
uint64_t n148_variable_transform_matrix32_hash(void);

#endif

src/variable_transform.c

O variable_transform.c implementa as DCTs inteiras de 4x4, 16x16 e 32x32 e o mapa de tamanhos, incluindo a de 32x32 que ficou no cemitério de ideias e continua disponível como experimento.

O arquivo completo tem 946 linhas:

/*
 * N.148i variable transform map and deterministic integer DCT.
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 *
 * The implementation is intentionally compact and original. Literal Q14
 * matrices make the transform independent of the platform math library.
 */

#include "variable_transform.h"

#include <limits.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#include "cpu.h"
#include "header.h"

#if defined(__x86_64__) || defined(__i386__)
#include <immintrin.h>
#endif

#define N148_DCT_SCALE_SQUARED 268435456ll
#if defined(__x86_64__) || defined(__i386__)
#include "dct_forward_transposes.inc"
#endif

static const int16_t DCT4_Q14[4][4] = {
    {8192, 8192, 8192, 8192},
    {10703, 4433, -4433, -10703},
    {8192, -8192, -8192, 8192},
    {4433, -10703, 10703, -4433},
};

/* Continuous synthesis energy of our native Q14 basis, before
   rounding to integer samples. This stays positive even at unit steps. */
double n148_variable_dct4_energy(int natural, int step) {
    double row_norm = 0.0, column_norm = 0.0;
    for (int sample = 0; sample < 4; ++sample) {
        double row = DCT4_Q14[natural / 4][sample];
        double column = DCT4_Q14[natural % 4][sample];
        row_norm += row * row;
        column_norm += column * column;
    }
    return (double)step * step *
        (row_norm / 268435456.0) * (column_norm / 268435456.0);
}

static const int16_t DCT16_Q14[16][16] = {
    {4096,4096,4096,4096,4096,4096,4096,4096,
     4096,4096,4096,4096,4096,4096,4096,4096},
    {5765,5543,5109,4478,3675,2731,1682,568,
     -568,-1682,-2731,-3675,-4478,-5109,-5543,-5765},
    {5681,4816,3218,1130,-1130,-3218,-4816,-5681,
     -5681,-4816,-3218,-1130,1130,3218,4816,5681},
    {5543,3675,568,-2731,-5109,-5765,-4478,-1682,
     1682,4478,5765,5109,2731,-568,-3675,-5543},
    {5352,2217,-2217,-5352,-5352,-2217,2217,5352,
     5352,2217,-2217,-5352,-5352,-2217,2217,5352},
    {5109,568,-4478,-5543,-1682,3675,5765,2731,
     -2731,-5765,-3675,1682,5543,4478,-568,-5109},
    {4816,-1130,-5681,-3218,3218,5681,1130,-4816,
     -4816,1130,5681,3218,-3218,-5681,-1130,4816},
    {4478,-2731,-5543,568,5765,1682,-5109,-3675,
     3675,5109,-1682,-5765,-568,5543,2731,-4478},
    {4096,-4096,-4096,4096,4096,-4096,-4096,4096,
     4096,-4096,-4096,4096,4096,-4096,-4096,4096},
    {3675,-5109,-1682,5765,-568,-5543,2731,4478,
     -4478,-2731,5543,568,-5765,1682,5109,-3675},
    {3218,-5681,1130,4816,-4816,-1130,5681,-3218,
     -3218,5681,-1130,-4816,4816,1130,-5681,3218},
    {2731,-5765,3675,1682,-5543,4478,568,-5109,
     5109,-568,-4478,5543,-1682,-3675,5765,-2731},
    {2217,-5352,5352,-2217,-2217,5352,-5352,2217,
     2217,-5352,5352,-2217,-2217,5352,-5352,2217},
    {1682,-4478,5765,-5109,2731,568,-3675,5543,
     -5543,3675,-568,-2731,5109,-5765,4478,-1682},
    {1130,-3218,4816,-5681,5681,-4816,3218,-1130,
     -1130,3218,-4816,5681,-5681,4816,-3218,1130},
    {568,-1682,2731,-3675,4478,-5109,5543,-5765,
     5765,-5543,5109,-4478,3675,-2731,1682,-568},
};

#include "dct32_q14.inc"

static int checked_plane_geometry(int width, int height, int *blocks_x,
                                  int *blocks_y, int *columns, int *rows,
                                  size_t *count) {
    if (width <= 0 || height <= 0 || !blocks_x || !blocks_y || !columns ||
        !rows || !count) return 0;
    *blocks_x = width / 8 + (width % 8 != 0);
    *blocks_y = height / 8 + (height % 8 != 0);
    *columns = (*blocks_x + 1) / 2;
    *rows = (*blocks_y + 1) / 2;
    if (*columns <= 0 || *rows <= 0 ||
        (size_t) *columns > SIZE_MAX / (size_t) *rows) return 0;
    *count = (size_t) *columns * (size_t) *rows;
    return *count <= UINT32_MAX;
}

int n148_transform_map_allocate(int width, int height, int chroma,
                                N148TransformMap *map) {
    if (!map || chroma < CHROMA_444 || chroma > CHROMA_420) return 0;
    memset(map, 0, sizeof(*map));
    int chroma_width, chroma_height;
    chroma_dimensions(chroma, width, height, &chroma_width, &chroma_height);
    int widths[3] = {width, chroma_width, chroma_width};
    int heights[3] = {height, chroma_height, chroma_height};
    size_t total = 0;
    for (int plane = 0; plane < 3; plane++) {
        size_t plane_count;
        map->plane_offsets[plane] = total;
        if (!checked_plane_geometry(
                widths[plane], heights[plane], &map->blocks_x[plane],
                &map->blocks_y[plane], &map->columns[plane],
                &map->rows[plane], &plane_count) ||
            plane_count > SIZE_MAX - total) {
            memset(map, 0, sizeof(*map));
            return 0;
        }
        total += plane_count;
    }
    if (total == 0 || total > UINT32_MAX) {
        memset(map, 0, sizeof(*map));
        return 0;
    }
    map->strategies = (uint8_t *) malloc(total);
    if (!map->strategies) {
        memset(map, 0, sizeof(*map));
        return 0;
    }
    memset(map->strategies, N148_TRANSFORM_INITIAL_STRATEGY, total);
    map->count = total;
    return 1;
}

static uint16_t transform_activity(const Plane *plane, int x0, int y0) {
    int x1 = x0 + N148_TRANSFORM_REGION_SIZE;
    int y1 = y0 + N148_TRANSFORM_REGION_SIZE;
    if (x1 > plane->width) x1 = plane->width;
    if (y1 > plane->height) y1 = plane->height;
    uint32_t total = 0;
    uint32_t samples = 0;
    for (int y = y0; y < y1; y++) {
        const uint8_t *row = plane->data + (long) y * plane->width;
        for (int x = x0; x < x1; x++) {
            if (x >= x0 + 2) {
                int value = (int) row[x] - 2 * (int) row[x - 1] + row[x - 2];
                if (value < 0) value = -value;
                if (value > 32) value = 32;
                total += (uint32_t) value;
                samples++;
            }
            if (y >= y0 + 2) {
                int value = (int) row[x] -
                    2 * (int) plane->data[(long)(y - 1) * plane->width + x] +
                    plane->data[(long)(y - 2) * plane->width + x];
                if (value < 0) value = -value;
                if (value > 32) value = 32;
                total += (uint32_t) value;
                samples++;
            }
        }
    }
    return samples ? (uint16_t)((total * 256u + samples / 2u) / samples) : 0;
}

static int build_plane_map(const Plane *plane, int plane_index,
                           N148TransformMap *map) {
    if (!plane || !plane->data || !map || plane_index < 0 || plane_index > 2)
        return 0;
    for (int row = 0; row < map->rows[plane_index]; row++) {
        for (int column = 0; column < map->columns[plane_index]; column++) {
            size_t index = map->plane_offsets[plane_index] +
                (size_t) row * (size_t) map->columns[plane_index] +
                (size_t) column;
            uint16_t activity = transform_activity(
                plane, column * N148_TRANSFORM_REGION_SIZE,
                row * N148_TRANSFORM_REGION_SIZE);
            int complete = column * 2 + 1 < map->blocks_x[plane_index] &&
                row * 2 + 1 < map->blocks_y[plane_index];
            map->strategies[index] = plane_index == 0 && complete &&
                activity == 0 ? N148_TRANSFORM_DCT16 :
                activity >= 31u * 256u ? N148_TRANSFORM_DCT4 :
                                         N148_TRANSFORM_DCT8;
        }
    }
    return 1;
}

int n148_transform_map_build(const Plane *y, const Plane *cb, const Plane *cr,
                             N148TransformMap *map) {
    if (!y || !cb || !cr || !map || !y->data || !cb->data || !cr->data ||
        cb->width != cr->width || cb->height != cr->height) return 0;
    int chroma = CHROMA_444;
    if (cb->width < y->width) chroma = cb->height < y->height ?
        CHROMA_420 : CHROMA_422;
    if (!n148_transform_map_allocate(y->width, y->height, chroma, map) ||
        map->blocks_x[1] != cb->width / 8 + (cb->width % 8 != 0) ||
        map->blocks_y[1] != cb->height / 8 + (cb->height % 8 != 0) ||
        !build_plane_map(y, 0, map) || !build_plane_map(cb, 1, map) ||
        !build_plane_map(cr, 2, map)) {
        n148_transform_map_release(map);
        return 0;
    }
    return n148_transform_map_validate(map);
}

static int plane_for_index(const N148TransformMap *map, size_t index) {
    if (!map || index >= map->count) return -1;
    if (index >= map->plane_offsets[2]) return 2;
    if (index >= map->plane_offsets[1]) return 1;
    return 0;
}

int n148_transform_map_validate(const N148TransformMap *map) {
    if (!map || !map->strategies || map->count == 0 ||
        map->plane_offsets[0] != 0) return 0;
    size_t expected_offset = 0;
    for (int plane = 0; plane < 3; plane++) {
        if (expected_offset > map->count ||
            map->plane_offsets[plane] != expected_offset ||
            map->columns[plane] <= 0 || map->rows[plane] <= 0 ||
            map->blocks_x[plane] <= 0 || map->blocks_y[plane] <= 0 ||
            (size_t) map->columns[plane] >
                SIZE_MAX / (size_t) map->rows[plane]) return 0;
        size_t plane_count = (size_t) map->columns[plane] *
            (size_t) map->rows[plane];
        if (plane_count > map->count - expected_offset) return 0;
        for (size_t local = 0; local < plane_count; local++) {
            uint8_t strategy = map->strategies[expected_offset + local];
            int column = (int)(local % (size_t) map->columns[plane]);
            int row = (int)(local / (size_t) map->columns[plane]);
            if (strategy >= N148_TRANSFORM_STRATEGY_COUNT ||
                (strategy == N148_TRANSFORM_DCT16 &&
                 (column * 2 + 1 >= map->blocks_x[plane] ||
                  row * 2 + 1 >= map->blocks_y[plane]))) return 0;
        }
        expected_offset += plane_count;
    }
    return expected_offset == map->count;
}

int n148_luma_transform_dct32_origin(const N148TransformMap *map,
                                     int macro_x, int macro_y) {
    if (!map || !map->strategies || macro_x < 0 || macro_y < 0 ||
        (macro_x & 1) || (macro_y & 1) ||
        macro_x + 1 >= map->columns[0] || macro_y + 1 >= map->rows[0] ||
        macro_x * 2 + 3 >= map->blocks_x[0] ||
        macro_y * 2 + 3 >= map->blocks_y[0]) return 0;
    for (int dy = 0; dy < 2; dy++) {
        for (int dx = 0; dx < 2; dx++) {
            size_t index = (size_t)(macro_y + dy) *
                (size_t) map->columns[0] + (size_t)(macro_x + dx);
            if (index >= map->plane_offsets[1] ||
                map->strategies[index] != N148_TRANSFORM_DCT4) return 0;
        }
    }
    return 1;
}

int n148_luma_transform_dct32_member(const N148TransformMap *map,
                                     int macro_x, int macro_y) {
    if (macro_x < 0 || macro_y < 0) return 0;
    return n148_luma_transform_dct32_origin(
        map, macro_x & ~1, macro_y & ~1);
}

int n148_luma_transform_map_validate_extended(const N148TransformMap *map,
                                               int allow_dct32) {
    if (!n148_transform_map_validate(map) || map->plane_offsets[1] == 0 ||
        map->plane_offsets[1] > map->count ||
        (allow_dct32 != 0 && allow_dct32 != 1)) return 0;
    for (int row = 0; row < map->rows[0]; row++) {
        for (int column = 0; column < map->columns[0]; column++) {
            size_t index = (size_t) row * (size_t) map->columns[0] +
                (size_t) column;
            uint8_t strategy = map->strategies[index];
            if (strategy == N148_TRANSFORM_DCT8 ||
                strategy == N148_TRANSFORM_DCT16) continue;
            if (!allow_dct32 || strategy != N148_TRANSFORM_DCT4 ||
                !n148_luma_transform_dct32_member(map, column, row))
                return 0;
        }
    }
    for (size_t index = map->plane_offsets[1]; index < map->count; index++)
        if (map->strategies[index] != N148_TRANSFORM_DCT8) return 0;
    return 1;
}

int n148_luma_transform_map_validate(const N148TransformMap *map) {
    return n148_luma_transform_map_validate_extended(map, 0);
}

uint8_t n148_transform_map_predict(const N148TransformMap *map,
                                   size_t index) {
    int plane = plane_for_index(map, index);
    if (plane < 0 || map->columns[plane] <= 0)
        return N148_TRANSFORM_INITIAL_STRATEGY;
    size_t local = index - map->plane_offsets[plane];
    size_t column = local % (size_t) map->columns[plane];
    if (column > 0) return map->strategies[index - 1];
    if (local >= (size_t) map->columns[plane])
        return map->strategies[index - (size_t) map->columns[plane]];
    return N148_TRANSFORM_INITIAL_STRATEGY;
}

int n148_transform_strategy_at(const N148TransformMap *map, int plane,
                               int macro_x, int macro_y, uint8_t *strategy) {
    if (!map || !map->strategies || !strategy || plane < 0 || plane > 2 ||
        macro_x < 0 || macro_y < 0 || macro_x >= map->columns[plane] ||
        macro_y >= map->rows[plane]) return 0;
    size_t index = map->plane_offsets[plane] +
        (size_t) macro_y * (size_t) map->columns[plane] + (size_t) macro_x;
    if (index >= map->count ||
        map->strategies[index] >= N148_TRANSFORM_STRATEGY_COUNT) return 0;
    *strategy = map->strategies[index];
    return 1;
}

void n148_transform_map_release(N148TransformMap *map) {
    if (!map) return;
    free(map->strategies);
    memset(map, 0, sizeof(*map));
}

static const int16_t *matrix_for_size(int size) {
    if (size == 4) return &DCT4_Q14[0][0];
    if (size == 16) return &DCT16_Q14[0][0];
    if (size == 32) return &DCT32_Q14[0][0];
    return NULL;
}

static int64_t round_q28(int64_t value) {
    if (value >= 0)
        return (value + N148_DCT_SCALE_SQUARED / 2) /
            N148_DCT_SCALE_SQUARED;
    return -((-value + N148_DCT_SCALE_SQUARED / 2) /
             N148_DCT_SCALE_SQUARED);
}

static inline void transform4_forward_1d(const int64_t input[4],
                                          int64_t output[4]) {
    int64_t outer_sum = input[0] + input[3];
    int64_t inner_sum = input[1] + input[2];
    int64_t outer_diff = input[0] - input[3];
    int64_t inner_diff = input[1] - input[2];
    output[0] = 8192 * (outer_sum + inner_sum);
    output[1] = 10703 * outer_diff + 4433 * inner_diff;
    output[2] = 8192 * (outer_sum - inner_sum);
    output[3] = 4433 * outer_diff - 10703 * inner_diff;
}

static inline void transform4_inverse_1d(const int64_t input[4],
                                          int64_t output[4]) {
    int64_t even_sum = 8192 * (input[0] + input[2]);
    int64_t even_diff = 8192 * (input[0] - input[2]);
    int64_t odd_0 = 10703 * input[1] + 4433 * input[3];
    int64_t odd_1 = 4433 * input[1] - 10703 * input[3];
    output[0] = even_sum + odd_0;
    output[1] = even_diff + odd_1;
    output[2] = even_diff - odd_1;
    output[3] = even_sum - odd_0;
}

static int transform4_forward(const int32_t *input, int32_t *output) {
    int64_t intermediate[16];
    int32_t result[16];
    for (int column = 0; column < 4; column++) {
        int64_t values[4], transformed[4];
        for (int row = 0; row < 4; row++)
            values[row] = input[row * 4 + column];
        transform4_forward_1d(values, transformed);
        for (int row = 0; row < 4; row++)
            intermediate[row * 4 + column] = transformed[row];
    }
    for (int row = 0; row < 4; row++) {
        int64_t transformed[4];
        transform4_forward_1d(intermediate + row * 4, transformed);
        for (int column = 0; column < 4; column++) {
            int64_t value = round_q28(transformed[column]);
            if (value < INT32_MIN || value > INT32_MAX) return 0;
            result[row * 4 + column] = (int32_t) value;
        }
    }
    memcpy(output, result, sizeof(result));
    return 1;
}

static int transform4_inverse(const int32_t *input, int32_t *output) {
    int64_t intermediate[16];
    int32_t result[16];
    for (int column = 0; column < 4; column++) {
        int64_t values[4], transformed[4];
        for (int row = 0; row < 4; row++)
            values[row] = input[row * 4 + column];
        transform4_inverse_1d(values, transformed);
        for (int row = 0; row < 4; row++)
            intermediate[row * 4 + column] = transformed[row];
    }
    for (int row = 0; row < 4; row++) {
        int64_t transformed[4];
        transform4_inverse_1d(intermediate + row * 4, transformed);
        for (int column = 0; column < 4; column++) {
            int64_t value = round_q28(transformed[column]);
            if (value < INT32_MIN || value > INT32_MAX) return 0;
            result[row * 4 + column] = (int32_t) value;
        }
    }
    memcpy(output, result, sizeof(result));
    return 1;
}

#if defined(__x86_64__) || defined(__i386__)
__attribute__((target("avx2")))
static inline void store_interleaved64_avx2(int64_t *destination,
                                            __m256i even, __m256i odd) {
    __m256i low = _mm256_unpacklo_epi64(even, odd);
    __m256i high = _mm256_unpackhi_epi64(even, odd);
    _mm256_storeu_si256((__m256i *) destination,
                        _mm256_permute2x128_si256(low, high, 0x20));
    _mm256_storeu_si256((__m256i *)(destination + 4),
                        _mm256_permute2x128_si256(low, high, 0x31));
}

__attribute__((target("avx2")))
static inline __m256i round_q28_avx2(__m256i values) {
    __m256i zero = _mm256_setzero_si256();
    __m256i negative = _mm256_cmpgt_epi64(zero, values);
    __m256i absolute = _mm256_sub_epi64(
        _mm256_xor_si256(values, negative), negative);
    __m256i rounded = _mm256_srli_epi64(_mm256_add_epi64(
        absolute, _mm256_set1_epi64x(N148_DCT_SCALE_SQUARED / 2)), 28);
    return _mm256_sub_epi64(_mm256_xor_si256(rounded, negative), negative);
}

__attribute__((target("avx2")))
static inline void transpose4x4_i64(__m256i v[4]) {
    __m256i a = _mm256_unpacklo_epi64(v[0], v[1]);
    __m256i b = _mm256_unpackhi_epi64(v[0], v[1]);
    __m256i c = _mm256_unpacklo_epi64(v[2], v[3]);
    __m256i d = _mm256_unpackhi_epi64(v[2], v[3]);
    v[0] = _mm256_permute2x128_si256(a, c, 0x20);
    v[1] = _mm256_permute2x128_si256(b, d, 0x20);
    v[2] = _mm256_permute2x128_si256(a, c, 0x31);
    v[3] = _mm256_permute2x128_si256(b, d, 0x31);
}

__attribute__((target("avx2")))
static inline void transform4_pass_avx2(__m256i v[4], int inverse) {
    const __m256i c1 = _mm256_set1_epi64x(10703);
    const __m256i c2 = _mm256_set1_epi64x(4433);
    __m256i a, b, c, d;
    if (inverse) {
        a = _mm256_slli_epi64(_mm256_add_epi64(v[0], v[2]), 13);
        b = _mm256_slli_epi64(_mm256_sub_epi64(v[0], v[2]), 13);
        c = _mm256_add_epi64(_mm256_mul_epi32(v[1], c1),
                             _mm256_mul_epi32(v[3], c2));
        d = _mm256_sub_epi64(_mm256_mul_epi32(v[1], c2),
                             _mm256_mul_epi32(v[3], c1));
        v[0] = _mm256_add_epi64(a, c);
        v[1] = _mm256_add_epi64(b, d);
        v[2] = _mm256_sub_epi64(b, d);
        v[3] = _mm256_sub_epi64(a, c);
    } else {
        a = _mm256_add_epi64(v[0], v[3]);
        b = _mm256_add_epi64(v[1], v[2]);
        c = _mm256_sub_epi64(v[0], v[3]);
        d = _mm256_sub_epi64(v[1], v[2]);
        v[0] = _mm256_slli_epi64(_mm256_add_epi64(a, b), 13);
        v[1] = _mm256_add_epi64(_mm256_mul_epi32(c, c1),
                             _mm256_mul_epi32(d, c2));
        v[2] = _mm256_slli_epi64(_mm256_sub_epi64(a, b), 13);
        v[3] = _mm256_sub_epi64(_mm256_mul_epi32(c, c2),
                             _mm256_mul_epi32(d, c1));
    }
}

/* The image-domain 4x4 transform uses the same Q14 matrix, pass order and
   final Q28 rounding as the general path. With |input| <= 8191 every
   multiplicand in both passes fits int32; products and sums stay int64.
   Larger internal inputs retain the general checked implementation. */
__attribute__((target("avx2")))
static int transform4_avx2(const int32_t *input, int32_t *output, int inverse) {
    __m128i rows[4];
    __m256i v[4];
    for (int row = 0; row < 4; row++)
        rows[row] = _mm_loadu_si128((const __m128i *)(input + 4 * row));
    __m128i packed0 = _mm_packs_epi32(rows[0], rows[1]);
    __m128i packed1 = _mm_packs_epi32(rows[2], rows[3]);
    __m128i low = _mm_set1_epi16(-8191), high = _mm_set1_epi16(8191);
    __m128i outside = _mm_or_si128(
        _mm_or_si128(_mm_cmpgt_epi16(low, packed0), _mm_cmpgt_epi16(packed0, high)),
        _mm_or_si128(_mm_cmpgt_epi16(low, packed1), _mm_cmpgt_epi16(packed1, high)));
    if (_mm_movemask_epi8(outside)) return 0;
    for (int row = 0; row < 4; row++) v[row] = _mm256_cvtepi32_epi64(rows[row]);
    transform4_pass_avx2(v, inverse);
    transpose4x4_i64(v);
    transform4_pass_avx2(v, inverse);
    transpose4x4_i64(v);
    const __m256i compact = _mm256_setr_epi32(0, 2, 4, 6, 0, 2, 4, 6);
    for (int row = 0; row < 4; row++) {
        __m256i rounded = round_q28_avx2(v[row]);
        __m256i packed = _mm256_permutevar8x32_epi32(rounded, compact);
        _mm_storeu_si128((__m128i *)(output + 4 * row), _mm256_castsi256_si128(packed));
    }
    return 1;
}

__attribute__((target("avx2")))
static inline int store_rounded8_avx2(int32_t *destination,
                                       __m256i even, __m256i odd) {
    even = round_q28_avx2(even);
    odd = round_q28_avx2(odd);
    __m256i maximum = _mm256_set1_epi64x(INT32_MAX);
    __m256i minimum = _mm256_set1_epi64x(INT32_MIN);
    __m256i overflow = _mm256_or_si256(
        _mm256_or_si256(_mm256_cmpgt_epi64(even, maximum),
                        _mm256_cmpgt_epi64(minimum, even)),
        _mm256_or_si256(_mm256_cmpgt_epi64(odd, maximum),
                        _mm256_cmpgt_epi64(minimum, odd)));
    if (!_mm256_testz_si256(overflow, overflow)) return 0;
    __m256i low_dwords = _mm256_set1_epi64x(0x0b0a090803020100ll);
    __m256i compact_even = _mm256_shuffle_epi8(even, low_dwords);
    __m256i compact_odd = _mm256_shuffle_epi8(odd, low_dwords);
    _mm256_storeu_si256((__m256i *) destination,
                        _mm256_unpacklo_epi32(compact_even, compact_odd));
    return 1;
}

__attribute__((target("avx2")))
static void transform_first_pass_avx2(const int32_t *input, int size,
                                      int inverse, const int16_t *matrix,
                                      int64_t *intermediate) {
    for (int outer = 0; outer < size; outer++) {
        for (int x = 0; x < size; x += 8) {
            __m256i even = _mm256_setzero_si256();
            __m256i odd = _mm256_setzero_si256();
            for (int inner = 0; inner < size; inner++) {
                int32_t coefficient = inverse ?
                    matrix[inner * size + outer] :
                    matrix[outer * size + inner];
                __m256i values = _mm256_loadu_si256(
                    (const __m256i *)(input + inner * size + x));
                __m256i factor = _mm256_set1_epi32(coefficient);
                even = _mm256_add_epi64(
                    even, _mm256_mul_epi32(values, factor));
                odd = _mm256_add_epi64(
                    odd, _mm256_mul_epi32(
                        _mm256_srli_epi64(values, 32), factor));
            }
            store_interleaved64_avx2(
                intermediate + outer * size + x, even, odd);
        }
    }
}

__attribute__((target("avx2")))
static int inverse_second_pass_avx2(const int64_t *intermediate, int size,
                                    const int16_t *matrix, int32_t *result) {
    for (int y = 0; y < size; y++) {
        for (int x = 0; x < size; x += 8) {
            __m256i even = _mm256_setzero_si256();
            __m256i odd = _mm256_setzero_si256();
            for (int frequency_x = 0; frequency_x < size; frequency_x++) {
                __m128i packed = _mm_loadu_si128((const __m128i *)(
                    matrix + frequency_x * size + x));
                __m256i coefficients = _mm256_cvtepi16_epi32(packed);
                __m256i value = _mm256_set1_epi32((int32_t)
                    intermediate[y * size + frequency_x]);
                even = _mm256_add_epi64(
                    even, _mm256_mul_epi32(coefficients, value));
                odd = _mm256_add_epi64(
                    odd, _mm256_mul_epi32(
                        _mm256_srli_epi64(coefficients, 32), value));
            }
            if (!store_rounded8_avx2(result + y * size + x, even, odd))
                return 0;
        }
    }
    return 1;
}

__attribute__((target("avx2")))
static void inverse_sparse16_first_pass_avx2(
    const int32_t input[16 * 16], uint32_t active_rows,
    uint32_t active_columns, int64_t intermediate[16 * 16]) {
    int active_frequencies[16];
    int active_count = 0;
    for (int frequency_y = 0; frequency_y < 16; frequency_y++) {
        if (active_rows & (1u << frequency_y))
            active_frequencies[active_count++] = frequency_y;
    }
    if (active_count <= 2) {
        int first_frequency = active_frequencies[0];
        int second_frequency = active_count == 2 ? active_frequencies[1] : 0;
        for (int y = 0; y < 16; y++) {
            __m256i first_factor = _mm256_set1_epi32(
                DCT16_Q14[first_frequency][y]);
            __m256i second_factor = _mm256_setzero_si256();
            if (active_count == 2)
                second_factor = _mm256_set1_epi32(
                    DCT16_Q14[second_frequency][y]);
            for (int x = 0; x < 16; x += 8) {
                if (!(active_columns & (0xffu << x))) continue;
                __m256i values = _mm256_loadu_si256(
                    (const __m256i *)(input + first_frequency * 16 + x));
                __m256i even = _mm256_mul_epi32(values, first_factor);
                __m256i odd = _mm256_mul_epi32(
                    _mm256_srli_epi64(values, 32), first_factor);
                if (active_count == 2) {
                    values = _mm256_loadu_si256((const __m256i *)(
                        input + second_frequency * 16 + x));
                    even = _mm256_add_epi64(
                        even, _mm256_mul_epi32(values, second_factor));
                    odd = _mm256_add_epi64(
                        odd, _mm256_mul_epi32(
                            _mm256_srli_epi64(values, 32), second_factor));
                }
                store_interleaved64_avx2(
                    intermediate + y * 16 + x, even, odd);
            }
        }
        return;
    }
    for (int y = 0; y < 16; y++) {
        for (int x = 0; x < 16; x += 8) {
            if (!(active_columns & (0xffu << x))) continue;
            __m256i even = _mm256_setzero_si256();
            __m256i odd = _mm256_setzero_si256();
            for (int frequency = 0; frequency < active_count; frequency++) {
                int frequency_y = active_frequencies[frequency];
                __m256i values = _mm256_loadu_si256(
                    (const __m256i *)(input + frequency_y * 16 + x));
                __m256i factor = _mm256_set1_epi32(
                    DCT16_Q14[frequency_y][y]);
                even = _mm256_add_epi64(
                    even, _mm256_mul_epi32(values, factor));
                odd = _mm256_add_epi64(
                    odd, _mm256_mul_epi32(
                        _mm256_srli_epi64(values, 32), factor));
            }
            store_interleaved64_avx2(
                intermediate + y * 16 + x, even, odd);
        }
    }
}

__attribute__((target("avx2")))
static int inverse_sparse16_second_pass_avx2(
    const int64_t intermediate[16 * 16], uint32_t active_columns,
    int32_t result[16 * 16]) {
    int active_frequencies[16];
    int active_count = 0;
    for (int frequency_x = 0; frequency_x < 16; frequency_x++) {
        if (active_columns & (1u << frequency_x))
            active_frequencies[active_count++] = frequency_x;
    }
    if (active_count <= 2) {
        int first_frequency = active_frequencies[0];
        int second_frequency = active_count == 2 ? active_frequencies[1] : 0;
        for (int y = 0; y < 16; y++) {
            __m256i first_value = _mm256_set1_epi32((int32_t)
                intermediate[y * 16 + first_frequency]);
            __m256i second_value = _mm256_setzero_si256();
            if (active_count == 2)
                second_value = _mm256_set1_epi32((int32_t)
                    intermediate[y * 16 + second_frequency]);
            for (int x = 0; x < 16; x += 8) {
                __m128i packed = _mm_loadu_si128((const __m128i *)(
                    DCT16_Q14[first_frequency] + x));
                __m256i coefficients = _mm256_cvtepi16_epi32(packed);
                __m256i even = _mm256_mul_epi32(coefficients, first_value);
                __m256i odd = _mm256_mul_epi32(
                    _mm256_srli_epi64(coefficients, 32), first_value);
                if (active_count == 2) {
                    packed = _mm_loadu_si128((const __m128i *)(
                        DCT16_Q14[second_frequency] + x));
                    coefficients = _mm256_cvtepi16_epi32(packed);
                    even = _mm256_add_epi64(
                        even, _mm256_mul_epi32(coefficients, second_value));
                    odd = _mm256_add_epi64(
                        odd, _mm256_mul_epi32(
                            _mm256_srli_epi64(coefficients, 32),
                            second_value));
                }
                if (!store_rounded8_avx2(result + y * 16 + x, even, odd))
                    return 0;
            }
        }
        return 1;
    }
    for (int y = 0; y < 16; y++) {
        for (int x = 0; x < 16; x += 8) {
            __m256i even = _mm256_setzero_si256();
            __m256i odd = _mm256_setzero_si256();
            for (int frequency = 0; frequency < active_count; frequency++) {
                int frequency_x = active_frequencies[frequency];
                __m128i packed = _mm_loadu_si128((const __m128i *)(
                    DCT16_Q14[frequency_x] + x));
                __m256i coefficients = _mm256_cvtepi16_epi32(packed);
                __m256i value = _mm256_set1_epi32((int32_t)
                    intermediate[y * 16 + frequency_x]);
                even = _mm256_add_epi64(
                    even, _mm256_mul_epi32(coefficients, value));
                odd = _mm256_add_epi64(
                    odd, _mm256_mul_epi32(
                        _mm256_srli_epi64(coefficients, 32), value));
            }
            if (!store_rounded8_avx2(result + y * 16 + x, even, odd))
                return 0;
        }
    }
    return 1;
}

#endif

int n148_variable_inverse_sparse16(const int32_t input[16 * 16],
                                   uint32_t active_rows,
                                   uint32_t active_columns,
                                   int32_t output[16 * 16]) {
    if (!input || !output ||
        ((active_rows | active_columns) & ~0xffffu) ||
        (!!active_rows != !!active_columns)) return 0;
    if (!active_rows) {
        memset(output, 0, 16 * 16 * sizeof(*output));
        return 1;
    }
    int64_t intermediate[16 * 16] = {0};
    int32_t result[16 * 16];
#if defined(__x86_64__) || defined(__i386__)
    int use_avx2 = n148_cpu_level() >= N148_CPU_AVX2;
    if (use_avx2)
        inverse_sparse16_first_pass_avx2(
            input, active_rows, active_columns, intermediate);
#else
    int use_avx2 = 0;
#endif
    if (!use_avx2) {
        for (int y = 0; y < 16; y++) {
            for (int frequency_x = 0; frequency_x < 16; frequency_x++) {
                if (!(active_columns & (1u << frequency_x))) continue;
                int64_t sum = 0;
                for (int frequency_y = 0; frequency_y < 16; frequency_y++) {
                    if (!(active_rows & (1u << frequency_y))) continue;
                    sum += (int64_t) DCT16_Q14[frequency_y][y] *
                        input[frequency_y * 16 + frequency_x];
                }
                intermediate[y * 16 + frequency_x] = sum;
            }
        }
    }
#if defined(__x86_64__) || defined(__i386__)
    if (use_avx2) {
        int fits32 = 1;
        uint32_t columns = active_columns;
        while (columns && fits32) {
            int x = __builtin_ctz(columns);
            columns &= columns - 1;
            for (int y = 0; y < 16; y++) {
                int64_t value = intermediate[y * 16 + x];
                if (value < INT32_MIN || value > INT32_MAX) {
                    fits32 = 0;
                    break;
                }
            }
        }
        if (fits32) {
            if (!inverse_sparse16_second_pass_avx2(
                    intermediate, active_columns, result)) return 0;
            memcpy(output, result, sizeof(result));
            return 1;
        }
    }
#endif
    for (int y = 0; y < 16; y++) {
        for (int x = 0; x < 16; x++) {
            int64_t sum = 0;
            for (int frequency_x = 0; frequency_x < 16; frequency_x++) {
                if (!(active_columns & (1u << frequency_x))) continue;
                sum += intermediate[y * 16 + frequency_x] *
                    DCT16_Q14[frequency_x][x];
            }
            int64_t value = round_q28(sum);
            if (value < INT32_MIN || value > INT32_MAX) return 0;
            result[y * 16 + x] = (int32_t) value;
        }
    }
    memcpy(output, result, sizeof(result));
    return 1;
}

static int transform_2d(const int32_t *input, int size, int inverse,
                        int32_t *output) {
    const int16_t *matrix = matrix_for_size(size);
    if (!input || !output || !matrix) return 0;
    if (size == 4) {
#if defined(__x86_64__) || defined(__i386__)
        if (n148_cpu_level() >= N148_CPU_AVX2 &&
            transform4_avx2(input, output, inverse)) return 1;
#endif
        return inverse ? transform4_inverse(input, output) :
                         transform4_forward(input, output);
    }
    int64_t intermediate[32 * 32];
    int32_t result[32 * 32];
#if defined(__x86_64__) || defined(__i386__)
    int use_avx2 = n148_cpu_level() >= N148_CPU_AVX2;
    if (use_avx2)
        transform_first_pass_avx2(input, size, inverse, matrix, intermediate);
#else
    int use_avx2 = 0;
#endif
    if (!inverse) {
        if (!use_avx2) {
            for (int frequency_y = 0; frequency_y < size; frequency_y++) {
                for (int x = 0; x < size; x++) {
                    int64_t sum = 0;
                    for (int y = 0; y < size; y++)
                        sum += (int64_t) matrix[frequency_y * size + y] *
                            input[y * size + x];
                    intermediate[frequency_y * size + x] = sum;
                }
            }
        }
#if defined(__x86_64__) || defined(__i386__)
        if (use_avx2) {
            int fits32 = 1;
            for (int index = 0; index < size * size; index++) {
                if (intermediate[index] < INT32_MIN ||
                    intermediate[index] > INT32_MAX) {
                    fits32 = 0;
                    break;
                }
            }
            if (fits32) {
                const int16_t *transposed = size == 16 ?
                    &DCT16_TRANSPOSE_Q14[0][0] : &DCT32_TRANSPOSE_Q14[0][0];
                if (!inverse_second_pass_avx2(intermediate, size,
                                              transposed, result)) return 0;
                memcpy(output, result,
                       (size_t) size * (size_t) size * sizeof(*output));
                return 1;
            }
        }
#endif
        for (int frequency_y = 0; frequency_y < size; frequency_y++) {
            for (int frequency_x = 0; frequency_x < size; frequency_x++) {
                int64_t sum = 0;
                for (int x = 0; x < size; x++)
                    sum += intermediate[frequency_y * size + x] *
                        matrix[frequency_x * size + x];
                int64_t value = round_q28(sum);
                if (value < INT32_MIN || value > INT32_MAX) return 0;
                result[frequency_y * size + frequency_x] = (int32_t) value;
            }
        }
    } else {
        if (!use_avx2) {
            for (int y = 0; y < size; y++) {
                for (int frequency_x = 0; frequency_x < size; frequency_x++) {
                    int64_t sum = 0;
                    for (int frequency_y = 0; frequency_y < size; frequency_y++)
                        sum += (int64_t) matrix[frequency_y * size + y] *
                            input[frequency_y * size + frequency_x];
                    intermediate[y * size + frequency_x] = sum;
                }
            }
        }
#if defined(__x86_64__) || defined(__i386__)
        if (use_avx2) {
            int fits32 = 1;
            for (int index = 0; index < size * size; index++) {
                if (intermediate[index] < INT32_MIN ||
                    intermediate[index] > INT32_MAX) {
                    fits32 = 0;
                    break;
                }
            }
            if (fits32) {
                if (!inverse_second_pass_avx2(intermediate, size,
                                              matrix, result)) return 0;
                memcpy(output, result,
                       (size_t) size * (size_t) size * sizeof(*output));
                return 1;
            }
        }
#endif
        for (int y = 0; y < size; y++) {
            for (int x = 0; x < size; x++) {
                int64_t sum = 0;
                for (int frequency_x = 0; frequency_x < size; frequency_x++)
                    sum += intermediate[y * size + frequency_x] *
                        matrix[frequency_x * size + x];
                int64_t value = round_q28(sum);
                if (value < INT32_MIN || value > INT32_MAX) return 0;
                result[y * size + x] = (int32_t) value;
            }
        }
    }
    memcpy(output, result, (size_t) size * (size_t) size * sizeof(*output));
    return 1;
}

int n148_variable_forward(const int32_t *input, int size, int32_t *output) {
    return transform_2d(input, size, 0, output);
}

int n148_variable_inverse(const int32_t *input, int size, int32_t *output) {
    return transform_2d(input, size, 1, output);
}

#include "variable_zigzag_tables.inc"

uint64_t n148_variable_transform_matrix_hash(void) {
    uint64_t hash = 14695981039346656037ull;
    const int16_t *tables[2] = {&DCT4_Q14[0][0], &DCT16_Q14[0][0]};
    const size_t counts[2] = {16, 256};
    for (int table = 0; table < 2; table++) {
        for (size_t index = 0; index < counts[table]; index++) {
            uint16_t value = (uint16_t) tables[table][index];
            hash ^= (uint8_t) value;
            hash *= 1099511628211ull;
            hash ^= (uint8_t)(value >> 8);
            hash *= 1099511628211ull;
        }
    }
    return hash;
}

uint64_t n148_variable_transform_matrix32_hash(void) {
    uint64_t hash = 14695981039346656037ull;
    const int16_t *values = &DCT32_Q14[0][0];
    for (size_t index = 0; index < 32u * 32u; index++) {
        uint16_t value = (uint16_t) values[index];
        hash ^= (uint8_t) value;
        hash *= 1099511628211ull;
        hash ^= (uint8_t)(value >> 8);
        hash *= 1099511628211ull;
    }
    return hash;
}

src/dct_forward_transposes.inc

O dct_forward_transposes.inc é incluído pelo variable_transform.c e guarda as matrizes transpostas das DCTs de 16x16 e de 32x32, em ponto fixo.

O arquivo completo tem 53 linhas:

/* Exact transposes of original N.148 matrices. */
static const int16_t DCT16_TRANSPOSE_Q14[16][16] = {
    {4096,5765,5681,5543,5352,5109,4816,4478,4096,3675,3218,2731,2217,1682,1130,568},
    {4096,5543,4816,3675,2217,568,-1130,-2731,-4096,-5109,-5681,-5765,-5352,-4478,-3218,-1682},
    {4096,5109,3218,568,-2217,-4478,-5681,-5543,-4096,-1682,1130,3675,5352,5765,4816,2731},
    {4096,4478,1130,-2731,-5352,-5543,-3218,568,4096,5765,4816,1682,-2217,-5109,-5681,-3675},
    {4096,3675,-1130,-5109,-5352,-1682,3218,5765,4096,-568,-4816,-5543,-2217,2731,5681,4478},
    {4096,2731,-3218,-5765,-2217,3675,5681,1682,-4096,-5543,-1130,4478,5352,568,-4816,-5109},
    {4096,1682,-4816,-4478,2217,5765,1130,-5109,-4096,2731,5681,568,-5352,-3675,3218,5543},
    {4096,568,-5681,-1682,5352,2731,-4816,-3675,4096,4478,-3218,-5109,2217,5543,-1130,-5765},
    {4096,-568,-5681,1682,5352,-2731,-4816,3675,4096,-4478,-3218,5109,2217,-5543,-1130,5765},
    {4096,-1682,-4816,4478,2217,-5765,1130,5109,-4096,-2731,5681,-568,-5352,3675,3218,-5543},
    {4096,-2731,-3218,5765,-2217,-3675,5681,-1682,-4096,5543,-1130,-4478,5352,-568,-4816,5109},
    {4096,-3675,-1130,5109,-5352,1682,3218,-5765,4096,568,-4816,5543,-2217,-2731,5681,-4478},
    {4096,-4478,1130,2731,-5352,5543,-3218,-568,4096,-5765,4816,-1682,-2217,5109,-5681,3675},
    {4096,-5109,3218,-568,-2217,4478,-5681,5543,-4096,1682,1130,-3675,5352,-5765,4816,-2731},
    {4096,-5543,4816,-3675,2217,-568,-1130,2731,-4096,5109,-5681,5765,-5352,4478,-3218,1682},
    {4096,-5765,5681,-5543,5352,-5109,4816,-4478,4096,-3675,3218,-2731,2217,-1682,1130,-568}
};
static const int16_t DCT32_TRANSPOSE_Q14[32][32] = {
    {2896,4091,4076,4052,4017,3973,3920,3857,3784,3703,3612,3513,3406,3290,3166,3035,2896,2751,2598,2440,2276,2106,1931,1751,1567,1380,1189,995,799,601,401,201},
    {2896,4052,3920,3703,3406,3035,2598,2106,1567,995,401,-201,-799,-1380,-1931,-2440,-2896,-3290,-3612,-3857,-4017,-4091,-4076,-3973,-3784,-3513,-3166,-2751,-2276,-1751,-1189,-601},
    {2896,3973,3612,3035,2276,1380,401,-601,-1567,-2440,-3166,-3703,-4017,-4091,-3920,-3513,-2896,-2106,-1189,-201,799,1751,2598,3290,3784,4052,4076,3857,3406,2751,1931,995},
    {2896,3857,3166,2106,799,-601,-1931,-3035,-3784,-4091,-3920,-3290,-2276,-995,401,1751,2896,3703,4076,3973,3406,2440,1189,-201,-1567,-2751,-3612,-4052,-4017,-3513,-2598,-1380},
    {2896,3703,2598,995,-799,-2440,-3612,-4091,-3784,-2751,-1189,601,2276,3513,4076,3857,2896,1380,-401,-2106,-3406,-4052,-3920,-3035,-1567,201,1931,3290,4017,3973,3166,1751},
    {2896,3513,1931,-201,-2276,-3703,-4076,-3290,-1567,601,2598,3857,4017,3035,1189,-995,-2896,-3973,-3920,-2751,-799,1380,3166,4052,3784,2440,401,-1751,-3406,-4091,-3612,-2106},
    {2896,3290,1189,-1380,-3406,-4091,-3166,-995,1567,3513,4076,3035,799,-1751,-3612,-4052,-2896,-601,1931,3703,4017,2751,401,-2106,-3784,-3973,-2598,-201,2276,3857,3920,2440},
    {2896,3035,401,-2440,-4017,-3513,-1189,1751,3784,3857,1931,-995,-3406,-4052,-2598,201,2896,4091,3166,601,-2276,-3973,-3612,-1380,1567,3703,3920,2106,-799,-3290,-4076,-2751},
    {2896,2751,-401,-3290,-4017,-2106,1189,3703,3784,1380,-1931,-3973,-3406,-601,2598,4091,2896,-201,-3166,-4052,-2276,995,3612,3857,1567,-1751,-3920,-3513,-799,2440,4076,3035},
    {2896,2440,-1189,-3857,-3406,-201,3166,3973,1567,-2106,-4076,-2751,799,3703,3612,601,-2896,-4052,-1931,1751,4017,3035,-401,-3513,-3784,-995,2598,4091,2276,-1380,-3920,-3290},
    {2896,2106,-1931,-4091,-2276,1751,4076,2440,-1567,-4052,-2598,1380,4017,2751,-1189,-3973,-2896,995,3920,3035,-799,-3857,-3166,601,3784,3290,-401,-3703,-3406,201,3612,3513},
    {2896,1751,-2598,-3973,-799,3290,3612,-201,-3784,-3035,1189,4052,2276,-2106,-4076,-1380,2896,3857,401,-3513,-3406,601,3920,2751,-1567,-4091,-1931,2440,4017,995,-3166,-3703},
    {2896,1380,-3166,-3513,799,4052,1931,-2751,-3784,201,3920,2440,-2276,-3973,-401,3703,2896,-1751,-4076,-995,3406,3290,-1189,-4091,-1567,3035,3612,-601,-4017,-2106,2598,3857},
    {2896,995,-3612,-2751,2276,3857,-401,-4052,-1567,3290,3166,-1751,-4017,-201,3920,2106,-2896,-3513,1189,4091,799,-3703,-2598,2440,3784,-601,-4076,-1380,3406,3035,-1931,-3973},
    {2896,601,-3920,-1751,3406,2751,-2598,-3513,1567,3973,-401,-4091,-799,3857,1931,-3290,-2896,2440,3612,-1380,-4017,201,4076,995,-3784,-2106,3166,3035,-2276,-3703,1189,4052},
    {2896,201,-4076,-601,4017,995,-3920,-1380,3784,1751,-3612,-2106,3406,2440,-3166,-2751,2896,3035,-2598,-3290,2276,3513,-1931,-3703,1567,3857,-1189,-3973,799,4052,-401,-4091},
    {2896,-201,-4076,601,4017,-995,-3920,1380,3784,-1751,-3612,2106,3406,-2440,-3166,2751,2896,-3035,-2598,3290,2276,-3513,-1931,3703,1567,-3857,-1189,3973,799,-4052,-401,4091},
    {2896,-601,-3920,1751,3406,-2751,-2598,3513,1567,-3973,-401,4091,-799,-3857,1931,3290,-2896,-2440,3612,1380,-4017,-201,4076,-995,-3784,2106,3166,-3035,-2276,3703,1189,-4052},
    {2896,-995,-3612,2751,2276,-3857,-401,4052,-1567,-3290,3166,1751,-4017,201,3920,-2106,-2896,3513,1189,-4091,799,3703,-2598,-2440,3784,601,-4076,1380,3406,-3035,-1931,3973},
    {2896,-1380,-3166,3513,799,-4052,1931,2751,-3784,-201,3920,-2440,-2276,3973,-401,-3703,2896,1751,-4076,995,3406,-3290,-1189,4091,-1567,-3035,3612,601,-4017,2106,2598,-3857},
    {2896,-1751,-2598,3973,-799,-3290,3612,201,-3784,3035,1189,-4052,2276,2106,-4076,1380,2896,-3857,401,3513,-3406,-601,3920,-2751,-1567,4091,-1931,-2440,4017,-995,-3166,3703},
    {2896,-2106,-1931,4091,-2276,-1751,4076,-2440,-1567,4052,-2598,-1380,4017,-2751,-1189,3973,-2896,-995,3920,-3035,-799,3857,-3166,-601,3784,-3290,-401,3703,-3406,-201,3612,-3513},
    {2896,-2440,-1189,3857,-3406,201,3166,-3973,1567,2106,-4076,2751,799,-3703,3612,-601,-2896,4052,-1931,-1751,4017,-3035,-401,3513,-3784,995,2598,-4091,2276,1380,-3920,3290},
    {2896,-2751,-401,3290,-4017,2106,1189,-3703,3784,-1380,-1931,3973,-3406,601,2598,-4091,2896,201,-3166,4052,-2276,-995,3612,-3857,1567,1751,-3920,3513,-799,-2440,4076,-3035},
    {2896,-3035,401,2440,-4017,3513,-1189,-1751,3784,-3857,1931,995,-3406,4052,-2598,-201,2896,-4091,3166,-601,-2276,3973,-3612,1380,1567,-3703,3920,-2106,-799,3290,-4076,2751},
    {2896,-3290,1189,1380,-3406,4091,-3166,995,1567,-3513,4076,-3035,799,1751,-3612,4052,-2896,601,1931,-3703,4017,-2751,401,2106,-3784,3973,-2598,201,2276,-3857,3920,-2440},
    {2896,-3513,1931,201,-2276,3703,-4076,3290,-1567,-601,2598,-3857,4017,-3035,1189,995,-2896,3973,-3920,2751,-799,-1380,3166,-4052,3784,-2440,401,1751,-3406,4091,-3612,2106},
    {2896,-3703,2598,-995,-799,2440,-3612,4091,-3784,2751,-1189,-601,2276,-3513,4076,-3857,2896,-1380,-401,2106,-3406,4052,-3920,3035,-1567,-201,1931,-3290,4017,-3973,3166,-1751},
    {2896,-3857,3166,-2106,799,601,-1931,3035,-3784,4091,-3920,3290,-2276,995,401,-1751,2896,-3703,4076,-3973,3406,-2440,1189,201,-1567,2751,-3612,4052,-4017,3513,-2598,1380},
    {2896,-3973,3612,-3035,2276,-1380,401,601,-1567,2440,-3166,3703,-4017,4091,-3920,3513,-2896,2106,-1189,201,799,-1751,2598,-3290,3784,-4052,4076,-3857,3406,-2751,1931,-995},
    {2896,-4052,3920,-3703,3406,-3035,2598,-2106,1567,-995,401,201,-799,1380,-1931,2440,-2896,3290,-3612,3857,-4017,4091,-4076,3973,-3784,3513,-3166,2751,-2276,1751,-1189,601},
    {2896,-4091,4076,-4052,4017,-3973,3920,-3857,3784,-3703,3612,-3513,3406,-3290,3166,-3035,2896,-2751,2598,-2440,2276,-2106,1931,-1751,1567,-1380,1189,-995,799,-601,401,-201}
};

src/dct32_q14.inc

O dct32_q14.inc também é incluído pelo variable_transform.c e guarda a matriz da DCT de 32x32 em ponto fixo, com 14 bits de fração.

O arquivo completo tem 37 linhas:

/* Normative Q14 orthonormal DCT32 matrix.
 * Copyright (c) 2026 Micilini Roll; MIT License.
 * Generated once from the DCT-II definition and stored literally. */
static const int16_t DCT32_Q14[32][32] = {
    {2896,2896,2896,2896,2896,2896,2896,2896,2896,2896,2896,2896,2896,2896,2896,2896,2896,2896,2896,2896,2896,2896,2896,2896,2896,2896,2896,2896,2896,2896,2896,2896},
    {4091,4052,3973,3857,3703,3513,3290,3035,2751,2440,2106,1751,1380,995,601,201,-201,-601,-995,-1380,-1751,-2106,-2440,-2751,-3035,-3290,-3513,-3703,-3857,-3973,-4052,-4091},
    {4076,3920,3612,3166,2598,1931,1189,401,-401,-1189,-1931,-2598,-3166,-3612,-3920,-4076,-4076,-3920,-3612,-3166,-2598,-1931,-1189,-401,401,1189,1931,2598,3166,3612,3920,4076},
    {4052,3703,3035,2106,995,-201,-1380,-2440,-3290,-3857,-4091,-3973,-3513,-2751,-1751,-601,601,1751,2751,3513,3973,4091,3857,3290,2440,1380,201,-995,-2106,-3035,-3703,-4052},
    {4017,3406,2276,799,-799,-2276,-3406,-4017,-4017,-3406,-2276,-799,799,2276,3406,4017,4017,3406,2276,799,-799,-2276,-3406,-4017,-4017,-3406,-2276,-799,799,2276,3406,4017},
    {3973,3035,1380,-601,-2440,-3703,-4091,-3513,-2106,-201,1751,3290,4052,3857,2751,995,-995,-2751,-3857,-4052,-3290,-1751,201,2106,3513,4091,3703,2440,601,-1380,-3035,-3973},
    {3920,2598,401,-1931,-3612,-4076,-3166,-1189,1189,3166,4076,3612,1931,-401,-2598,-3920,-3920,-2598,-401,1931,3612,4076,3166,1189,-1189,-3166,-4076,-3612,-1931,401,2598,3920},
    {3857,2106,-601,-3035,-4091,-3290,-995,1751,3703,3973,2440,-201,-2751,-4052,-3513,-1380,1380,3513,4052,2751,201,-2440,-3973,-3703,-1751,995,3290,4091,3035,601,-2106,-3857},
    {3784,1567,-1567,-3784,-3784,-1567,1567,3784,3784,1567,-1567,-3784,-3784,-1567,1567,3784,3784,1567,-1567,-3784,-3784,-1567,1567,3784,3784,1567,-1567,-3784,-3784,-1567,1567,3784},
    {3703,995,-2440,-4091,-2751,601,3513,3857,1380,-2106,-4052,-3035,201,3290,3973,1751,-1751,-3973,-3290,-201,3035,4052,2106,-1380,-3857,-3513,-601,2751,4091,2440,-995,-3703},
    {3612,401,-3166,-3920,-1189,2598,4076,1931,-1931,-4076,-2598,1189,3920,3166,-401,-3612,-3612,-401,3166,3920,1189,-2598,-4076,-1931,1931,4076,2598,-1189,-3920,-3166,401,3612},
    {3513,-201,-3703,-3290,601,3857,3035,-995,-3973,-2751,1380,4052,2440,-1751,-4091,-2106,2106,4091,1751,-2440,-4052,-1380,2751,3973,995,-3035,-3857,-601,3290,3703,201,-3513},
    {3406,-799,-4017,-2276,2276,4017,799,-3406,-3406,799,4017,2276,-2276,-4017,-799,3406,3406,-799,-4017,-2276,2276,4017,799,-3406,-3406,799,4017,2276,-2276,-4017,-799,3406},
    {3290,-1380,-4091,-995,3513,3035,-1751,-4052,-601,3703,2751,-2106,-3973,-201,3857,2440,-2440,-3857,201,3973,2106,-2751,-3703,601,4052,1751,-3035,-3513,995,4091,1380,-3290},
    {3166,-1931,-3920,401,4076,1189,-3612,-2598,2598,3612,-1189,-4076,-401,3920,1931,-3166,-3166,1931,3920,-401,-4076,-1189,3612,2598,-2598,-3612,1189,4076,401,-3920,-1931,3166},
    {3035,-2440,-3513,1751,3857,-995,-4052,201,4091,601,-3973,-1380,3703,2106,-3290,-2751,2751,3290,-2106,-3703,1380,3973,-601,-4091,-201,4052,995,-3857,-1751,3513,2440,-3035},
    {2896,-2896,-2896,2896,2896,-2896,-2896,2896,2896,-2896,-2896,2896,2896,-2896,-2896,2896,2896,-2896,-2896,2896,2896,-2896,-2896,2896,2896,-2896,-2896,2896,2896,-2896,-2896,2896},
    {2751,-3290,-2106,3703,1380,-3973,-601,4091,-201,-4052,995,3857,-1751,-3513,2440,3035,-3035,-2440,3513,1751,-3857,-995,4052,201,-4091,601,3973,-1380,-3703,2106,3290,-2751},
    {2598,-3612,-1189,4076,-401,-3920,1931,3166,-3166,-1931,3920,401,-4076,1189,3612,-2598,-2598,3612,1189,-4076,401,3920,-1931,-3166,3166,1931,-3920,-401,4076,-1189,-3612,2598},
    {2440,-3857,-201,3973,-2106,-2751,3703,601,-4052,1751,3035,-3513,-995,4091,-1380,-3290,3290,1380,-4091,995,3513,-3035,-1751,4052,-601,-3703,2751,2106,-3973,201,3857,-2440},
    {2276,-4017,799,3406,-3406,-799,4017,-2276,-2276,4017,-799,-3406,3406,799,-4017,2276,2276,-4017,799,3406,-3406,-799,4017,-2276,-2276,4017,-799,-3406,3406,799,-4017,2276},
    {2106,-4091,1751,2440,-4052,1380,2751,-3973,995,3035,-3857,601,3290,-3703,201,3513,-3513,-201,3703,-3290,-601,3857,-3035,-995,3973,-2751,-1380,4052,-2440,-1751,4091,-2106},
    {1931,-4076,2598,1189,-3920,3166,401,-3612,3612,-401,-3166,3920,-1189,-2598,4076,-1931,-1931,4076,-2598,-1189,3920,-3166,-401,3612,-3612,401,3166,-3920,1189,2598,-4076,1931},
    {1751,-3973,3290,-201,-3035,4052,-2106,-1380,3857,-3513,601,2751,-4091,2440,995,-3703,3703,-995,-2440,4091,-2751,-601,3513,-3857,1380,2106,-4052,3035,201,-3290,3973,-1751},
    {1567,-3784,3784,-1567,-1567,3784,-3784,1567,1567,-3784,3784,-1567,-1567,3784,-3784,1567,1567,-3784,3784,-1567,-1567,3784,-3784,1567,1567,-3784,3784,-1567,-1567,3784,-3784,1567},
    {1380,-3513,4052,-2751,201,2440,-3973,3703,-1751,-995,3290,-4091,3035,-601,-2106,3857,-3857,2106,601,-3035,4091,-3290,995,1751,-3703,3973,-2440,-201,2751,-4052,3513,-1380},
    {1189,-3166,4076,-3612,1931,401,-2598,3920,-3920,2598,-401,-1931,3612,-4076,3166,-1189,-1189,3166,-4076,3612,-1931,-401,2598,-3920,3920,-2598,401,1931,-3612,4076,-3166,1189},
    {995,-2751,3857,-4052,3290,-1751,-201,2106,-3513,4091,-3703,2440,-601,-1380,3035,-3973,3973,-3035,1380,601,-2440,3703,-4091,3513,-2106,201,1751,-3290,4052,-3857,2751,-995},
    {799,-2276,3406,-4017,4017,-3406,2276,-799,-799,2276,-3406,4017,-4017,3406,-2276,799,799,-2276,3406,-4017,4017,-3406,2276,-799,-799,2276,-3406,4017,-4017,3406,-2276,799},
    {601,-1751,2751,-3513,3973,-4091,3857,-3290,2440,-1380,201,995,-2106,3035,-3703,4052,-4052,3703,-3035,2106,-995,-201,1380,-2440,3290,-3857,4091,-3973,3513,-2751,1751,-601},
    {401,-1189,1931,-2598,3166,-3612,3920,-4076,4076,-3920,3612,-3166,2598,-1931,1189,-401,-401,1189,-1931,2598,-3166,3612,-3920,4076,-4076,3920,-3612,3166,-2598,1931,-1189,401},
    {201,-601,995,-1380,1751,-2106,2440,-2751,3035,-3290,3513,-3703,3857,-3973,4052,-4091,4091,-4052,3973,-3857,3703,-3513,3290,-3035,2751,-2440,2106,-1751,1380,-995,601,-201},
};

src/variable_zigzag_tables.inc

O variable_zigzag_tables.inc fecha o trio de arquivos incluídos pelo variable_transform.c, com as ordens de zigue-zague dos blocos de 4x4, 16x16 e 32x32.

O arquivo completo tem 94 linhas:

/* Fixed zig-zag scans for the normative 4x4, 16x16 and 32x32 transforms.
 * Values are natural-order offsets from the original diagonal scan.
 * Copyright (c) 2026 Micilini Roll. Licensed under the MIT License.
 */

const uint16_t N148_ZIGZAG_4[16] = {
    0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15,
};

const uint16_t N148_ZIGZAG_16[256] = {
    0, 1, 16, 32, 17, 2, 3, 18, 33, 48, 64, 49, 34, 19, 4, 5,
    20, 35, 50, 65, 80, 96, 81, 66, 51, 36, 21, 6, 7, 22, 37, 52,
    67, 82, 97, 112, 128, 113, 98, 83, 68, 53, 38, 23, 8, 9, 24, 39,
    54, 69, 84, 99, 114, 129, 144, 160, 145, 130, 115, 100, 85, 70, 55, 40,
    25, 10, 11, 26, 41, 56, 71, 86, 101, 116, 131, 146, 161, 176, 192, 177,
    162, 147, 132, 117, 102, 87, 72, 57, 42, 27, 12, 13, 28, 43, 58, 73,
    88, 103, 118, 133, 148, 163, 178, 193, 208, 224, 209, 194, 179, 164, 149, 134,
    119, 104, 89, 74, 59, 44, 29, 14, 15, 30, 45, 60, 75, 90, 105, 120,
    135, 150, 165, 180, 195, 210, 225, 240, 241, 226, 211, 196, 181, 166, 151, 136,
    121, 106, 91, 76, 61, 46, 31, 47, 62, 77, 92, 107, 122, 137, 152, 167,
    182, 197, 212, 227, 242, 243, 228, 213, 198, 183, 168, 153, 138, 123, 108, 93,
    78, 63, 79, 94, 109, 124, 139, 154, 169, 184, 199, 214, 229, 244, 245, 230,
    215, 200, 185, 170, 155, 140, 125, 110, 95, 111, 126, 141, 156, 171, 186, 201,
    216, 231, 246, 247, 232, 217, 202, 187, 172, 157, 142, 127, 143, 158, 173, 188,
    203, 218, 233, 248, 249, 234, 219, 204, 189, 174, 159, 175, 190, 205, 220, 235,
    250, 251, 236, 221, 206, 191, 207, 222, 237, 252, 253, 238, 223, 239, 254, 255,
};

const uint16_t N148_ZIGZAG_32[1024] = {
    0, 1, 32, 64, 33, 2, 3, 34, 65, 96, 128, 97, 66, 35, 4, 5,
    36, 67, 98, 129, 160, 192, 161, 130, 99, 68, 37, 6, 7, 38, 69, 100,
    131, 162, 193, 224, 256, 225, 194, 163, 132, 101, 70, 39, 8, 9, 40, 71,
    102, 133, 164, 195, 226, 257, 288, 320, 289, 258, 227, 196, 165, 134, 103, 72,
    41, 10, 11, 42, 73, 104, 135, 166, 197, 228, 259, 290, 321, 352, 384, 353,
    322, 291, 260, 229, 198, 167, 136, 105, 74, 43, 12, 13, 44, 75, 106, 137,
    168, 199, 230, 261, 292, 323, 354, 385, 416, 448, 417, 386, 355, 324, 293, 262,
    231, 200, 169, 138, 107, 76, 45, 14, 15, 46, 77, 108, 139, 170, 201, 232,
    263, 294, 325, 356, 387, 418, 449, 480, 512, 481, 450, 419, 388, 357, 326, 295,
    264, 233, 202, 171, 140, 109, 78, 47, 16, 17, 48, 79, 110, 141, 172, 203,
    234, 265, 296, 327, 358, 389, 420, 451, 482, 513, 544, 576, 545, 514, 483, 452,
    421, 390, 359, 328, 297, 266, 235, 204, 173, 142, 111, 80, 49, 18, 19, 50,
    81, 112, 143, 174, 205, 236, 267, 298, 329, 360, 391, 422, 453, 484, 515, 546,
    577, 608, 640, 609, 578, 547, 516, 485, 454, 423, 392, 361, 330, 299, 268, 237,
    206, 175, 144, 113, 82, 51, 20, 21, 52, 83, 114, 145, 176, 207, 238, 269,
    300, 331, 362, 393, 424, 455, 486, 517, 548, 579, 610, 641, 672, 704, 673, 642,
    611, 580, 549, 518, 487, 456, 425, 394, 363, 332, 301, 270, 239, 208, 177, 146,
    115, 84, 53, 22, 23, 54, 85, 116, 147, 178, 209, 240, 271, 302, 333, 364,
    395, 426, 457, 488, 519, 550, 581, 612, 643, 674, 705, 736, 768, 737, 706, 675,
    644, 613, 582, 551, 520, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179,
    148, 117, 86, 55, 24, 25, 56, 87, 118, 149, 180, 211, 242, 273, 304, 335,
    366, 397, 428, 459, 490, 521, 552, 583, 614, 645, 676, 707, 738, 769, 800, 832,
    801, 770, 739, 708, 677, 646, 615, 584, 553, 522, 491, 460, 429, 398, 367, 336,
    305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 27, 58, 89, 120, 151, 182,
    213, 244, 275, 306, 337, 368, 399, 430, 461, 492, 523, 554, 585, 616, 647, 678,
    709, 740, 771, 802, 833, 864, 896, 865, 834, 803, 772, 741, 710, 679, 648, 617,
    586, 555, 524, 493, 462, 431, 400, 369, 338, 307, 276, 245, 214, 183, 152, 121,
    90, 59, 28, 29, 60, 91, 122, 153, 184, 215, 246, 277, 308, 339, 370, 401,
    432, 463, 494, 525, 556, 587, 618, 649, 680, 711, 742, 773, 804, 835, 866, 897,
    928, 960, 929, 898, 867, 836, 805, 774, 743, 712, 681, 650, 619, 588, 557, 526,
    495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154, 123, 92, 61, 30,
    31, 62, 93, 124, 155, 186, 217, 248, 279, 310, 341, 372, 403, 434, 465, 496,
    527, 558, 589, 620, 651, 682, 713, 744, 775, 806, 837, 868, 899, 930, 961, 992,
    993, 962, 931, 900, 869, 838, 807, 776, 745, 714, 683, 652, 621, 590, 559, 528,
    497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 95,
    126, 157, 188, 219, 250, 281, 312, 343, 374, 405, 436, 467, 498, 529, 560, 591,
    622, 653, 684, 715, 746, 777, 808, 839, 870, 901, 932, 963, 994, 995, 964, 933,
    902, 871, 840, 809, 778, 747, 716, 685, 654, 623, 592, 561, 530, 499, 468, 437,
    406, 375, 344, 313, 282, 251, 220, 189, 158, 127, 159, 190, 221, 252, 283, 314,
    345, 376, 407, 438, 469, 500, 531, 562, 593, 624, 655, 686, 717, 748, 779, 810,
    841, 872, 903, 934, 965, 996, 997, 966, 935, 904, 873, 842, 811, 780, 749, 718,
    687, 656, 625, 594, 563, 532, 501, 470, 439, 408, 377, 346, 315, 284, 253, 222,
    191, 223, 254, 285, 316, 347, 378, 409, 440, 471, 502, 533, 564, 595, 626, 657,
    688, 719, 750, 781, 812, 843, 874, 905, 936, 967, 998, 999, 968, 937, 906, 875,
    844, 813, 782, 751, 720, 689, 658, 627, 596, 565, 534, 503, 472, 441, 410, 379,
    348, 317, 286, 255, 287, 318, 349, 380, 411, 442, 473, 504, 535, 566, 597, 628,
    659, 690, 721, 752, 783, 814, 845, 876, 907, 938, 969, 1000, 1001, 970, 939, 908,
    877, 846, 815, 784, 753, 722, 691, 660, 629, 598, 567, 536, 505, 474, 443, 412,
    381, 350, 319, 351, 382, 413, 444, 475, 506, 537, 568, 599, 630, 661, 692, 723,
    754, 785, 816, 847, 878, 909, 940, 971, 1002, 1003, 972, 941, 910, 879, 848, 817,
    786, 755, 724, 693, 662, 631, 600, 569, 538, 507, 476, 445, 414, 383, 415, 446,
    477, 508, 539, 570, 601, 632, 663, 694, 725, 756, 787, 818, 849, 880, 911, 942,
    973, 1004, 1005, 974, 943, 912, 881, 850, 819, 788, 757, 726, 695, 664, 633, 602,
    571, 540, 509, 478, 447, 479, 510, 541, 572, 603, 634, 665, 696, 727, 758, 789,
    820, 851, 882, 913, 944, 975, 1006, 1007, 976, 945, 914, 883, 852, 821, 790, 759,
    728, 697, 666, 635, 604, 573, 542, 511, 543, 574, 605, 636, 667, 698, 729, 760,
    791, 822, 853, 884, 915, 946, 977, 1008, 1009, 978, 947, 916, 885, 854, 823, 792,
    761, 730, 699, 668, 637, 606, 575, 607, 638, 669, 700, 731, 762, 793, 824, 855,
    886, 917, 948, 979, 1010, 1011, 980, 949, 918, 887, 856, 825, 794, 763, 732, 701,
    670, 639, 671, 702, 733, 764, 795, 826, 857, 888, 919, 950, 981, 1012, 1013, 982,
    951, 920, 889, 858, 827, 796, 765, 734, 703, 735, 766, 797, 828, 859, 890, 921,
    952, 983, 1014, 1015, 984, 953, 922, 891, 860, 829, 798, 767, 799, 830, 861, 892,
    923, 954, 985, 1016, 1017, 986, 955, 924, 893, 862, 831, 863, 894, 925, 956, 987,
    1018, 1019, 988, 957, 926, 895, 927, 958, 989, 1020, 1021, 990, 959, 991, 1022, 1023,
};

Novos na pasta src: o filtro em laço

src/loop_filter.h

O loop_filter.h é a interface do filtro em laço do artigo 34, com o desbloqueio e o deringing.

O arquivo completo tem 63 linhas:

/*
 * N.148i causal deblocking and deringing filter.
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#ifndef N148_LOOP_FILTER_H
#define N148_LOOP_FILTER_H

#include <stdint.h>

#include "ppm.h"

typedef struct {
    uint64_t deblocked_samples;
    uint64_t deringed_samples;
} N148LoopFilterStats;

typedef struct {
    int strength;
    int threshold;
    int use_avx2;
} N148LoopFilterPrepared;

typedef enum {
    N148_LOOP_FILTER_OFF = 0,
    N148_LOOP_FILTER_LEGACY = 1,
    N148_LOOP_FILTER_QUANT_ADAPTIVE_LUMA = 2
} N148LoopFilterPolicy;

/* Return the normative maximum per-pass sample adjustment. */
int n148_loop_filter_strength(int quality, int plane_index,
                              uint8_t adaptive_level);

/* Derive the quant-adaptive luma strength from the calibrated residual table's nominal
   DC quantization step. This policy deliberately ignores segmentation. */
int n148_loop_filter_quant_luma_strength(int quality);

/* Prepare the invariant parameters once when reconstructing a plane. */
int n148_loop_filter_prepare(int quality, int plane_index,
                             uint8_t adaptive_level, int quant_adaptive_luma,
                             N148LoopFilterPrepared *prepared);
int n148_loop_filter_block_prepared(Plane *plane, int x0, int y0, int size,
                                    const N148LoopFilterPrepared *prepared,
                                    N148LoopFilterStats *stats);

/* Filter a newly reconstructed square before it becomes a prediction
   reference. The square size is 8, 16, or 32. Only already available top/left
   boundaries are crossed, which makes raster-order encoder and decoder
   behavior identical. */
int n148_loop_filter_block(Plane *plane, int x0, int y0, int size,
                           int quality, int plane_index,
                           uint8_t adaptive_level,
                           N148LoopFilterStats *stats);

/* Apply the quant-adaptive policy to luma while retaining the base
   policy for chroma. */
int n148_loop_filter_quant_luma_block(Plane *plane, int x0, int y0, int size,
                              int quality, int plane_index,
                              N148LoopFilterStats *stats);

#endif

src/loop_filter.c

O loop_filter.c implementa esse filtro só com números inteiros, decidindo a força a partir da qualidade e de cada borda entre os blocos.

O arquivo completo tem 637 linhas:

/*
 * N.148i causal deblocking and deringing filter.
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 *
 * This original filter is deliberately small and integer-only. It operates
 * as part of reconstructed-neighbor prediction, so its exact order and
 * rounding are normative for streams carrying the LOOP_FILTER flag.
 */

#include "loop_filter.h"

#include <stdlib.h>
#include <string.h>

#include "adaptive_quant.h"
#include "cpu.h"
#include "tables.h"

#if defined(__x86_64__) || defined(__i386__)
#include <immintrin.h>
#endif

static int absolute(int value) {
    return value < 0 ? -value : value;
}

static int clamp_integer(int value, int minimum, int maximum) {
    if (value < minimum) return minimum;
    if (value > maximum) return maximum;
    return value;
}

static uint8_t clamp_byte(int value) {
    return (uint8_t) clamp_integer(value, 0, 255);
}

static int rounded_signed_division(int value, int divisor) {
    return value >= 0 ? (value + divisor / 2) / divisor :
        -((-value + divisor / 2) / divisor);
}

int n148_loop_filter_strength(int quality, int plane_index,
                              uint8_t adaptive_level) {
    if (quality < 1 || quality > 100 || plane_index < 0 || plane_index > 2 ||
        adaptive_level >= N148_AQ_LEVEL_COUNT) return -1;
    if (quality >= 96) return 0;
    int loss = 100 - quality;
    int strength = (loss + 19) / 20;
    if (adaptive_level == 0 && strength > 1) strength--;
    if (adaptive_level == 3) strength++;
    if (plane_index != 0 && strength > 1)
        strength = (strength * 3 + 2) / 4;
    if (strength > 5) strength = 5;
    return strength;
}

int n148_loop_filter_quant_luma_strength(int quality) {
    if (quality < 1 || quality > 100) return -1;
    int table[8][8];
    scale_table(FORMAT_5_LUMA_QUANT_BASE, quality, table);
    int quant_step = table[0][0];
    if (quant_step <= 2) return 0;
    int strength = (quant_step + 8) / 9;
    return strength > 5 ? 5 : strength;
}

static int edge_threshold(int quality, uint8_t adaptive_level) {
    int threshold = 3 + (100 - quality + 3) / 4;
    static const int scale[N148_AQ_LEVEL_COUNT] = {90, 97, 108, 118};
    threshold = (threshold * scale[adaptive_level] + 50) / 100;
    return threshold < 3 ? 3 : threshold;
}

static int filter_edge_sample(uint8_t *p1, uint8_t *p0,
                              uint8_t *q0, uint8_t *q1,
                              int strength, int threshold) {
    int p1_value = *p1;
    int p0_value = *p0;
    int q0_value = *q0;
    int q1_value = *q1;
    int gap = absolute(q0_value - p0_value);
    int side_activity = absolute(p0_value - p1_value) +
        absolute(q1_value - q0_value);
    if (gap < 2 || gap > threshold ||
        side_activity > threshold + strength) return 0;

    int delta = rounded_signed_division(
        3 * (q0_value - p0_value) + p1_value - q1_value, 8);
    delta = clamp_integer(delta, -strength, strength);
    if (delta == 0) return 0;
    *p0 = clamp_byte(p0_value + delta);
    *q0 = clamp_byte(q0_value - delta);
    if (strength >= 3 && side_activity <= threshold / 2) {
        int secondary = rounded_signed_division(delta, 2);
        *p1 = clamp_byte(p1_value + secondary);
        *q1 = clamp_byte(q1_value - secondary);
    }
    return 1;
}

#if defined(__x86_64__) || defined(__i386__)
/* A vertical edge has four contiguous source bytes per row. Gather eight
   rows, filter them together, then scatter the four bytes back per row. */
__attribute__((target("avx2")))
static uint64_t filter_vertical_simd(Plane *plane, int x0, int y0,
                                     int height, int strength, int threshold,
                                     int count_changes) {
    const __m128i zero = _mm_setzero_si128();
    const __m128i two = _mm_set1_epi16(2);
    const __m128i three = _mm_set1_epi16(3);
    const __m128i four = _mm_set1_epi16(4);
    const __m128i one = _mm_set1_epi16(1);
    const __m128i limit = _mm_set1_epi16((short)strength);
    const __m128i minus_limit = _mm_sub_epi16(zero, limit);
    const __m128i edge_limit = _mm_set1_epi16((short)threshold);
    const __m128i activity_limit = _mm_set1_epi16(
        (short)(threshold + strength));
    const __m128i secondary_limit = _mm_set1_epi16((short)(threshold / 2));
    const __m128i masks[4] = {
        _mm_setr_epi8(0, 4, 8, 12, -1, -1, -1, -1,
                      -1, -1, -1, -1, -1, -1, -1, -1),
        _mm_setr_epi8(1, 5, 9, 13, -1, -1, -1, -1,
                      -1, -1, -1, -1, -1, -1, -1, -1),
        _mm_setr_epi8(2, 6, 10, 14, -1, -1, -1, -1,
                      -1, -1, -1, -1, -1, -1, -1, -1),
        _mm_setr_epi8(3, 7, 11, 15, -1, -1, -1, -1,
                      -1, -1, -1, -1, -1, -1, -1, -1),
    };
    uint64_t changed = 0;
    int row = 0;
    for (; row + 8 <= height; row += 8) {
        uint8_t *edge[8];
        __m128i pixels[8];
        for (int i = 0; i < 8; i++) {
            edge[i] = plane->data +
                (long)(y0 + row + i) * plane->width + x0;
            pixels[i] = _mm_loadu_si32(edge[i] - 2);
        }
        __m128i first = _mm_unpacklo_epi64(
            _mm_unpacklo_epi32(pixels[0], pixels[1]),
            _mm_unpacklo_epi32(pixels[2], pixels[3]));
        __m128i second = _mm_unpacklo_epi64(
            _mm_unpacklo_epi32(pixels[4], pixels[5]),
            _mm_unpacklo_epi32(pixels[6], pixels[7]));
        __m128i values[4];
        for (int i = 0; i < 4; i++) {
            __m128i lo = _mm_shuffle_epi8(first, masks[i]);
            __m128i hi = _mm_shuffle_epi8(second, masks[i]);
            values[i] = _mm_unpacklo_epi8(
                _mm_or_si128(lo, _mm_slli_si128(hi, 4)), zero);
        }
        __m128i p1 = values[0], p0 = values[1];
        __m128i q0 = values[2], q1 = values[3];
        __m128i gap = _mm_abs_epi16(_mm_sub_epi16(q0, p0));
        __m128i side = _mm_add_epi16(
            _mm_abs_epi16(_mm_sub_epi16(p0, p1)),
            _mm_abs_epi16(_mm_sub_epi16(q1, q0)));
        __m128i blocked = _mm_or_si128(
            _mm_or_si128(_mm_cmpgt_epi16(two, gap),
                         _mm_cmpgt_epi16(gap, edge_limit)),
            _mm_cmpgt_epi16(side, activity_limit));
        __m128i numerator = _mm_add_epi16(
            _mm_mullo_epi16(_mm_sub_epi16(q0, p0), three),
            _mm_sub_epi16(p1, q1));
        __m128i magnitude = _mm_srli_epi16(
            _mm_add_epi16(_mm_abs_epi16(numerator), four), 3);
        __m128i delta = _mm_blendv_epi8(
            magnitude, _mm_sub_epi16(zero, magnitude),
            _mm_cmpgt_epi16(zero, numerator));
        delta = _mm_min_epi16(_mm_max_epi16(delta, minus_limit), limit);
        __m128i active = _mm_andnot_si128(
            _mm_or_si128(blocked, _mm_cmpeq_epi16(delta, zero)),
            _mm_set1_epi16(-1));
        p0 = _mm_blendv_epi8(p0, _mm_add_epi16(p0, delta), active);
        q0 = _mm_blendv_epi8(q0, _mm_sub_epi16(q0, delta), active);
        if (strength >= 3) {
            __m128i secondary_mask = _mm_andnot_si128(
                _mm_cmpgt_epi16(side, secondary_limit), active);
            __m128i half_magnitude = _mm_srli_epi16(
                _mm_add_epi16(_mm_abs_epi16(delta), one), 1);
            __m128i secondary = _mm_blendv_epi8(
                half_magnitude, _mm_sub_epi16(zero, half_magnitude),
                _mm_cmpgt_epi16(zero, delta));
            p1 = _mm_blendv_epi8(p1, _mm_add_epi16(p1, secondary),
                                 secondary_mask);
            q1 = _mm_blendv_epi8(q1, _mm_sub_epi16(q1, secondary),
                                 secondary_mask);
        }
        __m128i left = _mm_unpacklo_epi8(
            _mm_packus_epi16(p1, p1), _mm_packus_epi16(p0, p0));
        __m128i right = _mm_unpacklo_epi8(
            _mm_packus_epi16(q0, q0), _mm_packus_epi16(q1, q1));
        __m128i out0 = _mm_unpacklo_epi16(left, right);
        __m128i out1 = _mm_unpackhi_epi16(left, right);
        uint32_t packed[8];
        _mm_storeu_si128((__m128i *)packed, out0);
        _mm_storeu_si128((__m128i *)(packed + 4), out1);
        for (int i = 0; i < 8; i++)
            memcpy(edge[i] - 2, packed + i, sizeof(packed[i]));
        if (count_changes)
            changed += (uint64_t)__builtin_popcount(
                (unsigned)_mm_movemask_epi8(active)) / 2u;
    }
    for (; row < height; row++) {
        uint8_t *edge = plane->data +
            (long)(y0 + row) * plane->width + x0;
        int sample_changed = filter_edge_sample(
            edge - 2, edge - 1, edge, edge + 1, strength, threshold);
        if (count_changes) changed += (uint64_t)sample_changed;
    }
    return changed;
}

__attribute__((target("avx2")))
static uint64_t filter_horizontal_simd(Plane *plane, int x0, int y0,
                                       int width, int strength, int threshold,
                                       int count_changes) {
    const __m128i zero = _mm_setzero_si128();
    const __m128i two = _mm_set1_epi16(2);
    const __m128i three = _mm_set1_epi16(3);
    const __m128i four = _mm_set1_epi16(4);
    const __m128i one = _mm_set1_epi16(1);
    const __m128i limit = _mm_set1_epi16((short) strength);
    const __m128i minus_limit = _mm_sub_epi16(zero, limit);
    const __m128i edge_limit = _mm_set1_epi16((short) threshold);
    const __m128i activity_limit = _mm_set1_epi16(
        (short)(threshold + strength));
    const __m128i secondary_limit = _mm_set1_epi16((short)(threshold / 2));
    uint64_t changed = 0;
    for (int column = 0; column < width; column += 8) {
        uint8_t *q0_ptr = plane->data + (long)y0 * plane->width + x0 + column;
        uint8_t *p0_ptr = q0_ptr - plane->width;
        uint8_t *p1_ptr = p0_ptr - plane->width;
        uint8_t *q1_ptr = q0_ptr + plane->width;
        __m128i p1 = _mm_unpacklo_epi8(
            _mm_loadl_epi64((const __m128i *)p1_ptr), zero);
        __m128i p0 = _mm_unpacklo_epi8(
            _mm_loadl_epi64((const __m128i *)p0_ptr), zero);
        __m128i q0 = _mm_unpacklo_epi8(
            _mm_loadl_epi64((const __m128i *)q0_ptr), zero);
        __m128i q1 = _mm_unpacklo_epi8(
            _mm_loadl_epi64((const __m128i *)q1_ptr), zero);
        __m128i gap = _mm_abs_epi16(_mm_sub_epi16(q0, p0));
        __m128i side = _mm_add_epi16(
            _mm_abs_epi16(_mm_sub_epi16(p0, p1)),
            _mm_abs_epi16(_mm_sub_epi16(q1, q0)));
        __m128i blocked = _mm_or_si128(
            _mm_or_si128(_mm_cmpgt_epi16(two, gap),
                         _mm_cmpgt_epi16(gap, edge_limit)),
            _mm_cmpgt_epi16(side, activity_limit));
        __m128i numerator = _mm_add_epi16(
            _mm_mullo_epi16(_mm_sub_epi16(q0, p0), three),
            _mm_sub_epi16(p1, q1));
        __m128i magnitude = _mm_srli_epi16(
            _mm_add_epi16(_mm_abs_epi16(numerator), four), 3);
        __m128i negative = _mm_cmpgt_epi16(zero, numerator);
        __m128i delta = _mm_blendv_epi8(
            magnitude, _mm_sub_epi16(zero, magnitude), negative);
        delta = _mm_min_epi16(_mm_max_epi16(delta, minus_limit), limit);
        __m128i active = _mm_andnot_si128(
            _mm_or_si128(blocked, _mm_cmpeq_epi16(delta, zero)),
            _mm_set1_epi16(-1));
        __m128i new_p0 = _mm_blendv_epi8(
            p0, _mm_add_epi16(p0, delta), active);
        __m128i new_q0 = _mm_blendv_epi8(
            q0, _mm_sub_epi16(q0, delta), active);
        _mm_storel_epi64((__m128i *)p0_ptr,
                         _mm_packus_epi16(new_p0, new_p0));
        _mm_storel_epi64((__m128i *)q0_ptr,
                         _mm_packus_epi16(new_q0, new_q0));
        if (strength >= 3) {
            __m128i secondary_mask = _mm_andnot_si128(
                _mm_cmpgt_epi16(side, secondary_limit), active);
            __m128i half_magnitude = _mm_srli_epi16(
                _mm_add_epi16(_mm_abs_epi16(delta), one), 1);
            __m128i secondary = _mm_blendv_epi8(
                half_magnitude, _mm_sub_epi16(zero, half_magnitude),
                _mm_cmpgt_epi16(zero, delta));
            __m128i new_p1 = _mm_blendv_epi8(
                p1, _mm_add_epi16(p1, secondary), secondary_mask);
            __m128i new_q1 = _mm_blendv_epi8(
                q1, _mm_sub_epi16(q1, secondary), secondary_mask);
            _mm_storel_epi64((__m128i *)p1_ptr,
                             _mm_packus_epi16(new_p1, new_p1));
            _mm_storel_epi64((__m128i *)q1_ptr,
                             _mm_packus_epi16(new_q1, new_q1));
        }
        if (count_changes)
            changed += (uint64_t)__builtin_popcount(
                (unsigned)_mm_movemask_epi8(active)) / 2u;
    }
    return changed;
}

__attribute__((target("avx2")))
static uint64_t dering_square_avx2(Plane *plane, int x0, int y0, int size,
                                   int strength, int threshold,
                                   const uint8_t *source,
                                   int count_changes) {
    const __m256i zero = _mm256_setzero_si256();
    const __m256i two = _mm256_set1_epi16(2);
    const __m256i limit = _mm256_set1_epi16((short) strength);
    const __m256i negative_limit = _mm256_sub_epi16(zero, limit);
    const __m256i edge_threshold = _mm256_set1_epi16((short) threshold);
    const __m256i first_mask = _mm256_setr_epi16(
        0, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1);
    const __m256i last_mask = _mm256_setr_epi16(
        -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, 0);
    const __m256i paired_8_mask = _mm256_setr_epi16(
        0, -1, -1, -1, -1, -1, -1, 0,
        0, -1, -1, -1, -1, -1, -1, 0);
    uint64_t changed = 0;
    /* Pair adjacent interior rows for 8x8 blocks. Larger blocks process
       sixteen horizontal samples at a time. */
    int paired_rows = size == 8;
    for (int row = 1; row + 1 < size; row += paired_rows ? 2 : 1) {
        for (int column = 0; column < size; column += 16) {
            const uint8_t *p = source + row * size + column;
            __m256i interior = paired_rows ? paired_8_mask :
                _mm256_set1_epi16(-1);
            if (!paired_rows && column == 0)
                interior = _mm256_and_si256(interior, first_mask);
            if (!paired_rows && column + 16 == size)
                interior = _mm256_and_si256(interior, last_mask);
            __m256i center = _mm256_cvtepu8_epi16(
                _mm_loadu_si128((const __m128i *) p));
            __m256i left = _mm256_cvtepu8_epi16(
                _mm_loadu_si128((const __m128i *)(p - 1)));
            __m256i right = _mm256_cvtepu8_epi16(
                _mm_loadu_si128((const __m128i *)(p + 1)));
            __m256i top = _mm256_cvtepu8_epi16(
                _mm_loadu_si128((const __m128i *)(p - size)));
            __m256i bottom = _mm256_cvtepu8_epi16(
                _mm_loadu_si128((const __m128i *)(p + size)));
            __m256i horizontal = _mm256_abs_epi16(
                _mm256_sub_epi16(left, right));
            __m256i vertical = _mm256_abs_epi16(
                _mm256_sub_epi16(top, bottom));
            __m256i use_vertical = _mm256_cmpgt_epi16(horizontal, vertical);
            __m256i first = _mm256_blendv_epi8(left, top, use_vertical);
            __m256i second = _mm256_blendv_epi8(right, bottom, use_vertical);
            __m256i gap = _mm256_abs_epi16(_mm256_sub_epi16(first, second));
            __m256i within_threshold = _mm256_andnot_si256(
                _mm256_cmpgt_epi16(gap, edge_threshold), interior);
            __m256i minimum = _mm256_min_epi16(first, second);
            __m256i maximum = _mm256_max_epi16(first, second);
            __m256i outside = _mm256_or_si256(
                _mm256_cmpgt_epi16(_mm256_sub_epi16(minimum, limit), center),
                _mm256_cmpgt_epi16(center, _mm256_add_epi16(maximum, limit)));
            __m256i average = _mm256_srli_epi16(_mm256_add_epi16(
                _mm256_add_epi16(first, second),
                _mm256_add_epi16(_mm256_slli_epi16(center, 1), two)), 2);
            __m256i delta = _mm256_sub_epi16(average, center);
            delta = _mm256_min_epi16(
                _mm256_max_epi16(delta, negative_limit), limit);
            __m256i nonzero = _mm256_andnot_si256(
                _mm256_cmpeq_epi16(delta, zero), interior);
            __m256i change_mask = _mm256_and_si256(
                _mm256_and_si256(within_threshold, outside), nonzero);
            __m256i result = _mm256_blendv_epi8(
                center, _mm256_add_epi16(center, delta), change_mask);
            __m128i packed = _mm_packus_epi16(
                _mm256_castsi256_si128(result),
                _mm256_extracti128_si256(result, 1));
            uint8_t *destination = plane->data +
                (long)(y0 + row) * plane->width + x0 + column;
            if (paired_rows) {
                _mm_storel_epi64((__m128i *)destination, packed);
                _mm_storel_epi64((__m128i *)(destination + plane->width),
                                 _mm_srli_si128(packed, 8));
            } else {
                _mm_storeu_si128((__m128i *)destination, packed);
            }
            if (count_changes)
                changed += (uint64_t) __builtin_popcount(
                    (unsigned) _mm256_movemask_epi8(change_mask)) / 2u;
        }
    }
    return changed;
}
/* Original exact byte-domain implementation of N.148's existing deringer.
 * All samples and bounded results remain in [0,255]. */
__attribute__((target("avx2"), always_inline))
static inline __m256i dering_bytes_vector(
    __m256i center, __m256i left, __m256i right, __m256i top,
    __m256i bottom, __m256i interior, int strength, int threshold,
    __m256i *changed) {
    const __m256i one = _mm256_set1_epi8(1);
    const __m256i limit = _mm256_set1_epi8((char)strength);
    const __m256i edge = _mm256_set1_epi8((char)threshold);
    __m256i horizontal = _mm256_or_si256(
        _mm256_subs_epu8(left,right), _mm256_subs_epu8(right,left));
    __m256i vertical = _mm256_or_si256(
        _mm256_subs_epu8(top,bottom), _mm256_subs_epu8(bottom,top));
    __m256i gap = _mm256_min_epu8(horizontal,vertical);
    __m256i use_horizontal = _mm256_cmpeq_epi8(gap,horizontal);
    __m256i first = _mm256_blendv_epi8(top,left,use_horizontal);
    __m256i second = _mm256_blendv_epi8(bottom,right,use_horizontal);
    __m256i within = _mm256_cmpeq_epi8(_mm256_min_epu8(gap,edge),gap);
    __m256i minimum = _mm256_subs_epu8(_mm256_min_epu8(first,second),limit);
    __m256i maximum = _mm256_adds_epu8(_mm256_max_epu8(first,second),limit);
    __m256i clipped = _mm256_min_epu8(_mm256_max_epu8(center,minimum),maximum);
    __m256i outside = _mm256_andnot_si256(
        _mm256_cmpeq_epi8(clipped,center),interior);
    /* avg_epu8 rounds upward. Its two-stage result differs from the
       required floor((first+second+2*center+2)/4) only when that numerator
       without +2 is 1 modulo 4. The parity correction removes exactly 1. */
    __m256i neighbor_average = _mm256_avg_epu8(first,second);
    __m256i correction = _mm256_and_si256(one,_mm256_and_si256(
        _mm256_xor_si256(first,second),
        _mm256_xor_si256(center,neighbor_average)));
    __m256i average = _mm256_sub_epi8(
        _mm256_avg_epu8(center,neighbor_average),correction);
    __m256i result = _mm256_min_epu8(
        _mm256_max_epu8(average,_mm256_subs_epu8(center,limit)),
        _mm256_adds_epu8(center,limit));
    __m256i active = _mm256_and_si256(within,outside);
    *changed = _mm256_andnot_si256(_mm256_cmpeq_epi8(result,center),active);
    return _mm256_blendv_epi8(center,result,active);
}

__attribute__((target("avx2"), always_inline))
static inline __m256i load_dering_bytes(const uint8_t *p, int half) {
    return half ? _mm256_inserti128_si256(_mm256_setzero_si256(),
        _mm_loadu_si128((const __m128i *)p),0) :
        _mm256_loadu_si256((const __m256i *)p);
}

__attribute__((target("avx2")))
static uint64_t dering_square_bytes(Plane *plane, int x0, int y0,
    int size, int strength, int threshold, const uint8_t *source,
    int count_changes) {
    __m256i interior;
    if (size == 8) interior = _mm256_set1_epi64x(0x00ffffffffffff00ll);
    else if (size == 16) interior = _mm256_setr_epi64x(
        -256ll,0x00ffffffffffffffll,-256ll,0x00ffffffffffffffll);
    else interior = _mm256_setr_epi64x(-256ll,-1ll,-1ll,0x00ffffffffffffffll);
    uint64_t changed_count = 0;
    int step = 32 / size;
    for (int row = 1; row + 1 < size; row += step) {
        int half = size == 8 && row == 5;
        int rows = half ? 2 : step;
        const uint8_t *p = source + row*size;
        __m256i changed;
        __m256i result = dering_bytes_vector(
            load_dering_bytes(p,half), load_dering_bytes(p-1,half),
            load_dering_bytes(p+1,half), load_dering_bytes(p-size,half),
            load_dering_bytes(p+size,half),interior,strength,threshold,&changed);
        uint8_t *destination = plane->data+(long)(y0+row)*plane->width+x0;
        __m128i lo = _mm256_castsi256_si128(result);
        __m128i hi = _mm256_extracti128_si256(result,1);
        if (size == 8) {
            _mm_storel_epi64((__m128i *)destination,lo);
            _mm_storel_epi64((__m128i *)(destination+plane->width),_mm_srli_si128(lo,8));
            if (rows == 4) {
                _mm_storel_epi64((__m128i *)(destination+2*plane->width),hi);
                _mm_storel_epi64((__m128i *)(destination+3*plane->width),_mm_srli_si128(hi,8));
            }
        } else if (size == 16) {
            _mm_storeu_si128((__m128i *)destination,lo);
            _mm_storeu_si128((__m128i *)(destination+plane->width),hi);
        } else _mm256_storeu_si256((__m256i *)destination,result);
        if (count_changes) {
            unsigned mask = (unsigned)_mm256_movemask_epi8(changed);
            if (half) mask &= 0xffffu;
            changed_count += (uint64_t)__builtin_popcount(mask);
        }
    }
    return changed_count;
}

#endif

static uint64_t dering_square(Plane *plane, int x0, int y0, int width,
                              int height, int strength, int threshold,
                              int count_changes, int use_avx2) {
    if (width < 3 || height < 3 || strength <= 0) return 0;
    uint8_t source[32 * 32];
    for (int row = 0; row < height; row++) {
        memcpy(source + row * width,
               plane->data + (long)(y0 + row) * plane->width + x0,
               (size_t) width);
    }
#if defined(__x86_64__) || defined(__i386__)
    if (width == height &&
        (width == 8 || width == 16 || width == 32) &&
        use_avx2) {
        if (strength <= 255 && threshold >= 0 && threshold <= 255)
            return dering_square_bytes(plane, x0, y0, width, strength,
                                       threshold, source, count_changes);
        return dering_square_avx2(plane, x0, y0, width, strength,
                                  threshold, source, count_changes);
    }
#endif
    (void) use_avx2;
    uint64_t changed = 0;
    for (int row = 1; row + 1 < height; row++) {
        for (int column = 1; column + 1 < width; column++) {
            int center = source[row * width + column];
            int left = source[row * width + column - 1];
            int right = source[row * width + column + 1];
            int top = source[(row - 1) * width + column];
            int bottom = source[(row + 1) * width + column];
            int first, second;
            if (absolute(left - right) <= absolute(top - bottom)) {
                first = left;
                second = right;
            } else {
                first = top;
                second = bottom;
            }
            if (absolute(first - second) > threshold) continue;
            int minimum = first < second ? first : second;
            int maximum = first > second ? first : second;
            int limited = clamp_integer(center, minimum - strength,
                                        maximum + strength);
            if (limited == center) continue;
            int average = (first + 2 * center + second + 2) / 4;
            int delta = clamp_integer(average - center,
                                      -strength, strength);
            if (delta == 0) continue;
            plane->data[(long)(y0 + row) * plane->width + x0 + column] =
                clamp_byte(center + delta);
            if (count_changes) changed++;
        }
    }
    return changed;
}

int n148_loop_filter_prepare(int quality, int plane_index,
                             uint8_t adaptive_level, int quant_adaptive_luma,
                             N148LoopFilterPrepared *prepared) {
    if (!prepared || quality < 1 || quality > 100 ||
        plane_index < 0 || plane_index > 2 ||
        adaptive_level >= N148_AQ_LEVEL_COUNT ||
        (quant_adaptive_luma != 0 && quant_adaptive_luma != 1)) return 0;
    prepared->strength = quant_adaptive_luma && plane_index == 0 ?
        n148_loop_filter_quant_luma_strength(quality) :
        n148_loop_filter_strength(quality, plane_index, adaptive_level);
    if (prepared->strength < 0) return 0;
    prepared->threshold = edge_threshold(quality, adaptive_level);
    prepared->use_avx2 = 0;
#if defined(__x86_64__) || defined(__i386__)
    if (prepared->strength > 0)
        prepared->use_avx2 = n148_cpu_level() >= N148_CPU_AVX2;
#endif
    return 1;
}

int n148_loop_filter_block_prepared(Plane *plane, int x0, int y0, int size,
                                    const N148LoopFilterPrepared *prepared,
                                    N148LoopFilterStats *stats) {
    if (!plane || !plane->data || plane->width <= 0 || plane->height <= 0 ||
        x0 < 0 || y0 < 0 || x0 >= plane->width || y0 >= plane->height ||
        (size != 8 && size != 16 && size != 32) || !prepared ||
        prepared->strength < 0) return 0;
    int strength = prepared->strength;
    int width = plane->width - x0;
    int height = plane->height - y0;
    if (width > size) width = size;
    if (height > size) height = size;
    if (width <= 0 || height <= 0 || strength == 0) return 1;
    int threshold = prepared->threshold;
    int use_avx2 = prepared->use_avx2;

    uint64_t deringed = dering_square(
        plane, x0, y0, width, height, strength, threshold,
        stats != NULL, use_avx2);
    uint64_t deblocked = 0;
    if (x0 >= 2 && x0 + 1 < plane->width) {
#if defined(__x86_64__) || defined(__i386__)
        if (height >= 8 && use_avx2) {
            deblocked += filter_vertical_simd(
                plane, x0, y0, height, strength, threshold, stats != NULL);
        } else
#endif
        for (int row = 0; row < height; row++) {
            uint8_t *edge = plane->data +
                (long)(y0 + row) * plane->width + x0;
            int changed = filter_edge_sample(
                edge - 2, edge - 1, edge, edge + 1,
                strength, threshold);
            if (stats) deblocked += (uint64_t) changed;
        }
    }
    if (y0 >= 2 && y0 + 1 < plane->height) {
#if defined(__x86_64__) || defined(__i386__)
        if (width >= 8 && width % 8 == 0 && use_avx2) {
            deblocked += filter_horizontal_simd(
                plane, x0, y0, width, strength, threshold, stats != NULL);
        } else
#endif
        for (int column = 0; column < width; column++) {
            uint8_t *edge = plane->data + (long) y0 * plane->width +
                x0 + column;
            int changed = filter_edge_sample(
                edge - 2 * plane->width, edge - plane->width,
                edge, edge + plane->width, strength, threshold);
            if (stats) deblocked += (uint64_t) changed;
        }
    }
    if (stats) {
        stats->deblocked_samples += deblocked;
        stats->deringed_samples += deringed;
    }
    return 1;
}

static int loop_filter_block(Plane *plane, int x0, int y0, int size,
                             int quality, int plane_index,
                             uint8_t adaptive_level, int quant_adaptive_luma,
                             N148LoopFilterStats *stats) {
    N148LoopFilterPrepared prepared;
    return n148_loop_filter_prepare(quality, plane_index, adaptive_level,
                                     quant_adaptive_luma, &prepared) &&
           n148_loop_filter_block_prepared(
               plane, x0, y0, size, &prepared, stats);
}

int n148_loop_filter_block(Plane *plane, int x0, int y0, int size,
                           int quality, int plane_index,
                           uint8_t adaptive_level,
                           N148LoopFilterStats *stats) {
    return loop_filter_block(plane, x0, y0, size, quality, plane_index,
                             adaptive_level, 0, stats);
}

int n148_loop_filter_quant_luma_block(Plane *plane, int x0, int y0, int size,
                              int quality, int plane_index,
                              N148LoopFilterStats *stats) {
    return loop_filter_block(plane, x0, y0, size, quality, plane_index,
                             1, 1, stats);
}

Novos na pasta src: a cor e a segmentação

src/perceptual.h

O perceptual.h é a interface do espaço de cor oponente da etapa 4, que ficou no cemitério de ideias.

O arquivo completo tem 28 linhas:

/*
 * N.148i perceptual colour transform.
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#ifndef N148_PERCEPTUAL_H
#define N148_PERCEPTUAL_H

#include <stdint.h>

/* Prepare the deterministic transfer tables before starting worker threads. */
void n148_perceptual_init(void);

/* Convert packed sRGB bytes to intensity, red-green, and blue-yellow planes. */
void n148_rgb_to_perceptual(const uint8_t *rgb, long count,
                            uint8_t *intensity, uint8_t *red_green,
                            uint8_t *blue_yellow);

/* Convert one reconstructed perceptual sample back to packed sRGB. The two
   opponent samples carry four fractional bits from chroma interpolation. */
void n148_perceptual_to_rgb(uint8_t intensity,
                            uint16_t red_green_scaled,
                            uint16_t blue_yellow_scaled,
                            uint8_t rgb[3]);

#endif

src/perceptual.c

O perceptual.c implementa essa transformada de cor, e ela continua no código porque o decoder da V2 ainda lê os arquivos feitos com esse experimento.

O arquivo completo tem 214 linhas:

/*
 * N.148i deterministic cone-opponent colour transform.
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 *
 * This is an original, deliberately compact perceptual transform. It applies
 * a cube-root response after deterministic gamma expansion, then stores one
 * perceptual intensity plus two opponent axes. Integer arithmetic defines the
 * bitstream-facing forward transform so the same RGB input cannot acquire
 * platform-dependent coefficients through libm.
 */

#include "perceptual.h"

#include <stddef.h>
#include <stdint.h>

#define PERCEPTUAL_MAX 65535
#define RESPONSE_TABLE_BITS 4
#define RESPONSE_TABLE_SIZE ((PERCEPTUAL_MAX >> RESPONSE_TABLE_BITS) + 2)
#define XYB_X_SCALE 59
#define XYB_B_SCALE 253
#define XYB_X_NEUTRAL 94
#define XYB_B_NEUTRAL 115
#define CHROMA_FRACTION_BITS 4
#define OPSIN_BIAS 0

/* Rounded, intentionally compact cone mixing. Rows sum to 4096, so neutral
   grey remains neutral. The coefficients follow broad cone sensitivities but
   are represented as small integers rather than importing another codec's
   floating-point implementation. */
static const int cone_matrix[3][3] = {
    {1700, 2160,  236},
    { 900, 2900,  296},
    { 120,  500, 3476},
};

/* Inverse of the integer matrix above in Q20 fixed point. */
static const int cone_inverse_q20[3][3] = {
    { 4170622, -3103133,  -18912},
    {-1298702,  2469386, -122107},
    {   42830,  -248077, 1253823},
};

static uint16_t response_table[RESPONSE_TABLE_SIZE];
static uint16_t response_to_linear[PERCEPTUAL_MAX + 1];
static uint16_t srgb_to_linear[256];
static uint8_t linear_to_srgb[PERCEPTUAL_MAX + 1];
static int tables_ready;

static uint16_t perceptual_response(uint16_t linear);

static uint64_t cube_u16(uint32_t value) {
    return (uint64_t) value * value * value;
}

static uint32_t nearest_cube_root_response(uint32_t linear) {
    uint64_t target = (uint64_t) linear * PERCEPTUAL_MAX * PERCEPTUAL_MAX;
    uint32_t low = 0;
    uint32_t high = PERCEPTUAL_MAX + 256;
    while (low < high) {
        uint32_t middle = low + (high - low + 1) / 2;
        if (cube_u16(middle) <= target) low = middle;
        else high = middle - 1;
    }
    if (low < PERCEPTUAL_MAX + 256) {
        uint64_t lower_error = target - cube_u16(low);
        uint64_t upper_error = cube_u16(low + 1) - target;
        if (upper_error < lower_error) low++;
    }
    return low;
}

static int rounded_signed_division(int64_t value, int divisor) {
    if (value >= 0) return (int)((value + divisor / 2) / divisor);
    return -(int)((-value + divisor / 2) / divisor);
}

static int clamp_u16(int value) {
    if (value < 0) return 0;
    if (value > PERCEPTUAL_MAX) return PERCEPTUAL_MAX;
    return value;
}

static uint8_t clamp_byte(int value) {
    if (value < 0) return 0;
    if (value > 255) return 255;
    return (uint8_t) value;
}

void n148_perceptual_init(void) {
    if (tables_ready) return;

    for (int value = 0; value < 256; value++) {
        uint32_t squared = (uint32_t) value * value;
        srgb_to_linear[value] =
            (uint16_t)((squared * 257u + 127u) / 255u);
    }
    uint32_t bias_root = nearest_cube_root_response(OPSIN_BIAS);
    uint32_t white_root = nearest_cube_root_response(
        PERCEPTUAL_MAX + OPSIN_BIAS);
    uint32_t root_range = white_root - bias_root;
    for (int index = 0; index < RESPONSE_TABLE_SIZE; index++) {
        uint32_t linear = (uint32_t) index << RESPONSE_TABLE_BITS;
        if (linear > PERCEPTUAL_MAX) linear = PERCEPTUAL_MAX;
        uint32_t biased_root = nearest_cube_root_response(linear + OPSIN_BIAS);
        response_table[index] = (uint16_t)(
            ((biased_root - bias_root) * PERCEPTUAL_MAX + root_range / 2) /
            root_range);
    }

    int linear = 0;
    for (int response = 0; response <= PERCEPTUAL_MAX; response++) {
        while (linear < PERCEPTUAL_MAX) {
            int lower_error = response - perceptual_response((uint16_t) linear);
            int upper_error = perceptual_response((uint16_t)(linear + 1)) -
                response;
            if (upper_error >= lower_error) break;
            linear++;
        }
        response_to_linear[response] = (uint16_t) linear;
    }

    int srgb = 0;
    for (int linear = 0; linear <= PERCEPTUAL_MAX; linear++) {
        while (srgb < 255) {
            int lower_error = linear - srgb_to_linear[srgb];
            int upper_error = srgb_to_linear[srgb + 1] - linear;
            if (upper_error >= lower_error) break;
            srgb++;
        }
        linear_to_srgb[linear] = (uint8_t) srgb;
    }
    tables_ready = 1;
}

static uint16_t perceptual_response(uint16_t linear) {
    if (linear == PERCEPTUAL_MAX) return PERCEPTUAL_MAX;
    unsigned index = linear >> RESPONSE_TABLE_BITS;
    unsigned fraction = linear & ((1u << RESPONSE_TABLE_BITS) - 1u);
    unsigned first = response_table[index];
    unsigned second = response_table[index + 1];
    return (uint16_t)((first * ((1u << RESPONSE_TABLE_BITS) - fraction) +
                       second * fraction +
                       (1u << (RESPONSE_TABLE_BITS - 1))) >>
                      RESPONSE_TABLE_BITS);
}

static uint16_t inverse_perceptual_response(int response) {
    return response_to_linear[clamp_u16(response)];
}

void n148_rgb_to_perceptual(const uint8_t *rgb, long count,
                            uint8_t *intensity, uint8_t *red_green,
                            uint8_t *blue_yellow) {
    for (long pixel = 0; pixel < count; pixel++) {
        uint16_t linear[3] = {
            srgb_to_linear[rgb[pixel * 3]],
            srgb_to_linear[rgb[pixel * 3 + 1]],
            srgb_to_linear[rgb[pixel * 3 + 2]],
        };
        uint16_t response[3];
        for (int cone = 0; cone < 3; cone++) {
            uint32_t sum = 0;
            for (int channel = 0; channel < 3; channel++)
                sum += (uint32_t) cone_matrix[cone][channel] * linear[channel];
            response[cone] = perceptual_response(
                (uint16_t)((sum + 2048) >> 12));
        }
        int average = (response[0] + response[1] + 1) / 2;
        int x = (int) response[0] - response[1];
        int blue_difference = (int) response[2] - average;
        intensity[pixel] = clamp_byte((average + 128) / 257);
        red_green[pixel] = clamp_byte(
            XYB_X_NEUTRAL +
            rounded_signed_division(x, XYB_X_SCALE));
        blue_yellow[pixel] = clamp_byte(
            XYB_B_NEUTRAL +
            rounded_signed_division(blue_difference, XYB_B_SCALE));
    }
}

void n148_perceptual_to_rgb(uint8_t intensity,
                            uint16_t red_green_scaled,
                            uint16_t blue_yellow_scaled,
                            uint8_t rgb[3]) {
    int average = intensity * 257;
    int x = rounded_signed_division(
        ((int) red_green_scaled -
         (XYB_X_NEUTRAL << CHROMA_FRACTION_BITS)) * XYB_X_SCALE,
        1 << CHROMA_FRACTION_BITS);
    int blue_difference = rounded_signed_division(
        ((int) blue_yellow_scaled -
         (XYB_B_NEUTRAL << CHROMA_FRACTION_BITS)) * XYB_B_SCALE,
        1 << CHROMA_FRACTION_BITS);
    int responses[3] = {
        average + rounded_signed_division(x, 2),
        average - rounded_signed_division(x, 2),
        average + blue_difference,
    };
    uint16_t cones[3] = {
        inverse_perceptual_response(responses[0]),
        inverse_perceptual_response(responses[1]),
        inverse_perceptual_response(responses[2]),
    };
    for (int channel = 0; channel < 3; channel++) {
        int64_t sum = 0;
        for (int cone = 0; cone < 3; cone++)
            sum += (int64_t) cone_inverse_q20[channel][cone] * cones[cone];
        int linear = rounded_signed_division(sum, 1 << 20);
        rgb[channel] = linear_to_srgb[clamp_u16(linear)];
    }
}

src/adaptive_quant.h

O adaptive_quant.h é a interface da quantização adaptativa da etapa 5, a primeira versão da ideia de segmentação do artigo 36.

O arquivo completo tem 48 linhas:

/*
 * N.148i adaptive quantization map.
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#ifndef N148_ADAPTIVE_QUANT_H
#define N148_ADAPTIVE_QUANT_H

#include <stddef.h>
#include <stdint.h>

#include "ppm.h"

#define N148_AQ_REGION_SIZE 16
#define N148_AQ_LEVEL_COUNT 4
#define N148_AQ_INITIAL_LEVEL 1

typedef struct {
    uint8_t *levels;
    size_t count;
    int columns;
    int rows;
} N148AdaptiveMap;

/* Allocate a zeroed map whose dimensions are implied by the RGB canvas. */
int n148_adaptive_map_allocate(int width, int height, N148AdaptiveMap *map);

/* Select levels from local activity in the full-resolution intensity plane. */
int n148_adaptive_map_build(const Plane *intensity, N148AdaptiveMap *map);

/* Derive the causal left/above predictor for one raster-order map entry. */
uint8_t n148_adaptive_map_predict(const N148AdaptiveMap *map, size_t index);

/* Find the map level for an 8x8 block. Subsampling shifts are zero or one. */
int n148_adaptive_level_for_block(const N148AdaptiveMap *map,
                                  int block_x, int block_y,
                                  int subsample_x, int subsample_y,
                                  uint8_t *level);

/* Apply the normative per-level multiplier to a quality-scaled table. */
int n148_adaptive_adjust_table(const int input[8][8], uint8_t level,
                               int output[8][8]);

void n148_adaptive_map_release(N148AdaptiveMap *map);

#endif

src/adaptive_quant.c

O adaptive_quant.c implementa o mapa com o nível de quantização de cada região, que também ficou no cemitério e continua decodificável.

O arquivo completo tem 151 linhas:

/*
 * N.148i activity-masked quantization.
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 *
 * The map is deliberately small and causal to decode. Level selection is an
 * encoder heuristic; region geometry and quantization multipliers are the
 * normative pieces stored by the adaptive-quantization syntax.
 */

#include "adaptive_quant.h"

#include <limits.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

static int map_dimensions(int width, int height, int *columns, int *rows,
                          size_t *count) {
    if (width <= 0 || height <= 0 || !columns || !rows || !count) return 0;
    int map_columns = width / N148_AQ_REGION_SIZE +
        (width % N148_AQ_REGION_SIZE != 0);
    int map_rows = height / N148_AQ_REGION_SIZE +
        (height % N148_AQ_REGION_SIZE != 0);
    if ((size_t) map_columns > SIZE_MAX / (size_t) map_rows) return 0;
    size_t map_count = (size_t) map_columns * (size_t) map_rows;
    if (map_count == 0 || map_count > UINT32_MAX) return 0;
    *columns = map_columns;
    *rows = map_rows;
    *count = map_count;
    return 1;
}

int n148_adaptive_map_allocate(int width, int height, N148AdaptiveMap *map) {
    if (!map) return 0;
    memset(map, 0, sizeof(*map));
    if (!map_dimensions(width, height, &map->columns, &map->rows,
                        &map->count)) return 0;
    map->levels = (uint8_t *) calloc(map->count, 1);
    if (!map->levels) {
        memset(map, 0, sizeof(*map));
        return 0;
    }
    return 1;
}

static uint16_t activity_score(const Plane *plane, int x0, int y0) {
    int x1 = x0 + N148_AQ_REGION_SIZE;
    int y1 = y0 + N148_AQ_REGION_SIZE;
    if (x1 > plane->width) x1 = plane->width;
    if (y1 > plane->height) y1 = plane->height;
    uint32_t sum = 0;
    uint32_t comparisons = 0;
    for (int y = y0; y < y1; y++) {
        const uint8_t *row = plane->data + (long) y * plane->width;
        for (int x = x0; x < x1; x++) {
            if (x >= x0 + 2) {
                int difference = (int) row[x] - 2 * (int) row[x - 1] +
                    (int) row[x - 2];
                int magnitude = difference < 0 ? -difference : difference;
                if (magnitude > 32) magnitude = 32;
                sum += (uint32_t) magnitude;
                comparisons++;
            }
            if (y >= y0 + 2) {
                int difference = (int) row[x] -
                    2 * (int) plane->data[(long)(y - 1) * plane->width + x] +
                    (int) plane->data[(long)(y - 2) * plane->width + x];
                int magnitude = difference < 0 ? -difference : difference;
                if (magnitude > 32) magnitude = 32;
                sum += (uint32_t) magnitude;
                comparisons++;
            }
        }
    }
    if (comparisons == 0) return 0;
    return (uint16_t)((sum * 256u + comparisons / 2u) / comparisons);
}

int n148_adaptive_map_build(const Plane *intensity, N148AdaptiveMap *map) {
    if (!intensity || !intensity->data || !map ||
        !n148_adaptive_map_allocate(intensity->width, intensity->height, map))
        return 0;
    for (int row = 0; row < map->rows; row++) {
        for (int column = 0; column < map->columns; column++) {
            size_t index = (size_t) row * (size_t) map->columns +
                (size_t) column;
            uint16_t score = activity_score(
                intensity, column * N148_AQ_REGION_SIZE,
                row * N148_AQ_REGION_SIZE);
            map->levels[index] = score < 2u * 256u ? 0 :
                score < 8u * 256u ? 1 :
                score < 18u * 256u ? 2 : 3;
        }
    }
    return 1;
}

uint8_t n148_adaptive_map_predict(const N148AdaptiveMap *map, size_t index) {
    if (!map || !map->levels || index >= map->count || map->columns <= 0)
        return N148_AQ_INITIAL_LEVEL;
    size_t column = index % (size_t) map->columns;
    if (column > 0) return map->levels[index - 1];
    if (index >= (size_t) map->columns)
        return map->levels[index - (size_t) map->columns];
    return N148_AQ_INITIAL_LEVEL;
}

int n148_adaptive_level_for_block(const N148AdaptiveMap *map,
                                  int block_x, int block_y,
                                  int subsample_x, int subsample_y,
                                  uint8_t *level) {
    if (!map || !map->levels || !level || block_x < 0 || block_y < 0 ||
        (subsample_x != 0 && subsample_x != 1) ||
        (subsample_y != 0 && subsample_y != 1)) return 0;
    size_t canvas_x = (size_t) block_x * 8u * (1u << subsample_x);
    size_t canvas_y = (size_t) block_y * 8u * (1u << subsample_y);
    size_t region_x = canvas_x / N148_AQ_REGION_SIZE;
    size_t region_y = canvas_y / N148_AQ_REGION_SIZE;
    if (region_x >= (size_t) map->columns ||
        region_y >= (size_t) map->rows) return 0;
    size_t index = region_y * (size_t) map->columns + region_x;
    if (index >= map->count || map->levels[index] >= N148_AQ_LEVEL_COUNT)
        return 0;
    *level = map->levels[index];
    return 1;
}

int n148_adaptive_adjust_table(const int input[8][8], uint8_t level,
                               int output[8][8]) {
    static const int numerator[N148_AQ_LEVEL_COUNT] = {90, 97, 108, 118};
    static const int denominator[N148_AQ_LEVEL_COUNT] = {100, 100, 100, 100};
    if (!input || !output || level >= N148_AQ_LEVEL_COUNT) return 0;
    for (int row = 0; row < 8; row++) {
        for (int column = 0; column < 8; column++) {
            int value = (input[row][column] * numerator[level] +
                         denominator[level] / 2) / denominator[level];
            if (value < 1) value = 1;
            if (value > 255) value = 255;
            output[row][column] = value;
        }
    }
    return 1;
}

void n148_adaptive_map_release(N148AdaptiveMap *map) {
    if (!map) return;
    free(map->levels);
    memset(map, 0, sizeof(*map));
}

src/segmentation.h

O segmentation.h é a interface da segmentação do artigo 36, com os quatro tipos de região e as quatro quantizações.

O arquivo completo tem 67 linhas:

/*
 * N.148i frame-level segmentation
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#ifndef N148_SEGMENTATION_H
#define N148_SEGMENTATION_H

#include <stddef.h>
#include <stdint.h>

#include "ppm.h"

#define N148_SEGMENT_REGION_SIZE 16
#define N148_SEGMENT_COUNT 4
#define N148_SEGMENT_INITIAL 1
#define N148_SEGMENT_MIN_SCALE 75
#define N148_SEGMENT_MAX_SCALE 125

typedef struct {
    uint8_t *levels;
    size_t count;
    int columns;
    int rows;
    uint8_t quant_scale[N148_SEGMENT_COUNT];
    uint8_t adaptive_filter;
} N148SegmentationMap;

/* Build a deterministic, frame-level activity classification from luma. */
int n148_segmentation_map_build(const Plane *luma,
                                N148SegmentationMap *map);
int n148_segmentation_map_build_structural(const Plane *luma,
                                           N148SegmentationMap *map);

/* Allocate the normative 16x16 map geometry for a decoded canvas. */
int n148_segmentation_map_allocate(int width, int height,
                                   N148SegmentationMap *map);
int n148_segmentation_map_validate(const N148SegmentationMap *map);

/* Predict one map entry from information already available to the decoder. */
int n148_segmentation_map_build_detail(const Plane *luma,
                                       N148SegmentationMap *map);

uint8_t n148_segmentation_map_predict(const N148SegmentationMap *map,
                                      size_t index);

/* Resolve an 8x8 plane block to its full-resolution 16x16 segment. */
int n148_segmentation_level_for_block(const N148SegmentationMap *map,
                                      int block_x, int block_y,
                                      int subsample_x, int subsample_y,
                                      uint8_t *level);

/* Translate the ordered segment to the loop filter's strength class. */
int n148_segmentation_filter_level(const N148SegmentationMap *map,
                                   uint8_t segment, uint8_t *filter_level);

/* Apply the normative per-segment quantizer scale. Plane zero is luma. */
int n148_segmentation_adjust_table(const int input[8][8],
                                   const N148SegmentationMap *map,
                                   uint8_t level, int plane_index,
                                   int output[8][8]);

void n148_segmentation_map_release(N148SegmentationMap *map);

#endif

src/segmentation.c

O segmentation.c classifica a imagem inteira antes de codificar qualquer bloco, e traz também os mapas usados pelos perfis estrutural e de detalhe.

O arquivo completo tem 442 linhas:

/*
 * N.148i frame-level segmentation
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 *
 * The encoder classifies the complete frame before coding any block. This is
 * intentionally different from the rejected local-threshold experiment:
 * four ordered centres adapt to each image's own activity distribution. Only
 * the map geometry and quantizer scales are normative to the decoder.
 */

#include "segmentation.h"
#include "cpu.h"
#if defined(__x86_64__) || defined(__i386__)
#include <immintrin.h>
#endif

#include <limits.h>
#include <math.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

static int map_dimensions(int width, int height, int *columns, int *rows,
                          size_t *count) {
    if (width <= 0 || height <= 0 || !columns || !rows || !count) return 0;
    int map_columns = width / N148_SEGMENT_REGION_SIZE +
        (width % N148_SEGMENT_REGION_SIZE != 0);
    int map_rows = height / N148_SEGMENT_REGION_SIZE +
        (height % N148_SEGMENT_REGION_SIZE != 0);
    if ((size_t) map_columns > SIZE_MAX / (size_t) map_rows) return 0;
    size_t map_count = (size_t) map_columns * (size_t) map_rows;
    if (map_count == 0 || map_count > UINT32_MAX) return 0;
    *columns = map_columns;
    *rows = map_rows;
    *count = map_count;
    return 1;
}

int n148_segmentation_map_allocate(int width, int height,
                                   N148SegmentationMap *map) {
    if (!map) return 0;
    memset(map, 0, sizeof(*map));
    if (!map_dimensions(width, height, &map->columns, &map->rows,
                        &map->count)) return 0;
    map->levels = (uint8_t *) calloc(map->count, 1);
    if (!map->levels) {
        memset(map, 0, sizeof(*map));
        return 0;
    }
    for (int segment = 0; segment < N148_SEGMENT_COUNT; segment++)
        map->quant_scale[segment] = 100;
    return 1;
}

int n148_segmentation_map_validate(const N148SegmentationMap *map) {
    if (!map || !map->levels || map->count == 0 || map->columns <= 0 ||
        map->rows <= 0 || (size_t) map->columns >
            SIZE_MAX / (size_t) map->rows ||
        map->count != (size_t) map->columns * (size_t) map->rows ||
        map->adaptive_filter > 1) return 0;
    for (size_t index = 0; index < map->count; index++)
        if (map->levels[index] >= N148_SEGMENT_COUNT) return 0;
    for (int segment = 0; segment < N148_SEGMENT_COUNT; segment++)
        if (map->quant_scale[segment] < N148_SEGMENT_MIN_SCALE ||
            map->quant_scale[segment] > N148_SEGMENT_MAX_SCALE) return 0;
    return 1;
}

static int compare_u32(const void *first, const void *second) {
    uint32_t a = *(const uint32_t *) first;
    uint32_t b = *(const uint32_t *) second;
    return (a > b) - (a < b);
}

static int sample_or_neutral(const Plane *plane, int x, int y) {
    if (x < 0 || y < 0 || x >= plane->width || y >= plane->height) return 128;
    return plane->data[(long) y * plane->width + x];
}

static int clamp_sample(int value) {
    if (value < 0) return 0;
    if (value > 255) return 255;
    return value;
}

/* Approximate the residual susceptibility that the real encoder will see.
   Each 8x8 cell prices DC, vertical, horizontal and TrueMotion prediction
   from original neighbours, then contributes only its best absolute error.
   This separates predictable edges and ramps from genuinely irregular
   texture much better than a raw variance or gradient threshold. */
static uint32_t region_activity_scalar(const Plane *plane, int x0, int y0) {
    int x1 = x0 + N148_SEGMENT_REGION_SIZE;
    int y1 = y0 + N148_SEGMENT_REGION_SIZE;
    if (x1 > plane->width) x1 = plane->width;
    if (y1 > plane->height) y1 = plane->height;
    uint64_t activity = 0;
    uint32_t samples = 0;
    for (int block_y = y0; block_y < y1; block_y += 8) {
        for (int block_x = x0; block_x < x1; block_x += 8) {
            int block_x1 = block_x + 8;
            int block_y1 = block_y + 8;
            if (block_x1 > x1) block_x1 = x1;
            if (block_y1 > y1) block_y1 = y1;
            uint64_t errors[4] = {0, 0, 0, 0};
            uint32_t block_samples = 0;
            int dc_sum = 0;
            int dc_count = 0;
            if (block_y > 0) {
                for (int x = block_x; x < block_x1; x++) {
                    dc_sum += sample_or_neutral(plane, x, block_y - 1);
                    dc_count++;
                }
            }
            if (block_x > 0) {
                for (int y = block_y; y < block_y1; y++) {
                    dc_sum += sample_or_neutral(plane, block_x - 1, y);
                    dc_count++;
                }
            }
            int dc = dc_count ? (dc_sum + dc_count / 2) / dc_count : 128;
            int top_left = sample_or_neutral(
                plane, block_x - 1, block_y - 1);
            for (int y = block_y; y < block_y1; y++) {
                for (int x = block_x; x < block_x1; x++) {
                    int source = sample_or_neutral(plane, x, y);
                    int top = sample_or_neutral(plane, x, block_y - 1);
                    int left = sample_or_neutral(plane, block_x - 1, y);
                    int predictions[4] = {
                        dc, top, left, clamp_sample(top + left - top_left),
                    };
                    for (int mode = 0; mode < 4; mode++) {
                        int error = source - predictions[mode];
                        if (error < 0) error = -error;
                        if (error > 64) error = 64;
                        errors[mode] += (uint32_t) error;
                    }
                    block_samples++;
                }
            }
            uint64_t best = errors[0];
            for (int mode = 1; mode < 4; mode++)
                if (errors[mode] < best) best = errors[mode];
            activity += best;
            samples += block_samples;
        }
    }
    return samples ?
        (uint32_t)((activity * 256u + samples / 2u) / samples) : 0;
}

/* Mean local8x8 source variance in fixed-point units. The structural
   policy uses the SSIM contrast denominator for region allocation. */
#if defined(__x86_64__) || defined(__i386__)
__attribute__((target("avx2")))
static uint32_t region_activity_vector(const Plane *plane, int x0, int y0) {
    uint32_t activity=0;
    const __m128i limit=_mm_set1_epi16(64);
    for (int by=y0; by<y0+16; by+=8) for (int bx=x0; bx<x0+16; bx+=8) {
        int dc_sum=0, dc_count=0;
        if (by>0) for (int x=bx; x<bx+8; x++) {
            dc_sum+=plane->data[(long)(by-1)*plane->width+x]; dc_count++;
        }
        if (bx>0) for (int y=by; y<by+8; y++) {
            dc_sum+=plane->data[(long)y*plane->width+bx-1]; dc_count++;
        }
        int dc=dc_count ? (dc_sum+dc_count/2)/dc_count : 128;
        int top_left=sample_or_neutral(plane,bx-1,by-1);
        __m128i top8 = by>0 ? _mm_loadl_epi64((const __m128i *)(
            plane->data+(long)(by-1)*plane->width+bx)) : _mm_set1_epi8((char)128);
        __m128i top=_mm_cvtepu8_epi16(top8);
        __m128i totals01=_mm_setzero_si128(), totals23=_mm_setzero_si128();
        for (int y=by; y<by+8; y++) {
            __m128i pixels=_mm_cvtepu8_epi16(_mm_loadl_epi64((const __m128i *)(
                plane->data+(long)y*plane->width+bx)));
            int left_value=sample_or_neutral(plane,bx-1,y);
            __m128i left=_mm_set1_epi16((short)left_value);
            __m128i planar=_mm_add_epi16(top,_mm_set1_epi16((short)(left_value-top_left)));
            planar=_mm_min_epi16(_mm_max_epi16(planar,_mm_setzero_si128()),_mm_set1_epi16(255));
            __m128i e0=_mm_min_epi16(_mm_abs_epi16(_mm_sub_epi16(pixels,_mm_set1_epi16((short)dc))),limit);
            __m128i e1=_mm_min_epi16(_mm_abs_epi16(_mm_sub_epi16(pixels,top)),limit);
            __m128i e2=_mm_min_epi16(_mm_abs_epi16(_mm_sub_epi16(pixels,left)),limit);
            __m128i e3=_mm_min_epi16(_mm_abs_epi16(_mm_sub_epi16(pixels,planar)),limit);
            totals01=_mm_add_epi64(totals01,_mm_sad_epu8(_mm_packus_epi16(e0,e1),_mm_setzero_si128()));
            totals23=_mm_add_epi64(totals23,_mm_sad_epu8(_mm_packus_epi16(e2,e3),_mm_setzero_si128()));
        }
        uint64_t errors[4];
        _mm_storeu_si128((__m128i *)errors,totals01);
        _mm_storeu_si128((__m128i *)(errors+2),totals23);
        uint64_t best=errors[0];
        for (int k=1; k<4; k++) if (errors[k]<best) best=errors[k];
        activity+=(uint32_t)best;
    }
    /* Exactly 256 source samples: (sum*256 + 128)/256 equals sum. */
    return activity;
}
#endif

static uint32_t region_activity(const Plane *plane, int x0, int y0) {
#if defined(__x86_64__) || defined(__i386__)
    if (x0>=0 && y0>=0 && plane->width-x0>=16 && plane->height-y0>=16 &&
        n148_cpu_level()>=N148_CPU_AVX2) return region_activity_vector(plane,x0,y0);
#endif
    return region_activity_scalar(plane,x0,y0);
}

static uint32_t region_source_variance(const Plane *plane, int x0, int y0,
                                       int predictable) {
    uint64_t total = 0;
    unsigned int count = 0;
    for (int by = y0; by < y0 + 16 && by < plane->height; by += 8) {
        for (int bx = x0; bx < x0 + 16 && bx < plane->width; bx += 8) {
            uint64_t sum = 0, square = 0;
            unsigned int n = 0;
            for (int y = by; y < by + 8 && y < plane->height; y++) {
                for (int x = bx; x < bx + 8 && x < plane->width; x++) {
                    unsigned int v = plane->data[(long)y * plane->width + x];
                    sum += v; square += v * v; n++;
                }
            }
            total += 256 * (n * square - sum * sum) / n;
            count += n;
        }
    }
    if (!predictable) return count ? (uint32_t)(total / count) : 0;
    uint64_t residual = region_activity(plane, x0, y0);
    uint32_t activity = (uint32_t)((2 * residual * residual + 128) / 256);
    uint32_t variance = count ? (uint32_t)(total / count) : 0;
    return activity < variance ? activity : variance;
}

static int nearest_centre(uint32_t score,
                          const uint32_t centres[N148_SEGMENT_COUNT]) {
    int best = 0;
    uint32_t best_distance = score > centres[0] ?
        score - centres[0] : centres[0] - score;
    for (int level = 1; level < N148_SEGMENT_COUNT; level++) {
        uint32_t distance = score > centres[level] ?
            score - centres[level] : centres[level] - score;
        if (distance < best_distance) {
            best = level;
            best_distance = distance;
        }
    }
    return best;
}

static int build_map(const Plane *luma, N148SegmentationMap *map,
                      int source_variance) {
    if (!luma || !luma->data || !map ||
        !n148_segmentation_map_allocate(luma->width, luma->height, map))
        return 0;
    if (map->count > SIZE_MAX / sizeof(uint32_t)) {
        n148_segmentation_map_release(map);
        return 0;
    }
    uint32_t *scores = (uint32_t *) malloc(map->count * sizeof(*scores));
    uint32_t *sorted = (uint32_t *) malloc(map->count * sizeof(*sorted));
    if (!scores || !sorted) {
        free(scores);
        free(sorted);
        n148_segmentation_map_release(map);
        return 0;
    }
    for (int row = 0; row < map->rows; row++) {
        for (int column = 0; column < map->columns; column++) {
            size_t index = (size_t) row * (size_t) map->columns +
                (size_t) column;
            scores[index] = source_variance ? region_source_variance(
                luma, column * N148_SEGMENT_REGION_SIZE,
                row * N148_SEGMENT_REGION_SIZE, source_variance == 2) : region_activity(
                luma, column * N148_SEGMENT_REGION_SIZE,
                row * N148_SEGMENT_REGION_SIZE);
            if (source_variance == 2) scores[index] = (uint32_t)(
                256.0 * log(scores[index] / 256.0 + 29.26125) + 0.5);
            sorted[index] = scores[index];
        }
    }
    qsort(sorted, map->count, sizeof(*sorted), compare_u32);
    uint32_t centres[N148_SEGMENT_COUNT];
    for (int level = 0; level < N148_SEGMENT_COUNT; level++) {
        size_t numerator = (size_t)(2 * level + 1) * map->count;
        size_t position = numerator / (2u * N148_SEGMENT_COUNT);
        if (position >= map->count) position = map->count - 1;
        centres[level] = sorted[position];
    }
    for (int iteration = 0; iteration < 8; iteration++) {
        uint64_t sums[N148_SEGMENT_COUNT] = {0};
        uint32_t counts[N148_SEGMENT_COUNT] = {0};
        for (size_t index = 0; index < map->count; index++) {
            int level = nearest_centre(scores[index], centres);
            sums[level] += scores[index];
            counts[level]++;
        }
        int changed = 0;
        for (int level = 0; level < N148_SEGMENT_COUNT; level++) {
            if (!counts[level]) continue;
            uint32_t centre = (uint32_t)((sums[level] + counts[level] / 2u) /
                                         counts[level]);
            if (centre != centres[level]) changed = 1;
            centres[level] = centre;
        }
        if (!changed) break;
    }
    uint64_t weighted_sum = 0;
    for (size_t index = 0; index < map->count; index++) {
        int level = nearest_centre(scores[index], centres);
        map->levels[index] = (uint8_t) level;
        weighted_sum += centres[level];
    }
    if (source_variance) {
        double log_sum = 0.0;
        for (size_t index = 0; index < map->count; index++)
            log_sum += source_variance == 2 ? (centres[map->levels[index]] / 256.0) :
                log(centres[map->levels[index]] / 256.0 + 29.26125);
        double log_mean = log_sum / map->count;
        for (int level = 0; level < N148_SEGMENT_COUNT; level++) {
            double log_activity = source_variance == 2 ? (centres[level] / 256.0) :
                log(centres[level] / 256.0 + 29.26125);
            /* Eighth-root allocation balances RGB squared error with the
               structural preference for finer steps in smooth regions. */
            int scale = (int)(100.0 * exp(0.125 * (log_activity - log_mean)) + 0.5);
            if (scale < N148_SEGMENT_MIN_SCALE) scale = N148_SEGMENT_MIN_SCALE;
            if (scale > N148_SEGMENT_MAX_SCALE) scale = N148_SEGMENT_MAX_SCALE;
            map->quant_scale[level] = (uint8_t) scale;
        }
    } else {
        uint32_t weighted_mean = (uint32_t)(
            (weighted_sum + map->count / 2u) / map->count);
        uint32_t range = centres[N148_SEGMENT_COUNT - 1] - centres[0];
        for (int level = 0; level < N148_SEGMENT_COUNT; level++) {
            int64_t difference = (int64_t) centres[level] - weighted_mean;
            int delta = 0;
            if (range) {
                int64_t scaled = 32 * difference;
                delta = (int)((scaled >= 0 ? scaled + range / 2u :
                               scaled - range / 2u) / (int64_t) range);
            }
            int scale = 100 + delta;
            if (scale < N148_SEGMENT_MIN_SCALE) scale = N148_SEGMENT_MIN_SCALE;
            if (scale > N148_SEGMENT_MAX_SCALE) scale = N148_SEGMENT_MAX_SCALE;
            /* Preserve smooth surfaces aggressively and cap the texture penalty.
               The frame-derived middle scales still adapt to its distribution. */
            if (level == 0 && scale > 88) scale = 88;
            if (level == 1 && scale > 95) scale = 95;
            if (level == 3 && scale > 118) scale = 118;
            map->quant_scale[level] = (uint8_t) scale;
        }
    }
    free(scores);
    free(sorted);
    return n148_segmentation_map_validate(map);
}

int n148_segmentation_map_build(const Plane *luma, N148SegmentationMap *map) {
    return build_map(luma, map, 0);
}

int n148_segmentation_map_build_structural(const Plane *luma,
                                           N148SegmentationMap *map) {
    return build_map(luma, map, 1);
}

int n148_segmentation_map_build_detail(const Plane *luma,
                                       N148SegmentationMap *map) {
    return build_map(luma, map, 2);
}

uint8_t n148_segmentation_map_predict(const N148SegmentationMap *map,
                                      size_t index) {
    if (!map || !map->levels || index >= map->count || map->columns <= 0)
        return N148_SEGMENT_INITIAL;
    size_t column = index % (size_t) map->columns;
    if (column > 0) return map->levels[index - 1];
    if (index >= (size_t) map->columns)
        return map->levels[index - (size_t) map->columns];
    return N148_SEGMENT_INITIAL;
}

int n148_segmentation_level_for_block(const N148SegmentationMap *map,
                                      int block_x, int block_y,
                                      int subsample_x, int subsample_y,
                                      uint8_t *level) {
    if (!n148_segmentation_map_validate(map) || !level || block_x < 0 ||
        block_y < 0 || (subsample_x != 0 && subsample_x != 1) ||
        (subsample_y != 0 && subsample_y != 1)) return 0;
    size_t canvas_x = (size_t) block_x * 8u * (1u << subsample_x);
    size_t canvas_y = (size_t) block_y * 8u * (1u << subsample_y);
    size_t region_x = canvas_x / N148_SEGMENT_REGION_SIZE;
    size_t region_y = canvas_y / N148_SEGMENT_REGION_SIZE;
    if (region_x >= (size_t) map->columns ||
        region_y >= (size_t) map->rows) return 0;
    size_t index = region_y * (size_t) map->columns + region_x;
    if (index >= map->count || map->levels[index] >= N148_SEGMENT_COUNT)
        return 0;
    *level = map->levels[index];
    return 1;
}

int n148_segmentation_filter_level(const N148SegmentationMap *map,
                                   uint8_t segment,
                                   uint8_t *filter_level) {
    if (!filter_level || !n148_segmentation_map_validate(map) ||
        segment >= N148_SEGMENT_COUNT) return 0;
    /* Give the smoothest class a slightly wider edge threshold, keep the
       middle of the frame at the accepted level, and reduce strength for the
       most irregular detail class. Large level swings were perceptually
       unstable during calibration. */
    static const uint8_t level[N148_SEGMENT_COUNT] = {2, 1, 1, 0};
    *filter_level = level[segment];
    return 1;
}

int n148_segmentation_adjust_table(const int input[8][8],
                                   const N148SegmentationMap *map,
                                   uint8_t level, int plane_index,
                                   int output[8][8]) {
    /* Chroma remains neutral under segmentation. Calibrated chroma quantization
       already tuned it on a
       held-out set, while the channel diagnosis locates the remaining gap in
       luma. Conservative luma scales limit metric regressions during tuning. */
    if (!input || !output || !n148_segmentation_map_validate(map) ||
        level >= N148_SEGMENT_COUNT || plane_index < 0 || plane_index > 2)
        return 0;
    int scale = plane_index == 0 ? map->quant_scale[level] : 100;
    for (int row = 0; row < 8; row++) {
        for (int column = 0; column < 8; column++) {
            int value = (input[row][column] * scale + 50) / 100;
            if (value < 1) value = 1;
            if (value > 255) value = 255;
            output[row][column] = value;
        }
    }
    return 1;
}

void n148_segmentation_map_release(N148SegmentationMap *map) {
    if (!map) return;
    free(map->levels);
    memset(map, 0, sizeof(*map));
}

Novos na pasta src: os formatos de 3 a 7

Cada rodada de desenvolvimento da V2 gerou um número de formato, e cada formato tem um arquivo que liga as ferramentas daquela rodada.

src/predictive_codec.h

O predictive_codec.h é a interface do formato 3 e das ferramentas da rodada da cor, como a predição conjunta da cor, a cor calibrada, a segmentação e o filtro adaptativo.

O arquivo completo tem 196 linhas:

/*
 * N.148i predictive-codec interface
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#ifndef N148_PREDICTIVE_CODEC_H
#define N148_PREDICTIVE_CODEC_H

#include <stddef.h>
#include <stdint.h>

#include "ppm.h"
#include "entropy_payload.h"
#include "directional_intra.h"

#define N148_FEATURE_DIRECTIONAL_INTRA (1u << 8)
#define N148_FEATURE_INTRA_4X4 (1u << 9)
#define N148_FEATURE_CONTEXTUAL_RDO (1u << 10)
#define N148_FEATURE_PERCEPTUAL_TRELLIS (1u << 11)

#define N148_DIRECTIONAL_INTRA_PROFILE_FEATURES \
    (N148_FEATURE_RANS | N148_FEATURE_CONTEXT | \
     N148_FEATURE_INTRA | N148_FEATURE_RDO | \
     N148_FEATURE_LOOP_FILTER | \
     N148_FEATURE_DIRECTIONAL_INTRA | N148_FEATURE_INTRA_4X4)

#define N148_FORMAT_3_SUPPORTED_FEATURES \
    (N148_FEATURE_RANS | N148_FEATURE_CONTEXT | \
     N148_FEATURE_INTRA | N148_FEATURE_RDO | \
     N148_FEATURE_LOOP_FILTER | N148_FEATURE_DIRECTIONAL_INTRA | \
     N148_FEATURE_INTRA_4X4 | N148_FEATURE_CONTEXTUAL_RDO | \
     N148_FEATURE_PERCEPTUAL_TRELLIS)

/* Format-local entropy behavior selected by the format 7 wrapper. Older formats
   always pass zero and therefore retain byte-identical syntax. */
#define N148_ENTROPY_ADAPTIVE (1u << 0)
#define N148_ENTROPY_RICH_CONTEXT (1u << 1)
#define N148_ENTROPY_MULTIPLE_REFERENCES (1u << 2)
#define N148_ENTROPY_ADAPT_RATE_SHIFT 6u

typedef struct {
    uint64_t mode_histogram[10];
    uint64_t plane_mode_histogram[3][10];
    uint64_t luma_reference_histogram[3];
    uint64_t split_blocks;
    uint64_t plane_split_blocks[3];
    uint64_t total_blocks;
    uint64_t plane_total_blocks[3];
    uint64_t segment_histogram[4];
    uint64_t segment_count;
    uint8_t segment_quant_scale[4];
    uint64_t luma_transform_regions;
    uint64_t luma_transform_4x4;
    uint64_t luma_transform_8x8;
    uint64_t luma_transform_16x16;
    uint64_t luma_transform_32x32;
    uint64_t luma_transform_32x32_opportunities;
} N148SyntaxInspection;

int n148_format_3_features_valid(uint32_t features);

int n148_encode_format_3(Plane *y, Plane *cb, Plane *cr, int quality,
                   uint32_t features, int effort, N148EncodedPayload *output);

int n148_decode_format_3(const uint8_t *metadata, size_t metadata_size,
                   const uint8_t *payload, size_t payload_size,
                   int width, int height, int quality, int chroma,
                   uint32_t features,
                   Plane *y, Plane *cb, Plane *cr);

/* Joint-chroma payload helpers reuse the accepted format 3 coefficient syntax
   but jointly select and signal one chroma predictor for Cb/Cr. */
int n148_joint_chroma_encode(
    Plane *y, Plane *cb, Plane *cr, int quality,
    uint32_t features, int effort, N148EncodedPayload *output);
int n148_joint_chroma_decode(
    const uint8_t *metadata, size_t metadata_size,
    const uint8_t *payload, size_t payload_size,
    int width, int height, int quality, int chroma, uint32_t features,
    Plane *y, Plane *cb, Plane *cr);

/* Calibrated chroma quantization keeps the format 3/4 entropy syntax and changes only the normative
   chroma table and independently signalled chroma quality. */
int n148_calibrated_chroma_encode(
    Plane *y, Plane *cb, Plane *cr, int quality, int chroma_quality,
    uint32_t features, int effort, int joint_chroma,
    N148EncodedPayload *output);
int n148_calibrated_chroma_decode(
    const uint8_t *metadata, size_t metadata_size,
    const uint8_t *payload, size_t payload_size,
    int width, int height, int quality, int chroma_quality, int chroma,
    uint32_t features, int joint_chroma,
    Plane *y, Plane *cb, Plane *cr);

/* Frame segmentation adds a four-segment quantizer map. */
int n148_segmented_encode(
    Plane *y, Plane *cb, Plane *cr, int quality, int chroma_quality,
    uint32_t features, int effort, int joint_chroma,
    N148EncodedPayload *output);
int n148_segmented_decode(
    const uint8_t *metadata, size_t metadata_size,
    const uint8_t *payload, size_t payload_size,
    int width, int height, int quality, int chroma_quality, int chroma,
    uint32_t features, int joint_chroma,
    Plane *y, Plane *cb, Plane *cr);

/* The adaptive chroma filter keeps the segmentation payload grammar and changes the normative
   causal loop-filter strength according to the decoded segment class. */
int n148_adaptive_filter_encode(
    Plane *y, Plane *cb, Plane *cr, int quality, int chroma_quality,
    uint32_t features, int effort, int joint_chroma,
    N148EncodedPayload *output);
int n148_adaptive_filter_decode(
    const uint8_t *metadata, size_t metadata_size,
    const uint8_t *payload, size_t payload_size,
    int width, int height, int quality, int chroma_quality, int chroma,
    uint32_t features, int joint_chroma,
    Plane *y, Plane *cb, Plane *cr);

/* One quantization result can feed both format-7 entropy representations.
   The caller owns this cache and releases it after the final encode attempt. */
typedef struct {
    N148CoeffPlane coefficients[3];
    N148PartitionMap partition_map;
    N148SegmentationMap segmentation_map;
    N148TransformMap transform_map;
    uint8_t *prediction_modes;
    size_t prediction_mode_count;
    int valid;
} N148PredictivePreparation;

void n148_predictive_preparation_release(N148PredictivePreparation *prepared);

int n148_predictive_encode_cached(
    Plane *y, Plane *cb, Plane *cr, int quality, int chroma_quality,
    uint32_t features, int effort, int joint_chroma, int calibrated_chroma,
    int segmented, int adaptive_filter, int calibrated_luma,
    int variable_luma, int perceptual_luma_trellis, int quant_adaptive_filter,
    int dct32, uint32_t entropy_tools, N148EncodedPayload *output,
    N148PredictivePreparation *prepared);

/* Shared entropy/prediction core. Format 5 adds a format-local luma table
   selector and, when requested, the revision-11 variable-luma grammar. */
int n148_predictive_encode(
    Plane *y, Plane *cb, Plane *cr, int quality, int chroma_quality,
    uint32_t features, int effort, int joint_chroma, int calibrated_chroma,
    int segmented, int adaptive_filter, int calibrated_luma,
    int variable_luma, int perceptual_luma_trellis, int quant_adaptive_filter,
    int dct32, uint32_t entropy_tools,
    N148EncodedPayload *output);
int n148_predictive_decode(
    const uint8_t *metadata, size_t metadata_size,
    const uint8_t *payload, size_t payload_size,
    int width, int height, int quality, int chroma_quality, int chroma,
    uint32_t features, int joint_chroma, int calibrated_chroma, int segmented,
    int adaptive_filter, int calibrated_luma, int variable_luma,
    int quant_adaptive_filter, int dct32, uint32_t entropy_tools,
    Plane *y, Plane *cb, Plane *cr);

/* Validation and benchmark hook for syntax usage, not part of the public
   installed API. The full entropy stream is validated while it is counted. */
int n148_directional_intra_inspect(const uint8_t *metadata, size_t metadata_size,
                    const uint8_t *payload, size_t payload_size,
                    int width, int height, int chroma, uint32_t features,
                    N148SyntaxInspection *inspection);
int n148_joint_chroma_inspect(
    const uint8_t *metadata, size_t metadata_size,
    const uint8_t *payload, size_t payload_size,
    int width, int height, int chroma, uint32_t features,
    N148SyntaxInspection *inspection);
int n148_segmented_inspect(
    const uint8_t *metadata, size_t metadata_size,
    const uint8_t *payload, size_t payload_size,
    int width, int height, int chroma, uint32_t features, int joint_chroma,
    N148SyntaxInspection *inspection);
int n148_adaptive_filter_inspect(
    const uint8_t *metadata, size_t metadata_size,
    const uint8_t *payload, size_t payload_size,
    int width, int height, int chroma, uint32_t features, int joint_chroma,
    N148SyntaxInspection *inspection);
int n148_predictive_inspect(
    const uint8_t *metadata, size_t metadata_size,
    const uint8_t *payload, size_t payload_size,
    int width, int height, int chroma, uint32_t features, int joint_chroma,
    int segmented, int adaptive_filter, int variable_luma, int dct32,
    N148SyntaxInspection *inspection);
int n148_entropy_profile_inspect(
    const uint8_t *metadata, size_t metadata_size,
    const uint8_t *payload, size_t payload_size,
    int width, int height, int chroma, uint32_t features, int joint_chroma,
    int segmented, int adaptive_filter, int variable_luma, int dct32,
    uint32_t entropy_tools, N148SyntaxInspection *inspection);

#endif

src/chroma_profile.h

O chroma_profile.h é a interface do formato 4, o da rodada da cor, que estudamos no artigo 35.

O arquivo completo tem 63 linhas:

/*
 * N.148i chroma-profile codec interface
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#ifndef N148_CHROMA_PROFILE_H
#define N148_CHROMA_PROFILE_H

#include <stddef.h>
#include <stdint.h>

#include "ppm.h"
#include "entropy_payload.h"
#include "predictive_codec.h"

/* Reconstruction-aware chroma changes the encoder's 4:2:0 source reduction.
   The reconstructed-plane syntax remains the accepted format 3 syntax, so
   older formats stay isolated and format 4 can signal its input preparation. */
#define N148_FEATURE_RECONSTRUCTION_AWARE_CHROMA (1u << 12)
#define N148_FEATURE_JOINT_CHROMA_INTRA (1u << 13)
#define N148_FEATURE_CALIBRATED_CHROMA_QUANT (1u << 14)
#define N148_FEATURE_SEGMENTATION (1u << 15)
#define N148_FEATURE_ADAPTIVE_LOOP_FILTER (1u << 16)

#define N148_FORMAT_4_SUPPORTED_FEATURES \
    (N148_FORMAT_3_SUPPORTED_FEATURES | \
     N148_FEATURE_RECONSTRUCTION_AWARE_CHROMA | \
     N148_FEATURE_JOINT_CHROMA_INTRA | \
     N148_FEATURE_CALIBRATED_CHROMA_QUANT | \
     N148_FEATURE_SEGMENTATION | \
     N148_FEATURE_ADAPTIVE_LOOP_FILTER)

#define N148_RECONSTRUCTION_AWARE_CHROMA_PROFILE_FEATURES \
    (N148_DIRECTIONAL_INTRA_PROFILE_FEATURES | N148_FEATURE_CONTEXTUAL_RDO | \
     N148_FEATURE_RECONSTRUCTION_AWARE_CHROMA)

#define N148_JOINT_CHROMA_PROFILE_FEATURES \
    (N148_RECONSTRUCTION_AWARE_CHROMA_PROFILE_FEATURES | N148_FEATURE_JOINT_CHROMA_INTRA)

#define N148_CALIBRATED_CHROMA_PROFILE_FEATURES \
    (N148_RECONSTRUCTION_AWARE_CHROMA_PROFILE_FEATURES | N148_FEATURE_CALIBRATED_CHROMA_QUANT)

#define N148_SEGMENTED_CHROMA_PROFILE_FEATURES \
    (N148_CALIBRATED_CHROMA_PROFILE_FEATURES | N148_FEATURE_SEGMENTATION)

#define N148_ADAPTIVE_CHROMA_FILTER_PROFILE_FEATURES \
    (N148_SEGMENTED_CHROMA_PROFILE_FEATURES | N148_FEATURE_ADAPTIVE_LOOP_FILTER)

int n148_format_4_features_valid(uint32_t features);

int n148_encode_format_4(Plane *y, Plane *cb, Plane *cr, int quality,
                   int chroma_quality, uint32_t features, int effort,
                   N148EncodedPayload *output);

int n148_decode_format_4(const uint8_t *metadata, size_t metadata_size,
                   const uint8_t *payload, size_t payload_size,
                   int width, int height, int quality, int chroma_quality,
                   int chroma, uint32_t features,
                   Plane *y, Plane *cb, Plane *cr);

#endif

src/chroma_profile.c

O chroma_profile.c implementa o formato 4, conferindo quais bits de recurso são válidos nele e ligando as ferramentas da cor ao motor de predição.

O arquivo completo tem 86 linhas:

/*
 * N.148i chroma-profile codec
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#include "chroma_profile.h"

static uint32_t predictive_features(uint32_t features) {
    return features & N148_FORMAT_3_SUPPORTED_FEATURES;
}

int n148_format_4_features_valid(uint32_t features) {
    if (features & ~N148_FORMAT_4_SUPPORTED_FEATURES) return 0;
    if (!n148_format_3_features_valid(predictive_features(features))) return 0;
    if ((features & N148_FEATURE_JOINT_CHROMA_INTRA) &&
        !(features & N148_FEATURE_CONTEXTUAL_RDO)) return 0;
    if ((features & N148_FEATURE_SEGMENTATION) &&
        (!(features & N148_FEATURE_CALIBRATED_CHROMA_QUANT) ||
         !(features & N148_FEATURE_CONTEXTUAL_RDO))) return 0;
    if ((features & N148_FEATURE_ADAPTIVE_LOOP_FILTER) &&
        (!(features & N148_FEATURE_SEGMENTATION) ||
         !(features & N148_FEATURE_LOOP_FILTER))) return 0;
    return 1;
}

int n148_encode_format_4(Plane *y, Plane *cb, Plane *cr, int quality,
                   int chroma_quality, uint32_t features, int effort,
                   N148EncodedPayload *output) {
    if (!n148_format_4_features_valid(features) || chroma_quality < 1 ||
        chroma_quality > 100) return 0;
    int joint_chroma =
        (features & N148_FEATURE_JOINT_CHROMA_INTRA) != 0;
    if (features & N148_FEATURE_ADAPTIVE_LOOP_FILTER)
        return n148_adaptive_filter_encode(
            y, cb, cr, quality, chroma_quality, predictive_features(features),
            effort, joint_chroma, output);
    if (features & N148_FEATURE_SEGMENTATION)
        return n148_segmented_encode(
            y, cb, cr, quality, chroma_quality, predictive_features(features),
            effort, joint_chroma, output);
    if (features & N148_FEATURE_CALIBRATED_CHROMA_QUANT)
        return n148_calibrated_chroma_encode(
            y, cb, cr, quality, chroma_quality, predictive_features(features),
            effort, joint_chroma, output);
    if (features & N148_FEATURE_JOINT_CHROMA_INTRA)
        return n148_joint_chroma_encode(
            y, cb, cr, quality, predictive_features(features), effort, output);
    return n148_encode_format_3(y, cb, cr, quality, predictive_features(features), effort,
                          output);
}

int n148_decode_format_4(const uint8_t *metadata, size_t metadata_size,
                   const uint8_t *payload, size_t payload_size,
                   int width, int height, int quality, int chroma_quality,
                   int chroma, uint32_t features,
                   Plane *y, Plane *cb, Plane *cr) {
    if (!n148_format_4_features_valid(features) || chroma_quality < 1 ||
        chroma_quality > 100) return 0;
    int joint_chroma =
        (features & N148_FEATURE_JOINT_CHROMA_INTRA) != 0;
    if (features & N148_FEATURE_ADAPTIVE_LOOP_FILTER)
        return n148_adaptive_filter_decode(
            metadata, metadata_size, payload, payload_size,
            width, height, quality, chroma_quality, chroma,
            predictive_features(features), joint_chroma, y, cb, cr);
    if (features & N148_FEATURE_SEGMENTATION)
        return n148_segmented_decode(
            metadata, metadata_size, payload, payload_size,
            width, height, quality, chroma_quality, chroma,
            predictive_features(features), joint_chroma, y, cb, cr);
    if (features & N148_FEATURE_CALIBRATED_CHROMA_QUANT)
        return n148_calibrated_chroma_decode(
            metadata, metadata_size, payload, payload_size,
            width, height, quality, chroma_quality, chroma,
            predictive_features(features), joint_chroma, y, cb, cr);
    if (features & N148_FEATURE_JOINT_CHROMA_INTRA)
        return n148_joint_chroma_decode(
            metadata, metadata_size, payload, payload_size,
            width, height, quality, chroma, predictive_features(features),
            y, cb, cr);
    return n148_decode_format_3(metadata, metadata_size, payload, payload_size,
                          width, height, quality, chroma,
                          predictive_features(features), y, cb, cr);
}

src/luma_profile.h

O luma_profile.h é a interface do formato 5, o da rodada do brilho, com a tabela calibrada do artigo 37 e as transformadas variáveis com RDO do artigo 33.

O arquivo completo tem 51 linhas:

/*
 * N.148i luma-profile codec interface
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#ifndef N148_LUMA_PROFILE_H
#define N148_LUMA_PROFILE_H

#include <stddef.h>
#include <stdint.h>

#include "ppm.h"
#include "entropy_payload.h"
#include "chroma_profile.h"

#define N148_FEATURE_CALIBRATED_LUMA_QUANT (1u << 17)
#define N148_FEATURE_LUMA_TRANSFORM_16X16 (1u << 18)
#define N148_FEATURE_QUANT_ADAPTIVE_LUMA_FILTER (1u << 19)

#define N148_FORMAT_5_SUPPORTED_FEATURES \
    (N148_FORMAT_4_SUPPORTED_FEATURES | N148_FEATURE_CALIBRATED_LUMA_QUANT | \
     N148_FEATURE_LUMA_TRANSFORM_16X16 | \
     N148_FEATURE_QUANT_ADAPTIVE_LUMA_FILTER)

#define N148_CALIBRATED_LUMA_PROFILE_FEATURES \
    (N148_CALIBRATED_CHROMA_PROFILE_FEATURES | N148_FEATURE_CALIBRATED_LUMA_QUANT)

#define N148_VARIABLE_LUMA_PROFILE_FEATURES \
    (N148_CALIBRATED_LUMA_PROFILE_FEATURES | N148_FEATURE_LUMA_TRANSFORM_16X16)

#define N148_PERCEPTUAL_LUMA_PROFILE_FEATURES \
    (N148_VARIABLE_LUMA_PROFILE_FEATURES | N148_FEATURE_PERCEPTUAL_TRELLIS)

#define N148_QUANT_ADAPTIVE_LUMA_FILTER_PROFILE_FEATURES \
    (N148_VARIABLE_LUMA_PROFILE_FEATURES | N148_FEATURE_QUANT_ADAPTIVE_LUMA_FILTER)

int n148_format_5_features_valid(uint32_t features);

int n148_encode_format_5(Plane *y, Plane *cb, Plane *cr, int quality,
                   int chroma_quality, uint32_t features, int effort,
                   N148EncodedPayload *output);

int n148_decode_format_5(const uint8_t *metadata, size_t metadata_size,
                   const uint8_t *payload, size_t payload_size,
                   int width, int height, int quality, int chroma_quality,
                   int chroma, uint32_t features,
                   Plane *y, Plane *cb, Plane *cr);

#endif

src/luma_profile.c

O luma_profile.c implementa o formato 5 em cima do formato 4, acrescentando as ferramentas do brilho.

O arquivo completo tem 89 linhas:

/*
 * N.148i luma-profile codec
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#include "luma_profile.h"

#include "predictive_codec.h"

static uint32_t chroma_features(uint32_t features) {
    return features & N148_FORMAT_4_SUPPORTED_FEATURES;
}

static uint32_t predictive_features(uint32_t features) {
    return features & N148_FORMAT_3_SUPPORTED_FEATURES;
}

int n148_format_5_features_valid(uint32_t features) {
    if (features & ~N148_FORMAT_5_SUPPORTED_FEATURES) return 0;
    if (!n148_format_4_features_valid(chroma_features(features))) return 0;
    if ((features & N148_FEATURE_CALIBRATED_LUMA_QUANT) &&
        (!(features & N148_FEATURE_INTRA) ||
         !(features & N148_FEATURE_CONTEXTUAL_RDO))) return 0;
    if ((features & N148_FEATURE_LUMA_TRANSFORM_16X16) &&
        (!(features & N148_FEATURE_CONTEXTUAL_RDO) ||
         !(features & N148_FEATURE_INTRA_4X4))) return 0;
    if ((features & N148_FEATURE_QUANT_ADAPTIVE_LUMA_FILTER) &&
        (!(features & N148_FEATURE_LOOP_FILTER) ||
         !(features & N148_FEATURE_CALIBRATED_LUMA_QUANT))) return 0;
    return 1;
}

int n148_encode_format_5(Plane *y, Plane *cb, Plane *cr, int quality,
                   int chroma_quality, uint32_t features, int effort,
                   N148EncodedPayload *output) {
    if (!y || !cb || !cr || !output || quality < 1 || quality > 100 ||
        chroma_quality < 1 || chroma_quality > 100 || effort < 0 ||
        effort > 9 || !n148_format_5_features_valid(features)) return 0;
    int joint_chroma =
        (features & N148_FEATURE_JOINT_CHROMA_INTRA) != 0;
    int calibrated_chroma =
        (features & N148_FEATURE_CALIBRATED_CHROMA_QUANT) != 0;
    int segmented = (features & N148_FEATURE_SEGMENTATION) != 0;
    int adaptive_filter =
        (features & N148_FEATURE_ADAPTIVE_LOOP_FILTER) != 0;
    int calibrated_luma =
        (features & N148_FEATURE_CALIBRATED_LUMA_QUANT) != 0;
    int variable_luma =
        (features & N148_FEATURE_LUMA_TRANSFORM_16X16) != 0;
    int quant_adaptive_filter =
        (features & N148_FEATURE_QUANT_ADAPTIVE_LUMA_FILTER) != 0;
    if (!calibrated_chroma) chroma_quality = quality;
    return n148_predictive_encode(
        y, cb, cr, quality, chroma_quality, predictive_features(features), effort,
        joint_chroma, calibrated_chroma, segmented, adaptive_filter,
        calibrated_luma, variable_luma, 1, quant_adaptive_filter, 0, 0,
        output);
}

int n148_decode_format_5(const uint8_t *metadata, size_t metadata_size,
                   const uint8_t *payload, size_t payload_size,
                   int width, int height, int quality, int chroma_quality,
                   int chroma, uint32_t features,
                   Plane *y, Plane *cb, Plane *cr) {
    if (!n148_format_5_features_valid(features) || chroma_quality < 1 ||
        chroma_quality > 100) return 0;
    int joint_chroma =
        (features & N148_FEATURE_JOINT_CHROMA_INTRA) != 0;
    int calibrated_chroma =
        (features & N148_FEATURE_CALIBRATED_CHROMA_QUANT) != 0;
    int segmented = (features & N148_FEATURE_SEGMENTATION) != 0;
    int adaptive_filter =
        (features & N148_FEATURE_ADAPTIVE_LOOP_FILTER) != 0;
    int calibrated_luma =
        (features & N148_FEATURE_CALIBRATED_LUMA_QUANT) != 0;
    int variable_luma =
        (features & N148_FEATURE_LUMA_TRANSFORM_16X16) != 0;
    int quant_adaptive_filter =
        (features & N148_FEATURE_QUANT_ADAPTIVE_LUMA_FILTER) != 0;
    if (!calibrated_chroma) chroma_quality = quality;
    return n148_predictive_decode(
        metadata, metadata_size, payload, payload_size,
        width, height, quality, chroma_quality, chroma,
        predictive_features(features), joint_chroma, calibrated_chroma, segmented,
        adaptive_filter, calibrated_luma, variable_luma,
        quant_adaptive_filter, 0, 0, y, cb, cr);
}

src/fidelity_profile.h

O fidelity_profile.h é a interface do formato 6, o da rodada da fidelidade, que trouxe a predição planar do artigo 31.

O arquivo completo tem 62 linhas:

/*
 * N.148i fidelity-profile codec interface
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#ifndef N148_FIDELITY_PROFILE_H
#define N148_FIDELITY_PROFILE_H

#include <stddef.h>
#include <stdint.h>

#include "ppm.h"
#include "entropy_payload.h"
#include "luma_profile.h"

#define N148_FEATURE_FILTERED_INTRA_REFERENCES (1u << 20)
#define N148_FEATURE_PLANAR_INTRA_PREDICTION (1u << 21)
#define N148_FEATURE_STRUCTURAL_RDO (1u << 22)
#define N148_FEATURE_QUALITY_LAMBDA (1u << 23)
#define N148_FEATURE_LUMA_TRANSFORM_32X32 (1u << 24)
#define N148_FEATURE_SECOND_ORDER_DC (1u << 25)
#define N148_FEATURE_FINE_INTRA_DIRECTIONS (1u << 26)

#define N148_FORMAT_6_SUPPORTED_FEATURES \
    (N148_FORMAT_5_SUPPORTED_FEATURES | \
     N148_FEATURE_FILTERED_INTRA_REFERENCES | \
     N148_FEATURE_PLANAR_INTRA_PREDICTION | \
     N148_FEATURE_STRUCTURAL_RDO | \
     N148_FEATURE_QUALITY_LAMBDA | \
     N148_FEATURE_LUMA_TRANSFORM_32X32 | \
     N148_FEATURE_SECOND_ORDER_DC | \
     N148_FEATURE_FINE_INTRA_DIRECTIONS)

#define N148_DCT32_PROFILE_FEATURES \
    (N148_VARIABLE_LUMA_PROFILE_FEATURES | N148_FEATURE_LUMA_TRANSFORM_32X32)
#define N148_FILTERED_REFERENCE_PROFILE_FEATURES \
    (N148_VARIABLE_LUMA_PROFILE_FEATURES | N148_FEATURE_FILTERED_INTRA_REFERENCES)
#define N148_PLANAR_PREDICTION_PROFILE_FEATURES \
    (N148_VARIABLE_LUMA_PROFILE_FEATURES | N148_FEATURE_PLANAR_INTRA_PREDICTION)
#define N148_COMBINED_PREDICTION_PROFILE_FEATURES \
    (N148_VARIABLE_LUMA_PROFILE_FEATURES | N148_FEATURE_FILTERED_INTRA_REFERENCES | \
     N148_FEATURE_PLANAR_INTRA_PREDICTION)
#define N148_STRUCTURAL_RDO_PROFILE_FEATURES \
    (N148_PLANAR_PREDICTION_PROFILE_FEATURES | N148_FEATURE_STRUCTURAL_RDO)
#define N148_QUALITY_LAMBDA_PROFILE_FEATURES \
    (N148_PLANAR_PREDICTION_PROFILE_FEATURES | N148_FEATURE_QUALITY_LAMBDA)

int n148_format_6_features_valid(uint32_t features);

int n148_encode_format_6(Plane *y, Plane *cb, Plane *cr, int quality,
                   int chroma_quality, uint32_t features, int effort,
                   N148EncodedPayload *output);

int n148_decode_format_6(const uint8_t *metadata, size_t metadata_size,
                   const uint8_t *payload, size_t payload_size,
                   int width, int height, int quality, int chroma_quality,
                   int chroma, uint32_t features,
                   Plane *y, Plane *cb, Plane *cr);

#endif

src/fidelity_profile.c

O fidelity_profile.c implementa o formato 6, que acrescenta ao formato 5 as ferramentas da rodada 6, como o planar e os experimentos que vimos no cemitério de ideias.

O arquivo completo tem 121 linhas:

/*
 * N.148i fidelity-profile codec
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#include "fidelity_profile.h"

#include "predictive_codec.h"
#include "directional_intra.h"

static uint32_t luma_features(uint32_t features) {
    return features & N148_FORMAT_5_SUPPORTED_FEATURES;
}

static uint32_t predictive_features(uint32_t features) {
    return features & N148_FORMAT_3_SUPPORTED_FEATURES;
}

static uint32_t fidelity_tools(uint32_t features) {
    uint32_t tools = 0;
    if (features & N148_FEATURE_FILTERED_INTRA_REFERENCES)
        tools |= N148_FIDELITY_FILTER_REFERENCES;
    if (features & N148_FEATURE_PLANAR_INTRA_PREDICTION)
        tools |= N148_FIDELITY_PLANAR_PREDICTION;
    if (features & N148_FEATURE_STRUCTURAL_RDO)
        tools |= N148_FIDELITY_STRUCTURAL_RDO;
    if (features & N148_FEATURE_QUALITY_LAMBDA)
        tools |= N148_FIDELITY_QUALITY_LAMBDA;
    if (features & N148_FEATURE_LUMA_TRANSFORM_32X32)
        tools |= N148_FIDELITY_DCT32;
    if (features & N148_FEATURE_SECOND_ORDER_DC)
        tools |= N148_FIDELITY_SECOND_ORDER_DC;
    if (features & N148_FEATURE_FINE_INTRA_DIRECTIONS)
        tools |= N148_FIDELITY_FINE_DIRECTIONS;
    return tools;
}

int n148_format_6_features_valid(uint32_t features) {
    if (features & ~N148_FORMAT_6_SUPPORTED_FEATURES) return 0;
    if (!n148_format_5_features_valid(luma_features(features))) return 0;
    uint32_t fidelity = features & ~N148_FORMAT_5_SUPPORTED_FEATURES;
    if (fidelity &&
        (!(features & N148_FEATURE_INTRA) ||
         !(features & N148_FEATURE_CONTEXTUAL_RDO))) return 0;
    if ((features & N148_FEATURE_PLANAR_INTRA_PREDICTION) &&
        !(features & N148_FEATURE_DIRECTIONAL_INTRA)) return 0;
    if ((features & N148_FEATURE_LUMA_TRANSFORM_32X32) &&
        (!(features & N148_FEATURE_LUMA_TRANSFORM_16X16) ||
         !(features & N148_FEATURE_CALIBRATED_LUMA_QUANT))) return 0;
    return 1;
}

int n148_encode_format_6(Plane *y, Plane *cb, Plane *cr, int quality,
                   int chroma_quality, uint32_t features, int effort,
                   N148EncodedPayload *output) {
    if (!y || !cb || !cr || !output || quality < 1 || quality > 100 ||
        chroma_quality < 1 || chroma_quality > 100 || effort < 0 ||
        effort > 9 || !n148_format_6_features_valid(features)) return 0;
    int joint_chroma =
        (features & N148_FEATURE_JOINT_CHROMA_INTRA) != 0;
    int calibrated_chroma =
        (features & N148_FEATURE_CALIBRATED_CHROMA_QUANT) != 0;
    int segmented = (features & N148_FEATURE_SEGMENTATION) != 0;
    int adaptive_filter =
        (features & N148_FEATURE_ADAPTIVE_LOOP_FILTER) != 0;
    int calibrated_luma =
        (features & N148_FEATURE_CALIBRATED_LUMA_QUANT) != 0;
    int variable_luma =
        (features & N148_FEATURE_LUMA_TRANSFORM_16X16) != 0;
    int quant_adaptive_filter =
        (features & N148_FEATURE_QUANT_ADAPTIVE_LUMA_FILTER) != 0;
    int dct32 =
        (features & N148_FEATURE_LUMA_TRANSFORM_32X32) != 0;
    if (!calibrated_chroma) chroma_quality = quality;
    if (!n148_fidelity_quality_set(quality) ||
        !n148_fidelity_tools_set(fidelity_tools(features))) return 0;
    int success = n148_predictive_encode(
        y, cb, cr, quality, chroma_quality, predictive_features(features), effort,
        joint_chroma, calibrated_chroma, segmented, adaptive_filter,
        calibrated_luma, variable_luma, 1, quant_adaptive_filter, dct32, 0,
        output);
    n148_fidelity_tools_set(0);
    n148_fidelity_quality_set(50);
    return success;
}

int n148_decode_format_6(const uint8_t *metadata, size_t metadata_size,
                   const uint8_t *payload, size_t payload_size,
                   int width, int height, int quality, int chroma_quality,
                   int chroma, uint32_t features,
                   Plane *y, Plane *cb, Plane *cr) {
    if (!n148_format_6_features_valid(features) || chroma_quality < 1 ||
        chroma_quality > 100) return 0;
    int joint_chroma =
        (features & N148_FEATURE_JOINT_CHROMA_INTRA) != 0;
    int calibrated_chroma =
        (features & N148_FEATURE_CALIBRATED_CHROMA_QUANT) != 0;
    int segmented = (features & N148_FEATURE_SEGMENTATION) != 0;
    int adaptive_filter =
        (features & N148_FEATURE_ADAPTIVE_LOOP_FILTER) != 0;
    int calibrated_luma =
        (features & N148_FEATURE_CALIBRATED_LUMA_QUANT) != 0;
    int variable_luma =
        (features & N148_FEATURE_LUMA_TRANSFORM_16X16) != 0;
    int quant_adaptive_filter =
        (features & N148_FEATURE_QUANT_ADAPTIVE_LUMA_FILTER) != 0;
    int dct32 =
        (features & N148_FEATURE_LUMA_TRANSFORM_32X32) != 0;
    if (!calibrated_chroma) chroma_quality = quality;
    if (!n148_fidelity_tools_set(fidelity_tools(features))) return 0;
    int success = n148_predictive_decode(
        metadata, metadata_size, payload, payload_size,
        width, height, quality, chroma_quality, chroma,
        predictive_features(features), joint_chroma, calibrated_chroma, segmented,
        adaptive_filter, calibrated_luma, variable_luma,
        quant_adaptive_filter, dct32, 0, y, cb, cr);
    n148_fidelity_tools_set(0);
    return success;
}

src/entropy_profile.h

O entropy_profile.h é a interface do formato 7, o formato atual, com os contextos ricos do artigo 29.

O arquivo completo tem 72 linhas:

/*
 * N.148i adaptive-entropy profile codec interface
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#ifndef N148_ENTROPY_PROFILE_H
#define N148_ENTROPY_PROFILE_H

#include <stddef.h>
#include <stdint.h>

#include "ppm.h"
#include "entropy_payload.h"
#include "fidelity_profile.h"

#define N148_FEATURE_ADAPTIVE_ENTROPY (1u << 27)
#define N148_FEATURE_RICH_COEFFICIENT_CONTEXTS (1u << 28)
#define N148_FEATURE_MULTIPLE_INTRA_REFERENCES (1u << 29)
#define N148_FEATURE_DIRECTIONAL_SCAN (1u << 30)
#define N148_FEATURE_DIRECTIONAL_TRANSFORM (1u << 31)
/* The format 7 interpretation of a low feature bit previously used only by
   format 2. Format 7 headers make the table choice explicit to the decoder. */
#define N148_FEATURE_SPECTRAL_LUMA_QUANT (1u << 3)
#define N148_FEATURE_REFINED_SPECTRAL_LUMA_QUANT (1u << 4)
#define N148_FEATURE_STRUCTURAL_LUMA_QUANT (1u << 5)
#define N148_FEATURE_BALANCED_RECONSTRUCTION (1u << 31)
#define N148_FEATURE_DETAIL_RECONSTRUCTION (1u << 30)

/* Grow this mask only when an experiment has a complete encoder/decoder
   implementation.  Planned public bits remain rejected until that point. */
#define N148_FORMAT_7_SUPPORTED_FEATURES \
    (N148_FORMAT_6_SUPPORTED_FEATURES | N148_FEATURE_ADAPTIVE_ENTROPY | \
     N148_FEATURE_RICH_COEFFICIENT_CONTEXTS | \
     N148_FEATURE_MULTIPLE_INTRA_REFERENCES | \
     N148_FEATURE_SPECTRAL_LUMA_QUANT | \
     N148_FEATURE_REFINED_SPECTRAL_LUMA_QUANT | \
     N148_FEATURE_STRUCTURAL_LUMA_QUANT | \
     N148_FEATURE_BALANCED_RECONSTRUCTION | \
     N148_FEATURE_DETAIL_RECONSTRUCTION)

#define N148_ADAPTIVE_ENTROPY_PROFILE_FEATURES \
    (N148_PLANAR_PREDICTION_PROFILE_FEATURES | N148_FEATURE_ADAPTIVE_ENTROPY)
#define N148_RICH_CONTEXT_PROFILE_FEATURES \
    (N148_ADAPTIVE_ENTROPY_PROFILE_FEATURES | \
     N148_FEATURE_RICH_COEFFICIENT_CONTEXTS)
#define N148_MULTIPLE_REFERENCE_PROFILE_FEATURES \
    (N148_RICH_CONTEXT_PROFILE_FEATURES | N148_FEATURE_MULTIPLE_INTRA_REFERENCES)
#define N148_DIRECTIONAL_SCAN_PROFILE_FEATURES \
    (N148_MULTIPLE_REFERENCE_PROFILE_FEATURES | N148_FEATURE_DIRECTIONAL_SCAN)
#define N148_DIRECTIONAL_TRANSFORM_PROFILE_FEATURES \
    (N148_DIRECTIONAL_SCAN_PROFILE_FEATURES | N148_FEATURE_DIRECTIONAL_TRANSFORM)

int n148_format_7_features_valid(uint32_t features);

int n148_encode_format_7(Plane *y, Plane *cb, Plane *cr, int quality,
                   int chroma_quality, uint32_t features, int effort,
                   N148EncodedPayload *output);

int n148_decode_format_7(const uint8_t *metadata, size_t metadata_size,
                   const uint8_t *payload, size_t payload_size,
                   int width, int height, int quality, int chroma_quality,
                   int chroma, uint32_t features,
                   Plane *y, Plane *cb, Plane *cr);

int n148_inspect_format_7(const uint8_t *metadata, size_t metadata_size,
                    const uint8_t *payload, size_t payload_size,
                    int width, int height, int chroma, uint32_t features,
                    N148SyntaxInspection *inspection);

#endif

src/entropy_profile.c

O entropy_profile.c implementa o formato 7, que junta os contextos ricos, as tabelas espectral e estrutural do artigo 37 e as reconstruções balanceada e de detalhe do artigo 38, incluindo o filtro de saída da cor.

O arquivo completo tem 323 linhas:

/*
 * N.148i adaptive-entropy profile codec
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#include "entropy_profile.h"

#include "predictive_codec.h"
#include "directional_intra.h"

static uint32_t fidelity_features(uint32_t features) {
    return features & N148_FORMAT_6_SUPPORTED_FEATURES;
}

static uint32_t predictive_features(uint32_t features) {
    return features & N148_FORMAT_3_SUPPORTED_FEATURES;
}

static uint32_t fidelity_tools(uint32_t features) {
    uint32_t tools = 0;
    if (features & N148_FEATURE_FILTERED_INTRA_REFERENCES)
        tools |= N148_FIDELITY_FILTER_REFERENCES;
    if (features & N148_FEATURE_PLANAR_INTRA_PREDICTION)
        tools |= N148_FIDELITY_PLANAR_PREDICTION;
    if (features & N148_FEATURE_STRUCTURAL_RDO)
        tools |= N148_FIDELITY_STRUCTURAL_RDO;
    if (features & N148_FEATURE_QUALITY_LAMBDA)
        tools |= N148_FIDELITY_QUALITY_LAMBDA;
    if (features & N148_FEATURE_LUMA_TRANSFORM_32X32)
        tools |= N148_FIDELITY_DCT32;
    if (features & N148_FEATURE_SECOND_ORDER_DC)
        tools |= N148_FIDELITY_SECOND_ORDER_DC;
    if (features & N148_FEATURE_FINE_INTRA_DIRECTIONS)
        tools |= N148_FIDELITY_FINE_DIRECTIONS;
    if (features & N148_FEATURE_MULTIPLE_INTRA_REFERENCES)
        tools |= N148_FIDELITY_MULTIPLE_REFERENCES;
    if (features & N148_FEATURE_SPECTRAL_LUMA_QUANT)
        tools |= N148_FIDELITY_SPECTRAL_LUMA_QUANT;
    if (features & N148_FEATURE_REFINED_SPECTRAL_LUMA_QUANT)
        tools |= N148_FIDELITY_REFINED_SPECTRAL_LUMA_QUANT;
    if (features & N148_FEATURE_STRUCTURAL_LUMA_QUANT)
        tools |= N148_FIDELITY_STRUCTURAL_LUMA_QUANT;
    if (features & N148_FEATURE_DETAIL_RECONSTRUCTION)
        tools |= N148_FIDELITY_DETAIL_RECONSTRUCTION;
    if (features & N148_FEATURE_BALANCED_RECONSTRUCTION)
        tools |= N148_FIDELITY_BALANCED_RECONSTRUCTION;
    return tools;
}

static uint32_t entropy_tools(uint32_t features) {
    uint32_t tools = 0;
    if (features & N148_FEATURE_ADAPTIVE_ENTROPY)
        tools |= N148_ENTROPY_ADAPTIVE;
    if (features & N148_FEATURE_RICH_COEFFICIENT_CONTEXTS)
        tools |= N148_ENTROPY_RICH_CONTEXT;
    if (features & N148_FEATURE_MULTIPLE_INTRA_REFERENCES)
        tools |= N148_ENTROPY_MULTIPLE_REFERENCES;
    return tools;
}

int n148_format_7_features_valid(uint32_t features) {
    if (features & ~N148_FORMAT_7_SUPPORTED_FEATURES) return 0;
    if (!n148_format_6_features_valid(fidelity_features(features))) return 0;
    if ((features & N148_FEATURE_ADAPTIVE_ENTROPY) &&
        (!(features & N148_FEATURE_RANS) ||
         !(features & N148_FEATURE_CONTEXT))) return 0;
    if ((features & N148_FEATURE_RICH_COEFFICIENT_CONTEXTS) &&
        (!(features & N148_FEATURE_RANS) ||
         !(features & N148_FEATURE_CONTEXT) ||
         !(features & N148_FEATURE_INTRA) ||
         !(features & N148_FEATURE_ADAPTIVE_ENTROPY))) return 0;
    if ((features & N148_FEATURE_MULTIPLE_INTRA_REFERENCES) &&
        (!(features & N148_FEATURE_RICH_COEFFICIENT_CONTEXTS) ||
         !(features & N148_FEATURE_CONTEXTUAL_RDO) ||
         !(features & N148_FEATURE_DIRECTIONAL_INTRA))) return 0;
    if ((features & N148_FEATURE_SPECTRAL_LUMA_QUANT) &&
        !(features & N148_FEATURE_CALIBRATED_LUMA_QUANT)) return 0;
    if ((features & N148_FEATURE_REFINED_SPECTRAL_LUMA_QUANT) &&
        !(features & N148_FEATURE_SPECTRAL_LUMA_QUANT)) return 0;
    if ((features & N148_FEATURE_BALANCED_RECONSTRUCTION) &&
        !(features & N148_FEATURE_STRUCTURAL_LUMA_QUANT)) return 0;
    if ((features & N148_FEATURE_DETAIL_RECONSTRUCTION) &&
        !(features & N148_FEATURE_BALANCED_RECONSTRUCTION)) return 0;
    if (features & N148_FEATURE_STRUCTURAL_LUMA_QUANT) {
        const uint32_t required = N148_FEATURE_REFINED_SPECTRAL_LUMA_QUANT |
            N148_FEATURE_SEGMENTATION | N148_FEATURE_CONTEXTUAL_RDO |
            N148_FEATURE_CALIBRATED_CHROMA_QUANT |
            N148_FEATURE_LUMA_TRANSFORM_16X16;
        if ((features & required) != required) return 0;
    }
    return 1;
}

int n148_encode_format_7(Plane *y, Plane *cb, Plane *cr, int quality,
                   int chroma_quality, uint32_t features, int effort,
                   N148EncodedPayload *output) {
    if (!y || !cb || !cr || !output || quality < 1 || quality > 100 ||
        chroma_quality < 1 || chroma_quality > 100 || effort < 0 ||
        effort > 9 || !n148_format_7_features_valid(features)) return 0;
    int joint_chroma =
        (features & N148_FEATURE_JOINT_CHROMA_INTRA) != 0;
    int calibrated_chroma =
        (features & N148_FEATURE_CALIBRATED_CHROMA_QUANT) != 0;
    int segmented = (features & N148_FEATURE_SEGMENTATION) != 0;
    int adaptive_filter =
        (features & N148_FEATURE_ADAPTIVE_LOOP_FILTER) != 0;
    int calibrated_luma =
        (features & N148_FEATURE_CALIBRATED_LUMA_QUANT) != 0;
    int variable_luma =
        (features & N148_FEATURE_LUMA_TRANSFORM_16X16) != 0;
    int quant_adaptive_filter =
        (features & N148_FEATURE_QUANT_ADAPTIVE_LUMA_FILTER) != 0;
    int dct32 =
        (features & N148_FEATURE_LUMA_TRANSFORM_32X32) != 0;
    if (!calibrated_chroma) chroma_quality = quality;
    uint32_t encoder_tools = fidelity_tools(features);
    /* Efforts 3 and 4 use the measured four-mode shortlist. Effort 4 may
       revisit the runner-up on difficult luma blocks. */
    if ((effort == 3 || effort == 4) &&
        (features & N148_FEATURE_RICH_COEFFICIENT_CONTEXTS))
        encoder_tools |= N148_FIDELITY_FAST_MODE_SEARCH;
    if (!n148_fidelity_quality_set(quality) ||
        !n148_fidelity_tools_set(encoder_tools)) return 0;
    uint32_t entropy = entropy_tools(features);
    int success;
    if ((entropy & N148_ENTROPY_RICH_CONTEXT) && effort < 5) {
        /* The accepted maximum-compression path compares two complete
           representations. Lower effort levels retain exact format 6 entropy and
           avoid paying that search cost. The format 7 metadata-revision fallback
           makes the choice self-describing. */
        success = n148_predictive_encode(
            y, cb, cr, quality, chroma_quality, predictive_features(features), effort,
            joint_chroma, calibrated_chroma, segmented, adaptive_filter,
            calibrated_luma, variable_luma, 1, quant_adaptive_filter, dct32,
            entropy & N148_ENTROPY_MULTIPLE_REFERENCES, output);
    } else if (entropy & N148_ENTROPY_RICH_CONTEXT) {
        N148EncodedPayload rich = {0};
        N148EncodedPayload legacy = {0};
        N148PredictivePreparation prepared = {0};
        success = n148_predictive_encode_cached(
            y, cb, cr, quality, chroma_quality, predictive_features(features), effort,
            joint_chroma, calibrated_chroma, segmented, adaptive_filter,
            calibrated_luma, variable_luma, 1, quant_adaptive_filter, dct32,
            entropy, &rich, &prepared) &&
            n148_predictive_encode_cached(
                y, cb, cr, quality, chroma_quality, predictive_features(features),
                effort, joint_chroma, calibrated_chroma, segmented,
                adaptive_filter, calibrated_luma, variable_luma, 1,
                quant_adaptive_filter, dct32,
                entropy & N148_ENTROPY_MULTIPLE_REFERENCES, &legacy, &prepared);
        if (success) {
            int rich_overflow = rich.metadata_size >
                SIZE_MAX - rich.payload_size;
            int legacy_overflow = legacy.metadata_size >
                SIZE_MAX - legacy.payload_size;
            if (rich_overflow || legacy_overflow) {
                success = 0;
            } else if (legacy.metadata_size + legacy.payload_size <
                       rich.metadata_size + rich.payload_size) {
                *output = legacy;
                legacy = (N148EncodedPayload){0};
            } else {
                *output = rich;
                rich = (N148EncodedPayload){0};
            }
        }
        n148_encoded_payload_release(&rich);
        n148_encoded_payload_release(&legacy);
        n148_predictive_preparation_release(&prepared);
    } else {
        success = n148_predictive_encode(
            y, cb, cr, quality, chroma_quality, predictive_features(features), effort,
            joint_chroma, calibrated_chroma, segmented, adaptive_filter,
            calibrated_luma, variable_luma, 1, quant_adaptive_filter, dct32,
            entropy, output);
    }
    n148_fidelity_tools_set(0);
    n148_fidelity_quality_set(50);
    return success;
}

/* Balanced output reconstruction: mix each stored chroma sample with
   one quarter of its clamped 3x3 mean. All rows read this stage's
   unmodified samples; prediction references are already complete. */
#include "cpu.h"
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#if defined(__x86_64__) || defined(__i386__)
#include <immintrin.h>
__attribute__((target("avx2")))
static int balanced_smooth_row(const unsigned char *a,const unsigned char *b,
    const unsigned char *c,unsigned char *output,int width,int shift) {
    int x=1;
    const int half=(9<<shift)/2;
    __m128i count=_mm_cvtsi32_si128(shift);
    for(;x<width-16;x+=16) {
        __m256i center=_mm256_cvtepu8_epi16(_mm_loadu_si128((const __m128i *)(b+x)));
        __m256i delta=_mm256_sub_epi16(_mm256_setzero_si256(),_mm256_slli_epi16(center,3));
        for(int k=-1;k<=1;++k) {
            delta=_mm256_add_epi16(delta,_mm256_cvtepu8_epi16(_mm_loadu_si128((const __m128i *)(a+x+k))));
            delta=_mm256_add_epi16(delta,_mm256_cvtepu8_epi16(_mm_loadu_si128((const __m128i *)(c+x+k))));
        }
        delta=_mm256_add_epi16(delta,_mm256_cvtepu8_epi16(_mm_loadu_si128((const __m128i *)(b+x-1))));
        delta=_mm256_add_epi16(delta,_mm256_cvtepu8_epi16(_mm_loadu_si128((const __m128i *)(b+x+1))));
        __m256i negative=_mm256_cmpgt_epi16(_mm256_setzero_si256(),delta);
        __m256i magnitude=_mm256_add_epi16(_mm256_abs_epi16(delta),_mm256_set1_epi16((short)half));
        magnitude=_mm256_sub_epi16(magnitude,_mm256_and_si256(negative,_mm256_set1_epi16(1)));
        /* Numerator <= 3192: this reciprocal is exact over the used range. */
        __m256i correction=_mm256_srl_epi16(_mm256_mulhi_epu16(magnitude,_mm256_set1_epi16(7282)),count);
        correction=_mm256_sign_epi16(correction,delta);
        __m256i value=_mm256_add_epi16(center,correction);
        _mm_storeu_si128((__m128i *)(output+x),_mm_packus_epi16(
            _mm256_castsi256_si128(value),_mm256_extracti128_si256(value,1)));
    }
    return x;
}
#endif

static unsigned char balanced_smooth_pixel(const unsigned char *a,
    const unsigned char *b,const unsigned char *c,int x,int width,int shift) {
    int left=x ? x-1 : x,right=x+1<width ? x+1 : x;
    int delta=a[left]+a[x]+a[right]+b[left]+b[right]+c[left]+c[x]+c[right]-8*b[x];
    int denominator=9<<shift;
    int correction=delta>=0 ? (delta+denominator/2)/denominator :
                             -((-delta+denominator/2-1)/denominator);
    return (unsigned char)(b[x]+correction);
}

static int balanced_smooth_chroma(Plane *plane,int quality) {
    if(!plane || !plane->data || plane->width<=0 || plane->height<=0)return 0;
    int shift=2;
    size_t width=(size_t)plane->width;
    if(width>SIZE_MAX/3)return 0;
    unsigned char *scratch=malloc(width*3);
    if(!scratch)return 0;
    unsigned char *a=scratch,*b=a+width,*c=b+width;
    memcpy(a,plane->data,width);memcpy(b,plane->data,width);
    memcpy(c,plane->data+(plane->height>1 ? width : 0),width);
    int vector=0;
#if defined(__x86_64__) || defined(__i386__)
    vector=n148_cpu_level()>=N148_CPU_AVX2;
#endif
    for(int y=0;y<plane->height;++y) {
        unsigned char *output=plane->data+(size_t)y*width;
        output[0]=balanced_smooth_pixel(a,b,c,0,plane->width,shift);
        int x=1;
#if defined(__x86_64__) || defined(__i386__)
        if(vector)x=balanced_smooth_row(a,b,c,output,plane->width,shift);
#endif
        for(;x<plane->width;++x)output[x]=balanced_smooth_pixel(a,b,c,x,plane->width,shift);
        if(y+1<plane->height) {
            unsigned char *old=a;a=b;b=c;c=old;
            int next=y+2<plane->height ? y+2 : plane->height-1;
            memcpy(c,plane->data+(size_t)next*width,width);
        }
    }
    free(scratch);
    return 1;
}

int n148_decode_format_7(const uint8_t *metadata, size_t metadata_size,
                   const uint8_t *payload, size_t payload_size,
                   int width, int height, int quality, int chroma_quality,
                   int chroma, uint32_t features,
                   Plane *y, Plane *cb, Plane *cr) {
    if (!n148_format_7_features_valid(features) || chroma_quality < 1 ||
        chroma_quality > 100) return 0;
    int joint_chroma =
        (features & N148_FEATURE_JOINT_CHROMA_INTRA) != 0;
    int calibrated_chroma =
        (features & N148_FEATURE_CALIBRATED_CHROMA_QUANT) != 0;
    int segmented = (features & N148_FEATURE_SEGMENTATION) != 0;
    int adaptive_filter =
        (features & N148_FEATURE_ADAPTIVE_LOOP_FILTER) != 0;
    int calibrated_luma =
        (features & N148_FEATURE_CALIBRATED_LUMA_QUANT) != 0;
    int variable_luma =
        (features & N148_FEATURE_LUMA_TRANSFORM_16X16) != 0;
    int quant_adaptive_filter =
        (features & N148_FEATURE_QUANT_ADAPTIVE_LUMA_FILTER) != 0;
    int dct32 =
        (features & N148_FEATURE_LUMA_TRANSFORM_32X32) != 0;
    if (!calibrated_chroma) chroma_quality = quality;
    if (!n148_fidelity_tools_set(fidelity_tools(features))) return 0;
    int success = n148_predictive_decode(
        metadata, metadata_size, payload, payload_size,
        width, height, quality, chroma_quality, chroma,
        predictive_features(features), joint_chroma, calibrated_chroma, segmented,
        adaptive_filter, calibrated_luma, variable_luma,
        quant_adaptive_filter, dct32, entropy_tools(features), y, cb, cr);
    if (success && (features & N148_FEATURE_BALANCED_RECONSTRUCTION))
        success = balanced_smooth_chroma(cb, chroma_quality) &&
            balanced_smooth_chroma(cr, chroma_quality);
    n148_fidelity_tools_set(0);
    return success;
}

int n148_inspect_format_7(const uint8_t *metadata, size_t metadata_size,
                    const uint8_t *payload, size_t payload_size,
                    int width, int height, int chroma, uint32_t features,
                    N148SyntaxInspection *inspection) {
    if (!n148_format_7_features_valid(features)) return 0;
    int joint_chroma =
        (features & N148_FEATURE_JOINT_CHROMA_INTRA) != 0;
    int segmented = (features & N148_FEATURE_SEGMENTATION) != 0;
    int adaptive_filter =
        (features & N148_FEATURE_ADAPTIVE_LOOP_FILTER) != 0;
    int variable_luma =
        (features & N148_FEATURE_LUMA_TRANSFORM_16X16) != 0;
    int dct32 =
        (features & N148_FEATURE_LUMA_TRANSFORM_32X32) != 0;
    if (!n148_fidelity_tools_set(fidelity_tools(features))) return 0;
    int success = n148_entropy_profile_inspect(
        metadata, metadata_size, payload, payload_size,
        width, height, chroma, predictive_features(features), joint_chroma,
        segmented, adaptive_filter, variable_luma, dct32,
        entropy_tools(features), inspection);
    n148_fidelity_tools_set(0);
    return success;
}

src/luma_projection_avx2.inc

O luma_projection_avx2.inc é incluído pelo ppm.c e traz a versão em AVX2 da projeção do brilho a partir da cor, da reconstrução balanceada do artigo 38.

O arquivo completo tem 62 linhas:

#if defined(__x86_64__) || defined(__i386__)
/* Eight interior 4:2:x pixels. Byte loads stay within each chroma row;
   scalar borders and nonsubsampled planes retain the original path. */
__attribute__((target("avx2")))
static __m128i projection_chroma8(const unsigned char *first,
                                            const unsigned char *second) {
    const __m128i centres = _mm_setr_epi8(1,1,2,2,3,3,4,4,-1,-1,-1,-1,-1,-1,-1,-1);
    const __m128i neighbours = _mm_setr_epi8(0,2,1,3,2,4,3,5,-1,-1,-1,-1,-1,-1,-1,-1);
    __m128i a = _mm_loadl_epi64((const __m128i *)first);
    __m128i b = _mm_loadl_epi64((const __m128i *)second);
    __m128i a0 = _mm_cvtepu8_epi16(_mm_shuffle_epi8(a, centres));
    __m128i a1 = _mm_cvtepu8_epi16(_mm_shuffle_epi8(a, neighbours));
    __m128i b0 = _mm_cvtepu8_epi16(_mm_shuffle_epi8(b, centres));
    __m128i b1 = _mm_cvtepu8_epi16(_mm_shuffle_epi8(b, neighbours));
    return _mm_add_epi16(_mm_add_epi16(_mm_mullo_epi16(a0,_mm_set1_epi16(9)),
                                      _mm_mullo_epi16(a1,_mm_set1_epi16(3))),
                         _mm_add_epi16(_mm_mullo_epi16(b0,_mm_set1_epi16(3)),b1));
}

__attribute__((target("avx2")))
static __m128i project_luma4(__m128i rgb, __m128i y,
                                  __m128i cb, __m128i cr, double strength) {
    __m256d blue = _mm256_sub_pd(_mm256_div_pd(_mm256_cvtepi32_pd(cb),
                                  _mm256_set1_pd(16.0)),_mm256_set1_pd(128.0));
    __m256d red = _mm256_sub_pd(_mm256_div_pd(_mm256_cvtepi32_pd(cr),
                                  _mm256_set1_pd(16.0)),_mm256_set1_pd(128.0));
    __m256d source = _mm256_cvtepi32_pd(y);
    __m256d target = _mm256_sub_pd(_mm256_sub_pd(_mm256_cvtepi32_pd(rgb),
                       _mm256_mul_pd(_mm256_set1_pd(1.427864),blue)),
                       _mm256_mul_pd(_mm256_set1_pd(0.687864),red));
    target = _mm256_div_pd(target,_mm256_set1_pd(3.0));
    target = _mm256_add_pd(source,_mm256_mul_pd(_mm256_set1_pd(strength),
                           _mm256_sub_pd(target,source)));
    target = _mm256_min_pd(_mm256_max_pd(target,_mm256_setzero_pd()),
                           _mm256_set1_pd(255.0));
    return _mm256_cvttpd_epi32(_mm256_add_pd(target,_mm256_set1_pd(0.5)));
}

__attribute__((target("avx2")))
static void project_luma8_avx2(const unsigned char *rgb,
    const unsigned char *source, const unsigned char *cb0,
    const unsigned char *cb1, const unsigned char *cr0,
    const unsigned char *cr1, unsigned char *output, double strength) {
    __m256i pixels = _mm256_i32gather_epi32((const int *)rgb,
                              _mm256_setr_epi32(0,3,6,9,12,15,18,21),1);
    const __m256i mask = _mm256_set1_epi32(255);
    __m256i sum = _mm256_add_epi32(_mm256_add_epi32(_mm256_and_si256(pixels,mask),
                  _mm256_and_si256(_mm256_srli_epi32(pixels,8),mask)),
                  _mm256_and_si256(_mm256_srli_epi32(pixels,16),mask));
    __m256i y = _mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i *)source));
    __m256i cb = _mm256_cvtepu16_epi32(projection_chroma8(cb0,cb1));
    __m256i cr = _mm256_cvtepu16_epi32(projection_chroma8(cr0,cr1));
    __m128i low = project_luma4(_mm256_castsi256_si128(sum),
                         _mm256_castsi256_si128(y),_mm256_castsi256_si128(cb),
                         _mm256_castsi256_si128(cr),strength);
    __m128i high = project_luma4(_mm256_extracti128_si256(sum,1),
                         _mm256_extracti128_si256(y,1),_mm256_extracti128_si256(cb,1),
                         _mm256_extracti128_si256(cr,1),strength);
    __m128i shorts = _mm_packus_epi32(low,high);
    _mm_storel_epi64((__m128i *)output,_mm_packus_epi16(shorts,shorts));
}
#endif

A pasta examples

Aqui fica o exemplo que mostra como usar a biblioteca instalada.

examples/CMakeLists.txt

O CMakeLists.txt da pasta examples é o projeto que usa a biblioteca já instalada, do artigo 26. Na V2, ele pede a versão 2 da biblioteca e testa tanto a versão compartilhada quanto a estática.

Na V1, o arquivo tinha 10 linhas:

# Standalone installed-library example
# Copyright (c) 2026 Micilini Roll. Licensed under the MIT License.

cmake_minimum_required(VERSION 3.16)
project(n148i_consumer_example LANGUAGES C)

find_package(n148i 1 CONFIG REQUIRED)

add_executable(n148i_memory_roundtrip memory_roundtrip.c)
target_link_libraries(n148i_memory_roundtrip PRIVATE n148i::n148i)

Na V2, ele ficou com 17 linhas:

# Standalone installed-library example
# Copyright (c) 2026 Micilini Roll. Licensed under the MIT License.

cmake_minimum_required(VERSION 3.16)
project(n148i_consumer_example LANGUAGES C)

find_package(n148i 2 CONFIG REQUIRED)

add_executable(n148i_memory_roundtrip memory_roundtrip.c)
target_link_libraries(n148i_memory_roundtrip PRIVATE n148i::n148i)

add_executable(n148i_static_roundtrip memory_roundtrip.c)
target_link_libraries(n148i_static_roundtrip PRIVATE n148i::n148i_static)

enable_testing()
add_test(NAME installed.shared COMMAND n148i_memory_roundtrip)
add_test(NAME installed.static COMMAND n148i_static_roundtrip)

examples/memory_roundtrip.c

O memory_roundtrip.c é o exemplo mínimo de ida e volta na memória, também do artigo 26, e ele compila sem nenhuma mudança contra a V2.

Ele não mudou da V1 para a V2, e o arquivo completo tem 67 linhas:

/*
 * Minimal N.148i memory-to-memory example
 *
 * Copyright (c) 2026 Micilini Roll
 * Licensed under the MIT License. See LICENSE in the project root.
 */

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

#include <n148i.h>

static void report_error(const char *operation, n148i_result_t result) {
    fprintf(stderr, "%s: %s\n", operation, n148i_result_string(result));
}

int main(void) {
    enum { WIDTH = 64, HEIGHT = 48 };
    uint8_t pixels[WIDTH * HEIGHT * 3];
    for (int y = 0; y < HEIGHT; y++) {
        for (int x = 0; x < WIDTH; x++) {
            size_t offset = ((size_t) y * WIDTH + (size_t) x) * 3;
            pixels[offset + 0] = (uint8_t) (x * 255 / (WIDTH - 1));
            pixels[offset + 1] = (uint8_t) (y * 255 / (HEIGHT - 1));
            pixels[offset + 2] = (uint8_t) ((x ^ y) * 4);
        }
    }

    n148i_image_t source = {pixels, WIDTH, HEIGHT, WIDTH * 3};
    n148i_encode_options_t options;
    n148i_encode_options_init(&options);
    options.quality = 75;

    uint8_t *encoded = NULL;
    size_t encoded_size = 0;
    n148i_result_t result = n148i_encode_memory(
        &source, &options, &encoded, &encoded_size);
    if (result != N148I_OK) {
        report_error("encode", result);
        return EXIT_FAILURE;
    }

    n148i_image_info_t info;
    result = n148i_read_header(encoded, encoded_size, &info);
    if (result != N148I_OK) {
        report_error("read header", result);
        n148i_free_buffer(encoded);
        return EXIT_FAILURE;
    }

    n148i_image_t decoded = {0};
    result = n148i_decode_memory(encoded, encoded_size, &decoded);
    if (result != N148I_OK) {
        report_error("decode", result);
        n148i_free_buffer(encoded);
        return EXIT_FAILURE;
    }

    printf("N.148i %s encoded %ux%u RGB into %zu bytes; decoded %ux%u\n",
           n148i_library_version(), info.width, info.height, encoded_size,
           decoded.width, decoded.height);

    n148i_free_image(&decoded);
    n148i_free_buffer(encoded);
    return EXIT_SUCCESS;
}

A pasta packaging

Estes textos acompanham os pacotes de cada sistema, e a instalação copia o do sistema atual com o nome README.txt.

packaging/README-Darwin.txt

O README-Darwin.txt é o texto que acompanha o pacote do macOS.

Na V1, o arquivo tinha 14 linhas:

N.148i v1 for macOS
Copyright (c) 2026 Micilini Roll. Licensed under the MIT License.

The shared library is in lib/libn148i.dylib and the static library is in
lib/static/libn148i.a. Include include/n148i.h in your application.

Shared link example:
  cc app.c -Iinclude -Llib -ln148i -Wl,-rpath,@loader_path/lib -o app

Static link example:
  cc app.c -DN148I_STATIC_DEFINE -Iinclude lib/static/libn148i.a \
     -pthread -lm -o app

The release workflow builds one universal binary for x86-64 and Apple Silicon.

Na V2, ele ficou com 22 linhas:

N.148i V2 library
Copyright (c) 2026 Micilini Roll. Licensed under the MIT License.

Include include/n148i.h and initialize options with
n148i_encode_options_init(). The V2 default is the detail reconstruction
profile (0xd8a6d7ff), effort 3, 4:2:0, with equal luma/chroma quality.
The product name is V2; the numeric package/ABI version is 2.0.0.
The on-stream format identifier is independently 7. Formats 1 through 7
remain readable. Use N148I_FORMAT_VERSION_1 and feature_flags = 0 for
legacy Huffman output; numbered format presets retain their original masks.
Encode/decode calls in a process require external serialization.
Free library allocations with n148i_free_buffer()/n148i_free_image().

CMake consumer:
  find_package(n148i 2 CONFIG REQUIRED)
  target_link_libraries(app PRIVATE n148i::n148i)
Use n148i::n148i_static for static linkage.

Shared library: lib/libn148i.dylib. Static library: lib/static/libn148i.a.
Provide an appropriate @rpath or bundle the dylib with your application.
The CI package includes x86_64 and arm64 slices. Intel can dispatch AVX2;
Apple Silicon uses the portable scalar implementation.

packaging/README-Linux.txt

O README-Linux.txt faz o mesmo papel no pacote do Linux.

Na V1, o arquivo tinha 14 linhas:

N.148i v1 for Linux
Copyright (c) 2026 Micilini Roll. Licensed under the MIT License.

The shared library is in lib/libn148i.so and the static library is in
lib/static/libn148i.a. Include include/n148i.h in your application.

Shared link example:
  cc app.c -Iinclude -Llib -ln148i -Wl,-rpath,'$ORIGIN/lib' -o app

Static link example:
  cc app.c -DN148I_STATIC_DEFINE -Iinclude lib/static/libn148i.a \
     -pthread -lm -o app

The pkg-config and CMake package files under lib/ can also discover n148i.

Na V2, ele ficou com 23 linhas:

N.148i V2 library
Copyright (c) 2026 Micilini Roll. Licensed under the MIT License.

Include include/n148i.h and initialize options with
n148i_encode_options_init(). The V2 default is the detail reconstruction
profile (0xd8a6d7ff), effort 3, 4:2:0, with equal luma/chroma quality.
The product name is V2; the numeric package/ABI version is 2.0.0.
The on-stream format identifier is independently 7. Formats 1 through 7
remain readable. Use N148I_FORMAT_VERSION_1 and feature_flags = 0 for
legacy Huffman output; numbered format presets retain their original masks.
Encode/decode calls in a process require external serialization.
Free library allocations with n148i_free_buffer()/n148i_free_image().

CMake consumer:
  find_package(n148i 2 CONFIG REQUIRED)
  target_link_libraries(app PRIVATE n148i::n148i)
Use n148i::n148i_static for static linkage.

Shared library: lib/libn148i.so (ABI soname libn148i.so.2).
Static library: lib/static/libn148i.a.
  cc app.c -Iinclude -Llib -ln148i -Wl,-rpath,'$ORIGIN/lib' -o app
  cc app.c -DN148I_STATIC_DEFINE -Iinclude lib/static/libn148i.a -pthread -lm -o app
pkg-config metadata is in lib/pkgconfig. Linux x86-64 dispatches AVX2 at runtime.

packaging/README-Windows.txt

O README-Windows.txt acompanha o pacote do Windows e explica, entre outras coisas, quais DLLs precisam ficar ao lado do programa.

Na V1, o arquivo tinha 12 linhas:

N.148i v1 for Windows x86-64
Copyright (c) 2026 Micilini Roll. Licensed under the MIT License.

The DLL is bin/n148i.dll and its import library is lib/n148i.lib. The static
library is lib/static/n148i.lib. Include include/n148i.h in your application.

When using the shared library, link the import library and place n148i.dll
beside your executable. Define N148I_STATIC_DEFINE before including n148i.h
when linking the static library.

The v1 Windows build uses the tested single-thread fallback because its
parallel implementation is based on POSIX pthreads.

Na V2, ele ficou com 28 linhas:

N.148i V2 library
Copyright (c) 2026 Micilini Roll. Licensed under the MIT License.

Include include/n148i.h and initialize options with
n148i_encode_options_init(). The V2 default is the detail reconstruction
profile (0xd8a6d7ff), effort 3, 4:2:0, with equal luma/chroma quality.
The product name is V2; the numeric package/ABI version is 2.0.0.
The on-stream format identifier is independently 7. Formats 1 through 7
remain readable. Use N148I_FORMAT_VERSION_1 and feature_flags = 0 for
legacy Huffman output; numbered format presets retain their original masks.
Encode/decode calls in a process require external serialization.
Free library allocations with n148i_free_buffer()/n148i_free_image().

CMake consumer:
  find_package(n148i 2 CONFIG REQUIRED)
  target_link_libraries(app PRIVATE n148i::n148i)
Use n148i::n148i_static for static linkage.

Shared library: bin/n148i.dll and lib/n148i.lib (import library).
Static library: lib/static/n148i.lib.
Copy n148i.dll alongside your executable, or add bin/ to PATH.
For a manual static link define N148I_STATIC_DEFINE in the consumer.
The MSVC build uses the portable scalar, single-thread implementation.

MSVC DLL builds require the matching Microsoft C runtime on the target system.
MinGW builds can additionally depend on libgcc_s_seh-1.dll; distribute the
compiler runtime with your application or make it available through PATH.
The local cross-build audit records the actual imported DLLs.

A pasta tools

A pasta tools foi a que mais mudou de cara, porque as ferramentas do benchmark da V1, do artigo 25, foram removidas e substituídas pelas ferramentas do julgamento da V2, do artigo 40.

Estes são os arquivos que existiam na V1 e não existem mais na V2:

  • tools/analyze_final_benchmark.py
  • tools/analyze_local_matrix.py
  • tools/benchmark_final.py
  • tools/benchmark_random_corpus.py
  • tools/collect_benchmark_environment.py
  • tools/compare_benchmark_runs.py
  • tools/fetch_corpus.py
  • tools/prepare_final_corpus.py
  • tools/recheck_entropy_outliers.py

Como eles não fazem parte da V2, o código deles não aparece aqui, mas você encontra todos no commit da V1.

Quase todas as ferramentas novas são em Python e servem para repetir o julgamento, e nenhuma delas é necessária para compilar ou usar o codec.

tools/requirements-benchmark.txt

O requirements-benchmark.txt fixa as versões das bibliotecas Python usadas pelo benchmark, como o NumPy e o SciPy.

O arquivo completo tem 6 linhas:

numpy==2.5.3
scipy==1.18.1
Pillow==12.3.0
scikit-image==0.26.0
sewar==0.4.8
matplotlib==3.11.2

tools/prepare_release_benchmark.py

O prepare_release_benchmark.py monta, isoladas e com versões fixas, as dependências do benchmark e os programas que chamam cada codec.

O arquivo completo tem 165 linhas:

#!/usr/bin/env python3
"""Build isolated, version-pinned benchmark dependencies and API drivers.

Requires a C/C++ compiler, CMake, Git, pkg-config, libjpeg-turbo development
files and libbrotli development files. Nothing is installed system-wide.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import os
from pathlib import Path
import subprocess
import tarfile
import urllib.request

ROOT = Path(__file__).resolve().parents[1]
WEBP_SHA = "e4ab7009bf0629fd11982d4c2aa83964cf244cffba7347ecd39019a9e38c4564"
JXL_COMMIT = "a7a9c787341cf703dede03c2009fa460cae5e5df"


def sha(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--jxl-build", type=Path, help="Reuse a Release libjxl build; identity is recorded")
    parser.add_argument("--jobs", type=int, default=2)
    args = parser.parse_args()
    deps = ROOT / ".benchmark-deps/final"
    work = ROOT / ".build/v2-release"
    deps.mkdir(parents=True, exist_ok=True)
    work.mkdir(parents=True, exist_ok=True)
    commands = []

    def run(argv, cwd=ROOT):
        commands.append({"argv": list(map(str, argv)), "cwd": str(cwd)})
        with (work / "benchmark-build.log").open("a") as log:
            subprocess.run(list(map(str, argv)), cwd=cwd, check=True,
                           stdout=log, stderr=subprocess.STDOUT)

    archive = ROOT / "benchmarks/baselines/n148i-v1-source.tar.gz"
    provenance = json.loads((archive.parent / "provenance.json").read_text())
    if sha(archive) != provenance["archive_sha256"]:
        raise RuntimeError("Original V1 source archive differs from its recorded identity")
    baseline = deps / "v1"
    if not baseline.exists():
        baseline.mkdir()
        with tarfile.open(archive) as tar:
            tar.extractall(baseline, filter="data")
    for item in provenance["files"]:
        if sha(baseline / item["path"]) != item["sha256"]:
            raise RuntimeError("Extracted V1 source changed: " + item["path"])
    run(["make", "-B", f"-j{args.jobs}", "libn148i.a",
         "CFLAGS=-O3 -Wall -Wextra -Wno-unused-parameter -pthread"], baseline)
    run(["make", "-B", f"-j{args.jobs}", "libn148i.a"])

    webp_archive = deps / "libwebp-1.6.0.tar.gz"
    url = "https://storage.googleapis.com/downloads.webmproject.org/releases/webp/libwebp-1.6.0.tar.gz"
    if not webp_archive.exists():
        with urllib.request.urlopen(url, timeout=120) as response:
            webp_archive.write_bytes(response.read())
    if sha(webp_archive) != WEBP_SHA:
        raise RuntimeError("WebP source digest mismatch")
    webp_source = deps / "libwebp-1.6.0"
    if not webp_source.exists():
        with tarfile.open(webp_archive) as tar:
            tar.extractall(deps, filter="data")
    webp_prefix = deps / "webp"
    run(["cmake", "-S", webp_source, "-B", deps / "webp-build",
         "-DCMAKE_BUILD_TYPE=Release", "-DBUILD_SHARED_LIBS=ON",
         *[f"-DWEBP_BUILD_{tool}=OFF" for tool in
           ("ANIM_UTILS", "CWEBP", "DWEBP", "GIF2WEBP", "IMG2WEBP", "VWEBP", "WEBPINFO", "WEBPMUX")],
         "-DCMAKE_INSTALL_PREFIX=" + str(webp_prefix)])
    run(["cmake", "--build", deps / "webp-build", "--parallel", args.jobs])
    run(["cmake", "--install", deps / "webp-build"])

    if args.jxl_build:
        jxl = args.jxl_build.resolve()
        source = jxl.parent
    else:
        source = deps / "libjxl"
        if not source.exists():
            run(["git", "clone", "--branch", "v0.12.0", "--depth", "1",
                 "--recurse-submodules", "--shallow-submodules",
                 "https://github.com/libjxl/libjxl.git", source])
        jxl = source / "build"
        run(["cmake", "-S", source, "-B", jxl, "-DCMAKE_BUILD_TYPE=Release",
             "-DBUILD_SHARED_LIBS=ON", "-DJPEGXL_ENABLE_TOOLS=ON",
             "-DJPEGXL_ENABLE_DEVTOOLS=ON", "-DJPEGXL_ENABLE_BENCHMARK=OFF",
             "-DJPEGXL_ENABLE_EXAMPLES=OFF", "-DJPEGXL_ENABLE_TESTS=OFF"])
        run(["cmake", "--build", jxl, "--parallel", args.jobs, "--target",
             "jxl", "jxl_threads", "ssimulacra2", "butteraugli_main"])
    actual_commit = subprocess.check_output(["git", "-C", str(source), "rev-parse", "HEAD"], text=True).strip()
    dirty = subprocess.check_output(["git", "-C", str(source), "status", "--short"], text=True).strip()
    if actual_commit != JXL_COMMIT or dirty:
        raise RuntimeError("Expected an unmodified official libjxl 0.12.0 source checkout")
    settings = {}
    for line in (jxl / "CMakeCache.txt").read_text().splitlines():
        if line.startswith(("CMAKE_BUILD_TYPE:", "CMAKE_CXX_FLAGS:", "CMAKE_C_FLAGS:", "JPEGXL_", "BUILD_SHARED_LIBS:")) and "=" in line:
            key, value = line.split("=", 1)
            settings[key] = value
    (work / "jxl-provenance.json").write_text(json.dumps({
        "release_tag": "v0.12.0", "commit": actual_commit, "working_tree_clean": True,
        "submodules": subprocess.check_output(["git", "-C", str(source), "submodule", "status", "--recursive"], text=True).strip().splitlines(),
        "cmake_configuration": settings,
    }, indent=2) + "\n")
    jxl_header = jxl / "lib/include/jxl/version.h"
    if "#define JPEGXL_MAJOR_VERSION 0" not in jxl_header.read_text() or \
       "#define JPEGXL_MINOR_VERSION 12" not in jxl_header.read_text() or \
       "#define JPEGXL_PATCH_VERSION 0" not in jxl_header.read_text():
        raise RuntimeError("Expected libjxl 0.12.0 headers")

    compiler = os.environ.get("CC", "cc")
    common = [compiler, "-O3", "-Wall", "-Wextra", "-Wno-unused-parameter",
              "-pthread", "-DN148I_STATIC_DEFINE"]
    driver = ROOT / "src/benchmark_final_cli.c"
    jxl_flags = ["-I" + str(jxl / "lib/include"), "-L" + str(jxl / "lib"),
                 "-ljxl", "-ljxl_threads", "-Wl,--disable-new-dtags",
                 "-Wl,-rpath," + str(jxl / "lib")]
    webp_flags = ["-I" + str(webp_prefix / "include"), "-L" + str(webp_prefix / "lib"),
                  "-lwebp", "-Wl,-rpath," + str(webp_prefix / "lib")]
    drivers = {}
    for label, flags in (("current", webp_flags), ("historical", ["-lwebp"])):
        target = work / ("benchmark-" + label)
        run([*common, "-Iinclude", "-Isrc", driver, "libn148i.a", "-o", target,
             "-lm", "-ljpeg", *jxl_flags, *flags])
        drivers[label] = str(target)
    configurations = {}
    for label, flags in (("current", webp_flags), ("historical", ["-lwebp"])):
        target = work / ("describe-webp-" + label)
        run([compiler, "-O2", ROOT / "tools/describe_webp.c", *flags, "-o", target])
        configurations[label] = json.loads(subprocess.check_output([str(target)], text=True))
    (work / "webp-configurations.json").write_text(json.dumps(configurations, indent=2) + "\n")
    target = work / "benchmark-v1"
    run([*common, "-DN148_BENCH_V1", "-DN148_BENCH_NO_JXL",
         "-I" + str(baseline / "include"), "-I" + str(baseline / "src"), driver,
         baseline / "libn148i.a", "-o", target, "-lm", "-ljpeg", "-lwebp"])
    drivers["v1"] = str(target)
    metrics = {name: str(jxl / "tools" / name) for name in ("ssimulacra2", "butteraugli_main")}
    files = {**drivers, **metrics,
             "v1_source": str(archive), "webp_source": str(webp_archive),
             "jxl": str(jxl / "lib/libjxl.so.0.12.0"),
             "jxl_threads": str(jxl / "lib/libjxl_threads.so.0.12.0"),
             "webp": str(webp_prefix / "lib/libwebp.so.7.2.0")}
    # Resolve the installed soname instead of assuming the package ABI suffix.
    files["webp"] = str((webp_prefix / "lib/libwebp.so").resolve())
    versions = subprocess.check_output(["pkg-config", "--modversion", "libjpeg", "libwebp"], text=True).splitlines()
    if versions[1] != "1.3.2":
        raise RuntimeError("Historical reference requires libwebp 1.3.2 development/runtime files; use the documented Ubuntu environment")
    metadata = {"schema": "n148i-benchmark-build-v1", "drivers": drivers,
                "metrics": metrics, "versions": {"n148i": "V2", "baseline": "V1",
                "jpeg_turbo": versions[0], "webp_historical": versions[1],
                "webp": "1.6.0", "jxl": "0.12.0"}, "commands": commands,
                "files": {k: {"path": v, "sha256": sha(v)} for k, v in files.items()},
                "linkage": {k: subprocess.check_output(["ldd", v], text=True) for k, v in drivers.items()},
                "compiler": subprocess.check_output([compiler, "--version"], text=True)}
    (work / "build.json").write_text(json.dumps(metadata, indent=2) + "\n")
    print("Drivers and dependency hashes saved:", work / "build.json")


if __name__ == "__main__":
    main()

tools/release_benchmark.py

O release_benchmark.py é o roteiro principal do julgamento do artigo 40: primeiro ele mede a qualidade e depois o tempo, sempre na memória.

O arquivo completo tem 259 linhas:

#!/usr/bin/env python3
"""Frozen release comparison: quality first, then isolated in-memory timing."""
from __future__ import annotations

import argparse
from concurrent.futures import ProcessPoolExecutor
import csv
from datetime import datetime, timezone
import hashlib
import gzip
import json
import math
import os
from pathlib import Path
import platform
import random
import re
import subprocess
import tempfile

from benchmark_metrics import quality_metrics, parse_driver

ROOT = Path(__file__).resolve().parents[1]
REPORT = Path(os.environ.get("N148_BENCH_OUTPUT", str(ROOT / "benchmarks/release"))).resolve()
WORK = ROOT / ".build/v2-release"
CODECS = {
    "n148i_v1": ("v1", "n148i"),
    "n148i_v2": ("current", "n148i"),
    "jpeg_turbo": ("current", "jpeg"),
    "webp_m4": ("current", "webp_m4"),
    "webp_m6": ("current", "webp_m6"),
    "webp_m6_historical": ("historical", "webp_m6"),
    "jxl_e3": ("current", "jxl_e3"),
    "jxl_e7": ("current", "jxl_e7"),
}
QUALITIES = [30, 45, 60, 75, 90]
DISTANCES = [8.0, 5.0, 3.0, 1.5, 0.7]


def sha(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def save(path, data):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_suffix(path.suffix + ".tmp")
    temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2, allow_nan=False) + "\n")
    temporary.replace(path)


def now():
    return datetime.now(timezone.utc).isoformat()


def load_matching(images):
    """Read live checkpoints or the compact, published matching audit."""
    directory = REPORT / "matching"
    if directory.is_dir():
        rows = [json.loads((directory / f'{item["image_id"]:03d}.json').read_text())
                for item in images]
    else:
        with gzip.open(REPORT / "matching-audit.jsonl.gz", "rt") as handle:
            rows = [json.loads(line) for line in handle]
    result = {row["image_id"]: row for row in rows}
    if len(rows) != len(images) or set(result) != {item["image_id"] for item in images}:
        raise RuntimeError("Missing or duplicate matching records")
    return result


def linked_libraries(build):
    """Resolve all shared dependencies, including those of metric tools."""
    libraries = {}
    for binary in [*build["drivers"].values(), *build["metrics"].values()]:
        output = subprocess.check_output(["ldd", binary], text=True)
        if "not found" in output:
            raise RuntimeError("Unresolved shared dependency: " + binary)
        for line in output.splitlines():
            match = re.search(r"(?:=>\s*)?(/.+?)\s+\(0x[0-9a-f]+\)", line)
            if match:
                path = match.group(1)
                libraries[path] = sha(path)
    return libraries


def command(build, codec, source, parameter, *, reps=1, warmups=0,
            sample_ms=0.1, prefix=None, cpu=None):
    group, name = CODECS[codec]
    quality = 60 if codec.startswith("jxl") else parameter
    argv = [build["drivers"][group], "--input", str(source), "--codecs", name,
            "--n148-quality", str(int(quality)), "--jpeg-quality", str(int(quality)),
            "--webp-quality", str(quality), "--jxl-distance",
            str(parameter if codec.startswith("jxl") else 3),
            "--n148-effort", "3", "--n148-feature-flags", "0xd8a6d7ff",
            "--n148-chroma-quality", "0", "--chroma", "2",
            "--n148-threads", "1", "--webp-thread-level", "0", "--jxl-threads", "0",
            "--reps", str(reps), "--warmups", str(warmups), "--sample-ms", str(sample_ms)]
    if prefix:
        argv += ["--output-prefix", str(prefix)]
    if cpu is not None:
        argv = ["taskset", "-c", str(cpu), *argv]
    return argv


def verify():
    protocol = json.loads((REPORT / "protocol.json").read_text())
    if (protocol["codecs"] != {key: list(value) for key, value in CODECS.items()} or
        protocol["qualities"] != QUALITIES or protocol["jxl_distances"] != DISTANCES):
        raise RuntimeError("Measurement settings differ from the frozen protocol")
    build = json.loads((WORK / "build.json").read_text())
    frozen_build = json.loads((REPORT / "build.json").read_text())
    for name, item in frozen_build["files"].items():
        if build["files"].get(name, {}).get("sha256") != item["sha256"]:
            raise RuntimeError("Build differs from this run's freeze: " + name +
                               "; use a new N148_BENCH_OUTPUT directory")
    for name, digest in protocol["source_sha256"].items():
        if sha(ROOT / name) != digest:
            raise RuntimeError("Frozen source changed: " + name)
    for item in build["files"].values():
        if sha(item["path"]) != item["sha256"]:
            raise RuntimeError("Binary/source archive changed: " + item["path"])
    linked = REPORT / "linked-library-sha256.json"
    if linked.exists():
        frozen_linkage = json.loads(linked.read_text())
        for path, digest in frozen_linkage.items():
            if sha(path) != digest:
                raise RuntimeError("Linked shared library changed: " + path)
        if linked_libraries(build) != frozen_linkage:
            raise RuntimeError("Runtime dependency resolution differs from the recorded libraries")
    images = json.loads((REPORT / "corpus.json").read_text())["images"]
    if sha(REPORT / "corpus.json") != protocol["corpus_sha256"]:
        raise RuntimeError("Frozen corpus manifest changed")
    for item in images:
        if sha(ROOT / "images" / item["filename"]) != item["ppm_sha256"]:
            raise RuntimeError("Image changed: " + item["filename"])
    return protocol, build, images


def freeze():
    if (REPORT / "protocol.json").exists():
        verify()
        print("Frozen protocol and inputs verified.")
        return
    images = json.loads((ROOT / "images/MANIFEST.json").read_text())["images"]
    if len(images) != 130 or len({x["ppm_sha256"] for x in images}) != 130:
        raise RuntimeError("Expected all 130 development images, without exact duplicates")
    save(REPORT / "corpus.json", {"scope": "development; all inputs used before release freeze", "images": images})
    build = json.loads((WORK / "build.json").read_text())
    save(REPORT / "build.json", build)
    save(REPORT / "linked-library-sha256.json", linked_libraries(build))
    configurations = WORK / "webp-configurations.json"
    if configurations.exists():
        save(REPORT / "webp-configurations.json", json.loads(configurations.read_text()))
    provenance = WORK / "jxl-provenance.json"
    if provenance.exists():
        save(REPORT / "jxl-provenance.json", json.loads(provenance.read_text()))
    sources = [p for directory in ("src", "include") for p in (ROOT / directory).glob("*")
               if p.suffix in (".c", ".h", ".inc")]
    sources += [ROOT / "Makefile", ROOT / "CMakeLists.txt", ROOT / "cmake/n148i.map"]
    protocol = {
        "schema": "n148i-release-protocol-v1", "frozen_utc": now(), "release": "V2",
        "corpus_sha256": sha(REPORT / "corpus.json"), "count": len(images),
        "scope": "Descriptive release benchmark on the complete development corpus; not an unseen holdout.",
        "source_sha256": {str(p.relative_to(ROOT)): sha(p) for p in sources},
        "codecs": CODECS, "qualities": QUALITIES, "jxl_distances": DISTANCES,
        "profile": {"features": "0xd8a6d7ff", "effort": 3, "chroma": "420", "chroma_quality": "luma", "threads": 1},
        "metrics": ["psnr_y_db", "psnr_rgb_db", "ssim", "ms_ssim", "ssimulacra2", "butteraugli", "psnr_chroma_db"],
        "quality": "Same definitions as quality_metrics(); all RGB reconstructions compared with original PPM. Pooled-MSE PSNR, pixel-weighted other metrics, PCHIP BD-rate over shared ranges only; no extrapolation.",
        "uncertainty": {"unit": "image", "paired": True, "stratify_by": "category", "replicates": 10000,
                        "seed": 14820261001, "interval": "percentile 95%", "joint_quality_claim": "Bonferroni 7 metrics per reference; two-sided family alpha 0.05", "limits": "Conditional on this development sample; does not remove tuning bias or estimate cross-host uncertainty."},
        "timing": {"cpu": min(os.sched_getaffinity(0)), "threads": 1, "blocks": 2, "repetitions_per_block": 7,
                   "recovery_unit": "all codecs at one image/mode/level within a block",
                   "warmups": 2, "sample_ms": 20, "order": "Seeded codec shuffle; second block reverses each first-block order",
                   "nominal_points": [30, 60, 90], "matched_modes": ["bytes", "ssim"],
                   "targets": "25%, 50%, 75% of per-image common curve range across all codecs; log scale for bytes, linear for SSIM",
                   "matching": "Bracketed parameter search inside measured endpoints; nearest achievable point; record all residuals and unmatched cases",
                   "size_tolerance_relative": 0.02, "ssim_tolerance_absolute": 0.0005,
                   "interference": "Wait on external QEMU/compiler jobs and CPU load guard; repeat all eight codecs at one image/mode/level if any before/after observation reports interference; preserve other completed groups. Never interrupt other jobs or discard based on which codec wins."},
        "hardware": "This host only; another processor remains pending.",
        "stopping": "Complete matrix and all declared timing points, independent of win/loss. No codec tuning during this benchmark.",
    }
    save(REPORT / "protocol.json", protocol)
    commands = [["uname", "-a"], ["lscpu"], ["cc", "--version"], ["cmake", "--version"],
                ["pkg-config", "--modversion", "libjpeg", "libwebp"]]
    environment = {"date": now(), "python": platform.python_version(), "platform": platform.platform(),
                   "affinity": sorted(os.sched_getaffinity(0)), "commands": {" ".join(c): subprocess.run(c, capture_output=True, text=True).stdout for c in commands}}
    for name in ("numpy", "scipy", "PIL", "skimage", "sewar"):
        module = __import__(name)
        environment[name] = getattr(module, "__version__", "see requirements")
    save(REPORT / "environment.json", environment)
    verify()
    print("Frozen: V1, V2 and six external profiles; all 130 development images.")


def measure_quality(task):
    build, item, codec, point = task
    parameter = (DISTANCES if codec.startswith("jxl") else QUALITIES)[point - 1]
    source = ROOT / "images" / item["filename"]
    base = "/dev/shm" if Path("/dev/shm").is_dir() else None
    with tempfile.TemporaryDirectory(prefix="n148-quality-", dir=base) as directory:
        prefix = Path(directory) / "decoded"
        argv = command(build, codec, source, parameter, prefix=prefix)
        completed = subprocess.run(argv, capture_output=True, text=True, timeout=600, check=True)
        data = parse_driver(completed.stdout)
        native = CODECS[codec][1]
        reconstructed = Path(str(prefix) + "-" + native + ".ppm")
        metrics = quality_metrics(source, reconstructed, Path(build["metrics"]["ssimulacra2"]), Path(build["metrics"]["butteraugli_main"]))
        for key, value in metrics.items():
            if not math.isfinite(value):
                if key.startswith("psnr_") and value == math.inf:
                    metrics[key] = "inf"
                else:
                    raise RuntimeError(f"Invalid metric {key}: {value}")
        row = {"image_id": item["image_id"], "filename": item["filename"], "category": item["category"],
               "pixels": item["width"] * item["height"], "codec": codec, "point": point,
               "parameter": parameter, "bytes": data["sizes"][native],
               "decoded_sha256": sha(reconstructed), **metrics}
    path = REPORT / "quality" / f'{item["image_id"]:03d}-{codec}-{point}.json'
    save(path, row)
    return row


def quality(workers):
    protocol, build, images = verify()
    directory = REPORT / "quality"
    directory.mkdir(exist_ok=True)
    tasks = [(build, item, codec, point) for item in images for point in range(1, 6) for codec in CODECS
             if not (directory / f'{item["image_id"]:03d}-{codec}-{point}.json').exists()]
    total = len(images) * len(CODECS) * 5
    count = total - len(tasks)
    print(f"Quality {count}/{total}; {workers} workers; timings excluded.", flush=True)
    with ProcessPoolExecutor(max_workers=workers) as pool:
        for row in pool.map(measure_quality, tasks, chunksize=1):
            count += 1
            if count % 8 == 0 or count == total:
                print(f'Quality {count}/{total}: image {row["image_id"]}, {row["codec"]}, p{row["point"]}', flush=True)
    rows = [json.loads(path.read_text()) for path in sorted(directory.glob("*.json"))]
    if len(rows) != total:
        raise RuntimeError("Incomplete quality matrix")
    verify()
    with (REPORT / "quality.csv").open("w") as handle:
        writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n")
        writer.writeheader()
        writer.writerows(rows)
    save(REPORT / "quality-status.json", {"status": "complete", "rows": total, "completed_utc": now(), "sha256": sha(REPORT / "quality.csv")})


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("phase", choices=["freeze", "verify", "quality"])
    parser.add_argument("--workers", type=int, default=2)
    args = parser.parse_args()
    if args.phase == "freeze": freeze()
    elif args.phase == "verify": verify(); print("Frozen inputs, sources and binaries verified.")
    else: quality(args.workers)


if __name__ == "__main__":
    main()

tools/benchmark_metrics.py

O benchmark_metrics.py guarda as definições fixas das métricas de qualidade e a leitura das saídas do benchmark.

O arquivo completo tem 119 linhas:

#!/usr/bin/env python3
"""Shared, fixed quality definitions and benchmark-output parsing.
Copyright (c) 2026 Micilini Roll. MIT License.
"""
from __future__ import annotations
from collections import defaultdict
import math
from pathlib import Path
import subprocess
from typing import Any
import numpy as np
from PIL import Image as PillowImage
from sewar.full_ref import msssim
from skimage.metrics import structural_similarity

def parse_driver(stdout: str) -> dict[str, Any]:
    samples: dict[str, list[tuple[int, float, float]]] = defaultdict(list)
    calibration: dict[str, tuple[int, int]] = {}
    sizes: dict[str, int] = {}
    meta: list[str] | None = None
    for raw_line in stdout.splitlines():
        parts = raw_line.strip().split(",")
        if not parts or not parts[0]:
            continue
        if parts[0] == "meta" and len(parts) == 12:
            meta = parts[1:]
        elif parts[0] == "calibration" and len(parts) == 4:
            calibration[parts[1]] = (int(parts[2]), int(parts[3]))
        elif parts[0] == "sample" and len(parts) == 5:
            samples[parts[1]].append((int(parts[2]), float(parts[3]), float(parts[4])))
        elif parts[0] == "result" and len(parts) == 4:
            sizes[parts[1]] = int(parts[2])
    if meta is None or not samples or set(samples) != set(calibration) or set(samples) != set(sizes):
        raise RuntimeError(f"unrecognized/incomplete driver output: {stdout[:1000]!r}")
    for codec, codec_samples in samples.items():
        expected = list(range(len(codec_samples)))
        if [sample[0] for sample in codec_samples] != expected:
            raise RuntimeError(f"non-contiguous samples for {codec}")
    return {"meta": meta, "calibration": calibration, "samples": samples, "sizes": sizes}

def psnr(mse: float) -> float:
    return math.inf if mse == 0.0 else 10.0 * math.log10(65025.0 / mse)

def external_metric(binary: Path, reference: Path, distorted: Path) -> float:
    result = subprocess.run(
        [str(binary), str(reference), str(distorted)], check=False,
        stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=300
    )
    if result.returncode != 0:
        detail = (result.stderr or result.stdout).strip().replace("\n", " ")
        raise RuntimeError(f"{binary.name} failed: {detail[:600]}")
    first_line = result.stdout.strip().splitlines()[0]
    return float(first_line.strip())

def quality_metrics(
    reference_path: Path, distorted_path: Path, ssimulacra2: Path,
    butteraugli: Path,
) -> dict[str, float]:
    with PillowImage.open(reference_path) as image:
        reference = np.asarray(image.convert("RGB"), dtype=np.float64)
    with PillowImage.open(distorted_path) as image:
        distorted = np.asarray(image.convert("RGB"), dtype=np.float64)
    if reference.shape != distorted.shape:
        raise RuntimeError(
            f"metric dimensions differ: {reference.shape} vs {distorted.shape}"
        )
    difference = reference - distorted
    mse_rgb = float(np.mean(difference * difference))
    reference_y = (
        0.299 * reference[:, :, 0] + 0.587 * reference[:, :, 1] +
        0.114 * reference[:, :, 2]
    )
    distorted_y = (
        0.299 * distorted[:, :, 0] + 0.587 * distorted[:, :, 1] +
        0.114 * distorted[:, :, 2]
    )
    reference_cb = (
        -0.168736 * reference[:, :, 0] - 0.331264 * reference[:, :, 1] +
        0.5 * reference[:, :, 2]
    )
    distorted_cb = (
        -0.168736 * distorted[:, :, 0] - 0.331264 * distorted[:, :, 1] +
        0.5 * distorted[:, :, 2]
    )
    reference_cr = (
        0.5 * reference[:, :, 0] - 0.418688 * reference[:, :, 1] -
        0.081312 * reference[:, :, 2]
    )
    distorted_cr = (
        0.5 * distorted[:, :, 0] - 0.418688 * distorted[:, :, 1] -
        0.081312 * distorted[:, :, 2]
    )
    mse_y = float(np.mean((reference_y - distorted_y) ** 2))
    mse_cb = float(np.mean((reference_cb - distorted_cb) ** 2))
    mse_cr = float(np.mean((reference_cr - distorted_cr) ** 2))
    mse_chroma = 0.5 * (mse_cb + mse_cr)
    ssim = float(
        structural_similarity(
            reference, distorted, channel_axis=2, data_range=255.0,
            gaussian_weights=True, sigma=1.5, use_sample_covariance=False,
        )
    )
    ms_ssim = float(np.real(msssim(reference, distorted, MAX=255.0)))
    return {
        "mse_rgb": mse_rgb,
        "mse_y": mse_y,
        "mse_cb": mse_cb,
        "mse_cr": mse_cr,
        "mse_chroma": mse_chroma,
        "psnr_rgb_db": psnr(mse_rgb),
        "psnr_y_db": psnr(mse_y),
        "psnr_cb_db": psnr(mse_cb),
        "psnr_cr_db": psnr(mse_cr),
        "psnr_chroma_db": psnr(mse_chroma),
        "ssim": ssim,
        "ms_ssim": ms_ssim,
        "ssimulacra2": external_metric(ssimulacra2, reference_path, distorted_path),
        "butteraugli": external_metric(butteraugli, reference_path, distorted_path),
    }

tools/benchmark_math.py

O benchmark_math.py calcula o BD-rate com o PCHIP só na faixa comum de qualidade, a mesma conta que refizemos em C no artigo 40.

O arquivo completo tem 60 linhas:

"""Rate-distortion integration over shared measured quality ranges.
Copyright (c) 2026 Micilini Roll. MIT License.
"""
import math
from scipy.interpolate import PchipInterpolator

def pareto_points(points: list[tuple[float, float]]) -> list[tuple[float, float]]:
    """Return increasing-quality, increasing-rate non-dominated points."""
    finite = sorted(
        (quality, rate) for quality, rate in points
        if math.isfinite(quality) and math.isfinite(rate) and rate > 0
    )
    unique: list[tuple[float, float]] = []
    for quality, rate in finite:
        if unique and abs(quality - unique[-1][0]) <= 1e-12:
            if rate < unique[-1][1]:
                unique[-1] = (quality, rate)
        else:
            unique.append((quality, rate))
    # A point is dominated if equal/better quality exists at a lower rate.
    kept_reversed: list[tuple[float, float]] = []
    best_rate = math.inf
    for quality, rate in reversed(unique):
        if rate < best_rate:
            kept_reversed.append((quality, rate))
            best_rate = rate
    kept = list(reversed(kept_reversed))
    # PCHIP also expects rate to grow with quality for a physical RD curve.
    monotone: list[tuple[float, float]] = []
    largest = -math.inf
    for point in kept:
        if point[1] > largest:
            monotone.append(point)
            largest = point[1]
    return monotone

def bd_rate(
    candidate: list[tuple[float, float]], anchor: list[tuple[float, float]]
) -> tuple[float, float, float] | None:
    """PCHIP Bjontegaard delta-rate; negative means candidate uses fewer bits."""
    candidate = pareto_points(candidate)
    anchor = pareto_points(anchor)
    if len(candidate) < 3 or len(anchor) < 3:
        return None
    low = max(candidate[0][0], anchor[0][0])
    high = min(candidate[-1][0], anchor[-1][0])
    if not math.isfinite(low + high) or high - low <= 1e-9:
        return None
    candidate_curve = PchipInterpolator(
        [point[0] for point in candidate],
        [math.log(point[1]) for point in candidate], extrapolate=False,
    )
    anchor_curve = PchipInterpolator(
        [point[0] for point in anchor],
        [math.log(point[1]) for point in anchor], extrapolate=False,
    )
    difference = (
        candidate_curve.integrate(low, high) - anchor_curve.integrate(low, high)
    ) / (high - low)
    return (math.exp(float(difference)) - 1.0) * 100.0, low, high

tools/analyze_release_benchmark.py

O analyze_release_benchmark.py faz o bootstrap pareado e estratificado da comparação de qualidade, com os intervalos de família.

O arquivo completo tem 170 linhas:

#!/usr/bin/env python3
"""Paired, stratified image bootstrap for the frozen release comparison."""
from __future__ import annotations

import argparse
import csv
import json
import math
import hashlib
from pathlib import Path

import numpy as np

from benchmark_math import bd_rate
from release_benchmark import REPORT, CODECS, save

METRICS = {
    "psnr_y_db": "mse_y", "psnr_rgb_db": "mse_rgb", "ssim": None,
    "ms_ssim": None, "ssimulacra2": None, "butteraugli": None,
    "psnr_chroma_db": "mse_chroma",
}


def bootstrap_counts(categories, repetitions, seed):
    """Resample whole images within each stratum; reuse weights for all codecs."""
    rng = np.random.default_rng(seed)
    categories = np.asarray(categories)
    counts = np.zeros((repetitions, len(categories)), dtype=np.int32)
    for category in sorted(set(categories)):
        indices = np.flatnonzero(categories == category)
        draws = rng.choice(indices, size=(repetitions, len(indices)), replace=True)
        for rep in range(repetitions):
            np.add.at(counts[rep], draws[rep], 1)
    return counts


def interval(values, alpha=.05):
    finite = np.asarray([x for x in values if x is not None and math.isfinite(x)], dtype=float)
    if len(finite) == 0:
        return None
    return [float(x) for x in np.quantile(finite, [alpha / 2, 1 - alpha / 2])]


def curve(weights, pixels, sizes, values, mse=False, lower=False):
    """Aggregate with pixel weighting, converting pooled MSE to PSNR last."""
    weighted_pixels = weights * pixels
    denominator = weighted_pixels.sum()
    rates = 8 * (weights @ sizes) / denominator
    quality = (weighted_pixels @ values) / denominator
    if mse:
        with np.errstate(divide="ignore"):
            quality = 10 * np.log10(65025 / quality)
    elif lower:
        quality = -quality
    return list(zip(quality, rates))


def csv_write(path, rows):
    if not rows:
        raise ValueError("Cannot write empty result table")
    with Path(path).open("w") as handle:
        writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n")
        writer.writeheader()
        writer.writerows(rows)


def analyze_quality():
    protocol = json.loads((REPORT / "protocol.json").read_text())
    status = json.loads((REPORT / "quality-status.json").read_text())
    rows = list(csv.DictReader((REPORT / "quality.csv").open()))
    if hashlib.sha256((REPORT / "quality.csv").read_bytes()).hexdigest() != status["sha256"]:
        raise ValueError("Quality CSV digest differs from completion record")
    images = json.loads((REPORT / "corpus.json").read_text())["images"]
    n = len(images)
    keys = {(int(row["image_id"]), row["codec"], int(row["point"])): row for row in rows}
    expected = {(i["image_id"], codec, point) for i in images for codec in CODECS for point in range(1, 6)}
    if status["status"] != "complete" or set(keys) != expected or len(rows) != len(expected):
        raise ValueError("Quality matrix is incomplete or contains duplicate rows")
    pixels = np.asarray([i["width"] * i["height"] for i in images], dtype=float)
    settings = protocol["uncertainty"]
    weights = bootstrap_counts([i["category"] for i in images], settings["replicates"], settings["seed"])
    all_weights = np.vstack([np.ones(n), weights])
    denominators = all_weights @ pixels
    sizes = {codec: np.asarray([[float(keys[i["image_id"], codec, p]["bytes"]) for p in range(1, 6)] for i in images]) for codec in CODECS}
    rates = {codec: 8 * (all_weights @ values) / denominators[:, None] for codec, values in sizes.items()}
    pairs = [(codec, "webp_m6") for codec in CODECS if codec != "webp_m6"]
    pairs += [("n148i_v2", codec) for codec in CODECS if codec not in ("n148i_v2", "webp_m6")]
    summaries, per_image, aggregate = [], [], []
    for metric, mse_field in METRICS.items():
        values = {codec: np.asarray([[float(keys[i["image_id"], codec, p][mse_field or metric]) for p in range(1, 6)] for i in images]) for codec in CODECS}
        qualities = {}
        for codec in CODECS:
            qualities[codec] = (all_weights @ (values[codec] * pixels[:, None])) / denominators[:, None]
            if mse_field:
                with np.errstate(divide="ignore"):
                    qualities[codec] = 10 * np.log10(65025 / qualities[codec])
            elif metric == "butteraugli":
                qualities[codec] = -qualities[codec]
            for point in range(5):
                aggregate.append({"codec": codec, "metric": metric, "point": point + 1,
                                  "bpp": rates[codec][0, point], "quality_axis": qualities[codec][0, point]})
        for candidate, anchor in pairs:
            estimates = []
            for rep in range(len(all_weights)):
                result = bd_rate(list(zip(qualities[candidate][rep], rates[candidate][rep])),
                                 list(zip(qualities[anchor][rep], rates[anchor][rep])))
                estimates.append(result)
            point = estimates[0]
            boot = [result[0] if result else None for result in estimates[1:]]
            valid_bootstrap = sum(x is not None for x in boot)
            ci = interval(boot)
            simultaneous = interval(boot, alpha=.05 / len(METRICS))
            sensitivity = []
            for omitted in (1, 2, 3):
                selected = [p for p in range(5) if p != omitted]
                reduced = bd_rate(list(zip(qualities[candidate][0, selected], rates[candidate][0, selected])),
                                  list(zip(qualities[anchor][0, selected], rates[anchor][0, selected])))
                sensitivity.append({"omitted_point": omitted + 1, "bd_rate_pct": reduced[0] if reduced else None})
            image_values = []
            for index, item in enumerate(images):
                def image_curve(codec):
                    quality = values[codec][index]
                    if mse_field:
                        with np.errstate(divide="ignore"):
                            quality = 10 * np.log10(65025 / quality)
                    elif metric == "butteraugli": quality = -quality
                    return list(zip(quality, 8 * sizes[codec][index] / pixels[index]))
                result = bd_rate(image_curve(candidate), image_curve(anchor))
                per_image.append({"image_id": item["image_id"], "category": item["category"],
                                  "candidate": candidate, "anchor": anchor, "metric": metric,
                                  "bd_rate_pct": result[0] if result else "", "valid": result is not None})
                if result: image_values.append(result[0])
            summaries.append({"candidate": candidate, "anchor": anchor, "metric": metric,
                "bd_rate_pct": point[0] if point else None,
                "quality_overlap": list(point[1:]) if point else None,
                "ci95_pct": ci, "familywise95_pct": simultaneous,
                "bootstrap_valid": valid_bootstrap, "bootstrap_total": len(boot),
                "interior_point_omission": sensitivity,
                "images_valid": len(image_values), "images_missing": n - len(image_values),
                "images_won": sum(x < -1e-9 for x in image_values),
                "images_tied": sum(abs(x) <= 1e-9 for x in image_values),
                "images_lost": sum(x > 1e-9 for x in image_values),
                "median_image_bd_rate_pct": float(np.median(image_values)) if image_values else None,
                "conclusion": ("insufficient_bootstrap_overlap" if valid_bootstrap != len(boot) else
                               "lower_rate" if simultaneous and simultaneous[1] < 0 else
                               "higher_rate" if simultaneous and simultaneous[0] > 0 else "inconclusive")})
            print(f"{metric}: {candidate} / {anchor}: {point[0] if point else None}; CI {ci}", flush=True)
    save(REPORT / "quality-analysis.json", {"scope": protocol["scope"], "method": settings, "comparisons": summaries})
    csv_write(REPORT / "per-image-bd-rate.csv", per_image)
    csv_write(REPORT / "aggregate-curves.csv", aggregate)
    markdown = ["| Codec | Y | RGB | SSIM | MS-SSIM | SSIMULACRA2 | Butteraugli | Chroma |",
                "|---|---:|---:|---:|---:|---:|---:|---:|"]
    for codec in CODECS:
        cells = []
        for metric in METRICS:
            if codec == "webp_m6": cells.append("0 (reference)"); continue
            entry = next(x for x in summaries if x["candidate"] == codec and x["anchor"] == "webp_m6" and x["metric"] == metric)
            value = entry["bd_rate_pct"]
            cells.append(f"{value:+.2f}%" if value is not None else "N/A")
        markdown.append("| " + codec + " | " + " | ".join(cells) + " |")
    (REPORT / "quality-table.md").write_text("\n".join(markdown) + "\n")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.parse_args()
    analyze_quality()


if __name__ == "__main__": main()

tools/match_release_points.py

O match_release_points.py encontra os pontos de operação comparáveis, como o mesmo tamanho ou o mesmo SSIM, antes de medir a velocidade.

O arquivo completo tem 176 linhas:

#!/usr/bin/env python3
"""Select actual comparable operating points before measuring their speed.

All probes are untimed. Preserve search traces and unmatched points. This
selects encoder parameters only; it never adjusts the frozen codec.
"""
from __future__ import annotations

import argparse
from concurrent.futures import ProcessPoolExecutor, wait, FIRST_COMPLETED
import csv
import json
import math
from pathlib import Path
import subprocess
import tempfile
import time

import numpy as np
from PIL import Image
from skimage.metrics import structural_similarity

from benchmark_metrics import parse_driver
from release_benchmark import ROOT, REPORT, CODECS, command, save, verify


def parameter_key(value):
    return f"{value:.6f}"


def match_image(task):
    build, protocol, item, rows = task
    image_id = item["image_id"]
    output = REPORT / "matching" / f"{image_id:03d}.json"
    if output.exists():
        return json.loads(output.read_text())
    source = ROOT / "images" / item["filename"]
    with Image.open(source) as image:
        original = np.asarray(image.convert("RGB"), dtype=np.float64)
    cache = {codec: {} for codec in CODECS}
    for row in rows:
        parameter = float(row["parameter"])
        cache[row["codec"]][parameter_key(parameter)] = {
            "parameter": parameter, "bytes": int(row["bytes"]),
            "ssim": float(row["ssim"]), "origin": "quality_curve"}

    def probe(codec, value):
        value = round(value, 6)
        if codec.startswith("n148i") or codec == "jpeg_turbo":
            value = float(round(value))
        key = parameter_key(value)
        if key in cache[codec]:
            return cache[codec][key]
        temporary_parent = "/dev/shm" if Path("/dev/shm").is_dir() else None
        with tempfile.TemporaryDirectory(prefix="n148-match-", dir=temporary_parent) as directory:
            prefix = Path(directory) / "decoded"
            argv = command(build, codec, source, value, prefix=prefix)
            result = subprocess.run(argv, capture_output=True, text=True, timeout=600, check=True)
            parsed = parse_driver(result.stdout)
            native = CODECS[codec][1]
            with Image.open(str(prefix) + "-" + native + ".ppm") as image:
                reconstructed = np.asarray(image.convert("RGB"), dtype=np.float64)
            score = float(structural_similarity(original, reconstructed, channel_axis=2,
                          data_range=255., gaussian_weights=True, sigma=1.5,
                          use_sample_covariance=False))
            point = {"parameter": value, "bytes": parsed["sizes"][native], "ssim": score,
                     "origin": "search", "argv": argv[:-2]}
        cache[codec][key] = point
        return point

    selections = []
    for mode in ("bytes", "ssim"):
        # Compute ranges from the original five-point curves, never from
        # adaptively selected probes or from speed results.
        ranges = []
        for codec in CODECS:
            values = [float(row[mode]) for row in rows if row["codec"] == codec]
            ranges.append((min(values), max(values)))
        low = max(x[0] for x in ranges)
        high = min(x[1] for x in ranges)
        for level, fraction in (("low", .25), ("medium", .5), ("high", .75)):
            if high <= low:
                selections.append({"mode": mode, "level": level, "status": "no_common_range", "range": [low, high]})
                continue
            target = math.exp(math.log(low) + fraction * math.log(high / low)) if mode == "bytes" else low + fraction * (high - low)
            for codec in CODECS:
                tolerance = target * protocol["timing"]["size_tolerance_relative"] if mode == "bytes" else protocol["timing"]["ssim_tolerance_absolute"]
                integer = codec.startswith("n148i") or codec == "jpeg_turbo"
                direction = -1 if codec.startswith("jxl") else 1
                original_points = [p for p in cache[codec].values() if p["origin"] == "quality_curve"]
                min_control = min(direction * p["parameter"] for p in original_points)
                max_control = max(direction * p["parameter"] for p in original_points)
                tried = []
                for iteration in range(16):
                    points = sorted(cache[codec].values(), key=lambda p: direction * p["parameter"])
                    best = min(points, key=lambda p: (abs(p[mode] - target), p["parameter"]))
                    if abs(best[mode] - target) <= tolerance:
                        break
                    brackets = [(a, b) for a, b in zip(points, points[1:])
                                if a[mode] <= target <= b[mode]]
                    if not brackets:
                        break
                    a, b = min(brackets, key=lambda pair: abs(pair[0][mode] - target) + abs(pair[1][mode] - target))
                    left, right = direction * a["parameter"], direction * b["parameter"]
                    # Secant estimate, bounded away from an endpoint so every
                    # iteration also contracts the search interval.
                    ratio = (target - a[mode]) / (b[mode] - a[mode]) if b[mode] != a[mode] else .5
                    control = left + max(.2, min(.8, ratio)) * (right - left)
                    control = max(min_control, min(max_control, control))
                    if integer:
                        control = round(control)
                        if control <= left: control = left + 1
                        if control >= right: break
                    parameter = round(direction * control, 6)
                    if parameter_key(parameter) in cache[codec]: break
                    tried.append(parameter)
                    probe(codec, parameter)
                best = min(cache[codec].values(), key=lambda p: (abs(p[mode] - target), p["parameter"]))
                residual = best[mode] - target
                selections.append({"mode": mode, "level": level, "codec": codec,
                    "target": target, "range": [low, high], "parameter": best["parameter"],
                    "bytes": best["bytes"], "ssim": best["ssim"], "residual": residual,
                    "relative_size_residual": (best["bytes"] / target - 1) if mode == "bytes" else None,
                    "tolerance": tolerance, "matched": abs(residual) <= tolerance,
                    "status": "matched" if abs(residual) <= tolerance else "unmatched",
                    "probes": tried})
    result = {"image_id": image_id, "filename": item["filename"], "category": item["category"],
              "selections": selections, "probes": cache}
    save(output, result)
    return result


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--workers", type=int, default=3)
    parser.add_argument("--follow-quality", action="store_true",
                        help="Start each image only after all its frozen quality curves exist")
    args = parser.parse_args()
    protocol, build, images = verify()
    if args.follow_quality:
        completed, pending, submitted = set(), {}, set()
        with ProcessPoolExecutor(max_workers=args.workers) as pool:
            while len(completed) != len(images):
                for item in images:
                    image_id = item["image_id"]
                    if image_id in submitted or len(pending) >= args.workers: continue
                    paths = [REPORT / "quality" / f"{image_id:03d}-{codec}-{point}.json"
                             for codec in CODECS for point in range(1, 6)]
                    if not all(path.exists() for path in paths): continue
                    rows = [json.loads(path.read_text()) for path in paths]
                    future = pool.submit(match_image, (build, protocol, item, rows))
                    pending[future] = image_id
                    submitted.add(image_id)
                if not pending:
                    time.sleep(3)
                    continue
                done, _ = wait(pending, timeout=3, return_when=FIRST_COMPLETED)
                for future in done:
                    result = future.result()
                    completed.add(pending.pop(future))
                    successes = sum(p.get("matched", False) for p in result["selections"])
                    print(f"Matching {len(completed)}/{len(images)}: image {result['image_id']}, {successes}/48 within tolerance", flush=True)
        save(REPORT / "matching-status.json", {"status": "complete", "images": len(images)})
        return
    status = json.loads((REPORT / "quality-status.json").read_text())
    if status["status"] != "complete": raise RuntimeError("Complete quality curves first")
    rows = list(csv.DictReader((REPORT / "quality.csv").open()))
    tasks = [(build, protocol, item, [r for r in rows if int(r["image_id"]) == item["image_id"]]) for item in images]
    with ProcessPoolExecutor(max_workers=args.workers) as pool:
        for index, result in enumerate(pool.map(match_image, tasks), 1):
            successes = sum(p.get("matched", False) for p in result["selections"])
            print(f"Matching {index}/{len(images)}: {successes}/48 points within tolerance", flush=True)
    save(REPORT / "matching-status.json", {"status": "complete", "images": len(images)})


if __name__ == "__main__": main()

tools/time_release_benchmark.py

O time_release_benchmark.py repete esses pontos num núcleo fixo do processador para medir o tempo de encode e de decode.

O arquivo completo tem 206 linhas:

#!/usr/bin/env python3
"""Repeat actual nominal and matched operating points on one pinned CPU.

Do not run other benchmark or build jobs concurrently. External QEMU/build
jobs are awaited, never stopped. Raw samples include allocation and RGB
conversion inside the in-process library calls, excluding file I/O.
"""
from __future__ import annotations

import csv
import json
import os
from pathlib import Path
import random
import subprocess
import time

from benchmark_metrics import parse_driver
from benchmark_host import HostMonitor
from release_benchmark import ROOT, REPORT, CODECS, command, save, verify, now, sha, load_matching

HOST = HostMonitor()

def interference():
    return HOST.conflicts()


def snapshot(cpu):
    result = {"utc": now(), "loadavg": os.getloadavg(), "interference": interference()}
    result["observed_external_cpu_cores"] = HOST.external_cores
    path = Path(f"/sys/devices/system/cpu/cpu{cpu}/cpufreq")
    for field in ("scaling_cur_freq", "scaling_governor"):
        try: result[field] = (path / field).read_text().strip()
        except OSError: result[field] = None
    for line in Path("/proc/stat").read_text().splitlines():
        if line.startswith(f"cpu{cpu} "): result["cpu_ticks"] = line.split()[1:]
    return result


def collect_group(tasks, run_task, observe, pause, record, first_attempt=0):
    """Retry all codecs at one operating point if any observation is noisy.

    Other operating points have separate paired comparisons and checkpoints.
    An interrupted group never contributes a partial set of codecs.
    """
    attempt = first_attempt
    while True:
        before = observe()
        while before["interference"]:
            pause()
            before = observe()
        attempt += 1
        rows, disturbed = [], False
        for task in tasks:
            if observe()["interference"]:
                disturbed = True
                break
            row = run_task(task)
            rows.append(row)
            if row["before"]["interference"] or row["after"]["interference"]:
                disturbed = True
                break
        after = observe()
        disturbed = disturbed or bool(after["interference"])
        audit = {"attempt": attempt, "before": before, "after": after,
                 "status": "interference" if disturbed else "accepted", "rows": rows}
        record(audit)
        if not disturbed:
            return audit


def validate_group(audit, tasks, configuration):
    fields = ("mode", "level", "codec", "parameter", "bytes", "ssim", "matched")
    expected = [[task[key] for key in fields] for task in tasks]
    actual = [[row[key] for key in fields] for row in audit["rows"]]
    observations = [audit["before"], audit["after"]]
    observations += [row[side] for row in audit["rows"] for side in ("before", "after")]
    if (audit["status"] != "accepted" or audit["configuration"] != configuration or
            actual != expected or any(s["interference"] for s in observations)):
        raise RuntimeError("Invalid paired operating-point checkpoint")


def main():
    protocol, build, images = verify()
    for name in ("quality", "matching"):
        if json.loads((REPORT / f"{name}-status.json").read_text())["status"] != "complete":
            raise RuntimeError("Finish untimed quality and matching first")
    if len(os.sched_getaffinity(0)) < 1: raise RuntimeError("No CPU available")
    configuration = protocol["timing"]
    cpu = configuration["cpu"]
    if cpu not in os.sched_getaffinity(0): raise RuntimeError("Frozen CPU is unavailable")
    interference()
    time.sleep(1)
    directory = REPORT / "timing"
    directory.mkdir(exist_ok=True)
    parts = REPORT / "timing-progress"
    parts.mkdir(exist_ok=True)
    if configuration.get("recovery_unit") != "all codecs at one image/mode/level within a block":
        raise RuntimeError("Timing protocol must declare the operating-point recovery unit")
    curves = list(csv.DictReader((REPORT / "quality.csv").open()))
    curve_keys = {(int(r["image_id"]), r["codec"], int(r["point"])): r for r in curves}
    matching = load_matching(images)
    rng = random.Random(protocol["uncertainty"]["seed"])
    schedule = []
    for item in images:
        selection = matching[item["image_id"]]
        groups = []
        for point, label in ((1, "low"), (3, "medium"), (5, "high")):
            entries = []
            for codec in CODECS:
                row = curve_keys[item["image_id"], codec, point]
                entries.append({"mode": "nominal", "level": label, "codec": codec,
                                "parameter": float(row["parameter"]), "bytes": int(row["bytes"]),
                                "ssim": float(row["ssim"]), "matched": False})
            groups.append(entries)
        for mode in ("bytes", "ssim"):
            for label in ("low", "medium", "high"):
                group = [s for s in selection["selections"] if s["mode"] == mode and s["level"] == label and "codec" in s]
                if group: groups.append(group)
        for group in groups:
            rng.shuffle(group)
        # The entire second pass reverses the first block's group and codec
        # orders, spreading thermals/order effects across every comparison.
        schedule.append((item, groups))
    for block in range(configuration["blocks"]):
        image_schedule = schedule if block == 0 else list(reversed(schedule))
        for image_index, (item, groups) in enumerate(image_schedule, 1):
            output = directory / f'{item["image_id"]:03d}-block{block}.json'
            if output.exists():
                for path in parts.glob(f'{item["image_id"]:03d}-block{block}-*.json'):
                    path.unlink()
                continue
            ordered_groups = groups if block == 0 else [list(reversed(g)) for g in reversed(groups)]
            completed = []
            for tasks in ordered_groups:
                if len(tasks) != len(CODECS) or {t["codec"] for t in tasks} != set(CODECS):
                    raise RuntimeError("A paired operating point must contain all codecs")
                mode, level = tasks[0]["mode"], tasks[0]["level"]
                key = f'{item["image_id"]:03d}-block{block}-{mode}-{level}'
                checkpoint = parts / (key + ".json")

                def run_task(task):
                    argv = command(build, task["codec"], ROOT / "images" / item["filename"], task["parameter"],
                                   reps=configuration["repetitions_per_block"], warmups=configuration["warmups"],
                                   sample_ms=configuration["sample_ms"], cpu=cpu)
                    start = snapshot(cpu)
                    result = subprocess.run(argv, capture_output=True, text=True, timeout=1800,
                                            env={**os.environ, "OMP_NUM_THREADS": "1", "OPENBLAS_NUM_THREADS": "1"}, check=True)
                    end = snapshot(cpu)
                    parsed = parse_driver(result.stdout)
                    native = CODECS[task["codec"]][1]
                    if parsed["sizes"][native] != task["bytes"]:
                        raise RuntimeError(f"Encoded size changed at frozen operating point: {item['image_id']} {task}")
                    samples = [{"index": s[0], "encode_ms": s[1], "decode_ms": s[2]} for s in parsed["samples"][native]]
                    return {**task, "image_id": item["image_id"], "category": item["category"],
                                 "pixels": item["width"] * item["height"], "block": block, "samples": samples,
                                 "encode_loops": parsed["calibration"][native][0], "decode_loops": parsed["calibration"][native][1],
                                 "before": start, "after": end, "argv": argv}

                def pause():
                    print("Waiting for external compute/build jobs; no process was interrupted.", flush=True)
                    time.sleep(30)

                def record(audit):
                    audit.update(image_id=item["image_id"], block=block, mode=mode, level=level,
                                 configuration=configuration, unit="paired_operating_point")
                    if audit["status"] == "accepted":
                        save(checkpoint, audit)
                    else:
                        save(directory / f'{key}-rejected{audit["attempt"]}.json', audit)
                        print(f"External interference in image {item['image_id']} {mode}/{level}; all eight codecs at this point will be repeated.", flush=True)

                if checkpoint.exists():
                    audit = json.loads(checkpoint.read_text())
                else:
                    attempts = [int(path.stem.rsplit("rejected", 1)[1]) for path in directory.glob(key + "-rejected*.json")]
                    audit = collect_group(tasks, run_task, lambda: snapshot(cpu), pause, record,
                                          first_attempt=max(attempts, default=0))
                validate_group(audit, tasks, configuration)
                completed.append(audit)
            rows = [row for group in completed for row in group["rows"]]
            save(output, {"image_id": item["image_id"], "block": block, "status": "accepted",
                          "unit": "image_block_with_individually_paired_operating_points",
                          "configuration": configuration, "before": completed[0]["before"],
                          "after": completed[-1]["after"], "rows": rows,
                          "groups": [{k: v for k, v in group.items() if k not in {"rows", "configuration"}}
                                     for group in completed]})
            for group in completed:
                (parts / f'{item["image_id"]:03d}-block{block}-{group["mode"]}-{group["level"]}.json').unlink()
            print(f"Timing block {block+1}/{configuration['blocks']}, image {image_index}/{len(images)} (id {item['image_id']})", flush=True)
    parts.rmdir()
    records = []
    for item in images:
        for block in range(configuration["blocks"]):
            audit = json.loads((directory / f'{item["image_id"]:03d}-block{block}.json').read_text())
            for row in audit["rows"]:
                for sample in row["samples"]:
                    records.append({k: row[k] for k in ("image_id", "category", "pixels", "codec", "mode", "level", "parameter", "bytes", "ssim", "matched", "block", "encode_loops", "decode_loops")} | sample)
    with (REPORT / "timing-samples.csv").open("w") as handle:
        writer = csv.DictWriter(handle, fieldnames=list(records[0]), lineterminator="\n")
        writer.writeheader(); writer.writerows(records)
    verify()
    save(REPORT / "timing-status.json", {"status": "complete", "images": len(images), "samples": len(records), "completed_utc": now(), "sha256": sha(REPORT / "timing-samples.csv")})


if __name__ == "__main__": main()

tools/benchmark_host.py

O benchmark_host.py observa a carga dos outros processos da máquina durante as medições, sem parar nenhum deles.

O arquivo completo tem 58 linhas:

"""Observe external compute load without changing or stopping other jobs."""
from __future__ import annotations

import os
from pathlib import Path
import time


class HostMonitor:
    """Track CPU ticks; require quiet observation before accepting timing work.

    This is a noise guard, not exclusive CPU ownership. Short-lived processes
    can escape observations; raw load and frequency snapshots remain necessary.
    """

    def __init__(self):
        self.owner = os.getpid()
        self.hz = os.sysconf("SC_CLK_TCK")
        self.previous = None
        self.previous_time = None
        self.busy = []
        self.external_cores = None

    def conflicts(self):
        current, named = {}, []
        for path in Path("/proc").glob("[0-9]*/stat"):
            try:
                raw = path.read_text()
                name = raw[raw.index("(") + 1:raw.rindex(")")]
                fields = raw[raw.rindex(")") + 2:].split()
                pid, parent = int(path.parent.name), int(fields[1])
                if pid == self.owner or parent == self.owner or fields[0] in {"Z", "X"}:
                    continue
                ticks = int(fields[11]) + int(fields[12])
                current[pid] = (int(fields[19]), ticks, name)
            except (OSError, ValueError, IndexError):
                continue
            if name.startswith("qemu-system") or name in {"cc1", "cc1plus", "clang", "clang++", "ninja", "rustc"}:
                named.append({"pid": pid, "command": name, "reason": "external_qemu_or_build"})
        stamp = time.monotonic()
        if self.previous is None:
            self.previous, self.previous_time = current, stamp
        elif stamp - self.previous_time >= .75:
            elapsed = stamp - self.previous_time
            self.busy, self.external_cores = [], 0.
            for pid, (started, ticks, name) in current.items():
                before = self.previous.get(pid)
                if before is None or before[0] != started:
                    continue
                cores = max(0., (ticks - before[1]) / (self.hz * elapsed))
                self.external_cores += cores
                if cores >= .5:
                    self.busy.append({"pid": pid, "command": name,
                                      "reason": "external_cpu", "cpu_cores": cores})
            if self.external_cores >= 1.:
                self.busy.append({"reason": "aggregate_external_cpu", "cpu_cores": self.external_cores})
            self.previous, self.previous_time = current, stamp
        return named + self.busy

tools/analyze_release_timing.py

O analyze_release_timing.py faz o bootstrap das medições de tempo, sorteando imagens, blocos e amostras.

O arquivo completo tem 141 linhas:

#!/usr/bin/env python3
"""Paired image/block/sample bootstrap of measured operating-point timings."""
from __future__ import annotations
import csv
import json
from pathlib import Path
import numpy as np
from analyze_release_benchmark import interval, csv_write
from release_benchmark import REPORT, CODECS, save, sha, load_matching


def timing_bootstrap(candidate, anchor, categories, count, seed):
    """Resample images in strata, then blocks/repetitions paired across codecs."""
    rng = np.random.default_rng(seed)
    categories = np.asarray(categories)
    strata = [np.flatnonzero(categories == cat) for cat in sorted(set(categories))]
    n, blocks, repetitions = candidate.shape
    results = []
    for offset in range(0, count, 128):
        batch = min(128, count - offset)
        indices = np.concatenate([rng.choice(s, size=(batch, len(s))) for s in strata], axis=1)
        selected_blocks = rng.integers(blocks, size=(batch, n, blocks, 1))
        selected_repetitions = rng.integers(repetitions, size=(batch, n, blocks, repetitions))
        a = candidate[indices[:, :, None, None], selected_blocks, selected_repetitions]
        b = anchor[indices[:, :, None, None], selected_blocks, selected_repetitions]
        # Each resampled image contributes one median time. Reusing exactly
        # the same indices on both sides preserves the experimental pairing.
        total_a = np.median(a, axis=(2, 3)).sum(axis=1)
        total_b = np.median(b, axis=(2, 3)).sum(axis=1)
        results.extend((100 * (total_a / total_b - 1)).tolist())
    return results


def main():
    protocol = json.loads((REPORT / "protocol.json").read_text())
    status = json.loads((REPORT / "timing-status.json").read_text())
    if status["status"] != "complete": raise RuntimeError("Timing matrix is incomplete")
    if status["sha256"] != sha(REPORT / "timing-samples.csv"):
        raise RuntimeError("Timing CSV digest differs from completion record")
    rows = list(csv.DictReader((REPORT / "timing-samples.csv").open()))
    groups = {}
    for row in rows:
        key = (int(row["image_id"]), row["mode"], row["level"], row["codec"])
        groups.setdefault(key, []).append(row)
    images = json.loads((REPORT / "corpus.json").read_text())["images"]
    matching = load_matching(images)
    expected_groups = {(image["image_id"], "nominal", level, codec) for image in images
                       for level in ("low", "medium", "high") for codec in CODECS}
    for image in images:
        expected_groups.update((image["image_id"], row["mode"], row["level"], row["codec"])
                               for row in matching[image["image_id"]]["selections"] if "codec" in row)
    if set(groups) != expected_groups:
        raise RuntimeError("Timing matrix has missing or unexpected operating points")
    blocks, repetitions = protocol["timing"]["blocks"], protocol["timing"]["repetitions_per_block"]
    for key, samples in groups.items():
        actual = {(int(r["block"]), int(r["index"])) for r in samples}
        expected = {(b, r) for b in range(blocks) for r in range(repetitions)}
        if actual != expected or len(samples) != len(expected):
            raise RuntimeError(f"Missing/duplicate samples: {key}")
        samples.sort(key=lambda r: (int(r["block"]), int(r["index"])))
    comparisons, per_image = [], []
    for mode in ("nominal", "bytes", "ssim"):
        for level in ("low", "medium", "high"):
            for reference in CODECS:
                if reference == "n148i_v2": continue
                pairs = []
                rejected = {"missing_common_range": 0, "unmatched_to_target": 0, "pairwise_tolerance": 0}
                for image in images:
                    a = groups.get((image["image_id"], mode, level, "n148i_v2"))
                    b = groups.get((image["image_id"], mode, level, reference))
                    if not a or not b:
                        rejected["missing_common_range"] += 1; continue
                    if mode != "nominal" and (a[0]["matched"] != "True" or b[0]["matched"] != "True"):
                        rejected["unmatched_to_target"] += 1; continue
                    rate_difference = float(a[0]["bytes"]) / float(b[0]["bytes"]) - 1
                    score_difference = float(a[0]["ssim"]) - float(b[0]["ssim"])
                    if ((mode == "bytes" and abs(rate_difference) > protocol["timing"]["size_tolerance_relative"]) or
                        (mode == "ssim" and abs(score_difference) > protocol["timing"]["ssim_tolerance_absolute"])):
                        rejected["pairwise_tolerance"] += 1; continue
                    pairs.append((image, a, b, rate_difference, score_difference))
                for operation in ("encode_ms", "decode_ms"):
                    if not pairs:
                        comparisons.append({"mode": mode, "level": level, "candidate": "n148i_v2", "anchor": reference,
                                            "operation": operation, "paired_images": 0, "excluded": rejected, "conclusion": "no_matched_pairs"})
                        continue
                    a = np.asarray([[float(s[operation]) for s in pair[1]] for pair in pairs]).reshape(-1, blocks, repetitions)
                    b = np.asarray([[float(s[operation]) for s in pair[2]] for pair in pairs]).reshape(-1, blocks, repetitions)
                    median_a, median_b = np.median(a, axis=(1, 2)), np.median(b, axis=(1, 2))
                    boot = timing_bootstrap(a, b, [p[0]["category"] for p in pairs],
                                            protocol["uncertainty"]["replicates"], protocol["uncertainty"]["seed"])
                    ci, joint = interval(boot), interval(boot, .05 / 6)
                    pixels = sum(p[0]["width"] * p[0]["height"] for p in pairs)
                    entry = {"mode": mode, "level": level, "candidate": "n148i_v2", "anchor": reference,
                        "operation": operation, "paired_images": len(pairs), "total_images": len(images), "excluded": rejected,
                        "time_difference_pct": float(100 * (median_a.sum() / median_b.sum() - 1)),
                        "ci95_pct": ci, "familywise95_pct": joint,
                        "candidate_mean_ms": float(median_a.mean()), "anchor_mean_ms": float(median_b.mean()),
                        "candidate_mpix_s": float(pixels / (1000 * median_a.sum())),
                        "anchor_mpix_s": float(pixels / (1000 * median_b.sum())),
                        "geometric_time_ratio": float(np.exp(np.log(median_a / median_b).mean())),
                        "size_difference_pct_range": [100 * min(p[3] for p in pairs), 100 * max(p[3] for p in pairs)],
                        "ssim_difference_range": [min(p[4] for p in pairs), max(p[4] for p in pairs)],
                        "conclusion": "faster" if joint[1] < 0 else "slower" if joint[0] > 0 else "inconclusive"}
                    comparisons.append(entry)
                    for index, pair in enumerate(pairs):
                        per_image.append({"image_id": pair[0]["image_id"], "mode": mode, "level": level,
                            "anchor": reference, "operation": operation, "candidate_median_ms": median_a[index],
                            "anchor_median_ms": median_b[index], "time_difference_pct": 100 * (median_a[index] / median_b[index] - 1),
                            "size_difference_pct": 100 * pair[3], "ssim_difference": pair[4]})
                    print(f"{mode}/{level}/{reference}/{operation}: {entry['time_difference_pct']:+.3f}% CI {ci}; n={len(pairs)}", flush=True)
    save(REPORT / "timing-analysis.json", {"method": "Paired stratified image bootstrap, nested paired resampling of two blocks and seven repetitions; 10000 replicates. Bonferroni six tests per reference/matching mode (three levels, two operations). Strict pairwise matching tolerance applied in addition to target tolerance.", "comparisons": comparisons})
    csv_write(REPORT / "per-image-timing.csv", per_image)
    common = []
    for item in images:
        entries = {codec: groups.get((item["image_id"], "bytes", "medium", codec)) for codec in CODECS}
        if not all(entries.values()): continue
        baseline_size = float(entries["webp_m6"][0]["bytes"])
        if all(samples[0]["matched"] == "True" and abs(float(samples[0]["bytes"]) / baseline_size - 1) <= protocol["timing"]["size_tolerance_relative"]
               for samples in entries.values()):
            common.append((item, entries))
    table = []
    if common:
        for codec in CODECS:
            entry = {"codec": codec, "images": len(common),
                     "total_bytes": sum(int(p[1][codec][0]["bytes"]) for p in common)}
            for operation in ("encode_ms", "decode_ms"):
                a = np.asarray([[float(r[operation]) for r in p[1][codec]] for p in common]).reshape(-1, blocks, repetitions)
                b = np.asarray([[float(r[operation]) for r in p[1]["webp_m6"]] for p in common]).reshape(-1, blocks, repetitions)
                med_a, med_b = np.median(a, axis=(1, 2)), np.median(b, axis=(1, 2))
                bootstrap = timing_bootstrap(a, b, [p[0]["category"] for p in common], protocol["uncertainty"]["replicates"], protocol["uncertainty"]["seed"])
                total_pixels = sum(p[0]["width"] * p[0]["height"] for p in common)
                entry[operation] = {"mean_ms": float(med_a.mean()), "mpix_s": float(total_pixels / (1000 * med_a.sum())),
                                    "time_difference_pct": float(100 * (med_a.sum() / med_b.sum() - 1)),
                                    "ci95_pct": interval(bootstrap), "familywise95_pct": interval(bootstrap, .05 / 14)}
            table.append(entry)
    save(REPORT / "common-size-timing.json", {"mode": "bytes", "level": "medium", "reference": "webp_m6",
        "scope": "Same subset for all eight codecs; every codec matches target and WebP M6 size within 2% per image. Conditional subset, not the full corpus.",
        "image_ids": [p[0]["image_id"] for p in common], "count": len(common), "total": len(images), "codecs": table})


if __name__ == "__main__": main()

tools/compact_release_evidence.py

O compact_release_evidence.py compacta os registros intermediários sem perder as evidências das medições.

O arquivo completo tem 70 linhas:

#!/usr/bin/env python3
"""Compact completed checkpoints while preserving the measurement evidence."""
from __future__ import annotations

import csv
import gzip
import hashlib
import json
from pathlib import Path
import shutil

from release_benchmark import REPORT, verify


def compact(directory, archive, wrap_filename=False):
    if not directory.exists():
        if not archive.exists():
            raise RuntimeError("Missing audit records: " + str(directory))
        return
    paths = sorted(directory.glob("*.json"))
    if not paths or any(p.suffix != ".json" for p in directory.iterdir()):
        raise RuntimeError("Incomplete checkpoint directory: " + str(directory))
    digests = []
    temporary = archive.with_suffix(archive.suffix + ".tmp")
    with temporary.open("wb") as raw, gzip.GzipFile(filename="", fileobj=raw, mode="wb", mtime=0) as compressed:
        for path in paths:
            record = json.loads(path.read_text())
            if wrap_filename:
                record = {"checkpoint": path.name, "record": record}
            line = (json.dumps(record, ensure_ascii=False, separators=(",", ":"), allow_nan=False) + "\n").encode()
            compressed.write(line)
            digests.append(hashlib.sha256(line).hexdigest())
    with gzip.open(temporary, "rb") as handle:
        actual = [hashlib.sha256(line).hexdigest() for line in handle]
    if actual != digests:
        raise RuntimeError("Compressed audit roundtrip mismatch")
    temporary.replace(archive)
    shutil.rmtree(directory)


def main():
    verify()
    for phase in ("quality", "matching", "timing"):
        if json.loads((REPORT / f"{phase}-status.json").read_text())["status"] != "complete":
            raise RuntimeError("Refusing to compact an incomplete experiment")
    for result in ("quality-analysis.json", "timing-analysis.json", "common-size-timing.json", "rate-distortion.svg"):
        if not (REPORT / result).exists():
            raise RuntimeError("Finish analysis first: " + result)
    quality = REPORT / "quality"
    if quality.exists():
        with (REPORT / "quality.csv").open() as handle:
            rows = list(csv.DictReader(handle))
        expected = {(r["image_id"], r["codec"], r["point"]): r for r in rows}
        paths = list(quality.glob("*.json"))
        if len(paths) != len(rows):
            raise RuntimeError("Quality checkpoint/CSV counts differ")
        for path in paths:
            row = {key: str(value) for key, value in json.loads(path.read_text()).items()}
            if row != expected[row["image_id"], row["codec"], row["point"]]:
                raise RuntimeError("Quality checkpoint differs from CSV: " + str(path))
        shutil.rmtree(quality)
    compact(REPORT / "matching", REPORT / "matching-audit.jsonl.gz")
    compact(REPORT / "timing", REPORT / "timing-audit.jsonl.gz", wrap_filename=True)
    files = sorted(p for p in REPORT.rglob("*") if p.is_file() and p.name != "SHA256SUMS")
    (REPORT / "SHA256SUMS").write_text("".join(
        hashlib.sha256(path.read_bytes()).hexdigest() + "  " + str(path.relative_to(REPORT)) + "\n" for path in files))
    print(f"Compacted audit records; {len(files)} evidence files checksummed.")


if __name__ == "__main__": main()

tools/verify_release_evidence.py

O verify_release_evidence.py confere as entradas publicadas e as matrizes brutas usando só a biblioteca padrão do Python.

O arquivo completo tem 115 linhas:

#!/usr/bin/env python3
"""Audit published inputs and complete raw matrices using only Python stdlib."""
from __future__ import annotations

import argparse
import csv
import gzip
import hashlib
import json
import math
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]


def sha(path):
    digest = hashlib.sha256()
    with Path(path).open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def require(condition, message):
    if not condition:
        raise RuntimeError(message)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--report", type=Path, default=ROOT / "benchmarks/release")
    args = parser.parse_args()
    report = args.report.resolve()
    listed = set()
    for line in (report / "SHA256SUMS").read_text().splitlines():
        digest, name = line.split("  ", 1)
        path = (report / name).resolve()
        require(path.is_relative_to(report), "Unsafe checksum path")
        require(name not in listed, "Duplicate checksum path")
        listed.add(name)
        require(sha(path) == digest, "Evidence digest mismatch: " + name)
    actual = {str(p.relative_to(report)) for p in report.rglob("*") if p.is_file() and p.name != "SHA256SUMS"}
    require(actual == listed, "Evidence files differ from checksum inventory")
    read = lambda name: json.loads((report / name).read_text())
    protocol, corpus = read("protocol.json"), read("corpus.json")
    require(sha(report / "corpus.json") == protocol["corpus_sha256"], "Corpus identity mismatch")
    images = corpus["images"]
    ids = {row["image_id"] for row in images}
    require(len(images) == len(ids) == protocol["count"], "Duplicate or missing images")
    require(len({row["ppm_sha256"] for row in images}) == len(images), "Duplicate image content")
    for row in images:
        require(sha(ROOT / "images" / row["filename"]) == row["ppm_sha256"], "Input image changed")
    for name, digest in protocol["source_sha256"].items():
        require(sha(ROOT / name) == digest, "Measured source changed: " + name)
    for name, digest in read("measurement-implementation.json")["current_tools_sha256"].items():
        require(sha(ROOT / name) == digest, "Reproduction tool changed: " + name)
    baseline = json.loads((ROOT / "benchmarks/baselines/provenance.json").read_text())
    require(sha(ROOT / "benchmarks/baselines/n148i-v1-source.tar.gz") == baseline["archive_sha256"], "V1 archive changed")
    with (report / "quality.csv").open() as handle:
        quality = list(csv.DictReader(handle))
    codecs = protocol["codecs"]
    keys = {(int(r["image_id"]), r["codec"], int(r["point"])) for r in quality}
    expected = {(image_id, codec, point) for image_id in ids for codec in codecs
                for point in range(1, len(protocol["qualities"]) + 1)}
    require(keys == expected and len(keys) == len(quality), "Quality matrix is incomplete or duplicated")
    require(sha(report / "quality.csv") == read("quality-status.json")["sha256"], "Quality completion digest changed")
    with gzip.open(report / "matching-audit.jsonl.gz", "rt") as handle:
        records = [json.loads(line) for line in handle]
    matching = {r["image_id"]: r for r in records}
    require(set(matching) == ids and len(records) == len(ids), "Matching matrix incomplete")
    groups = {(image_id, "nominal", level, codec) for image_id in ids
              for level in ("low", "medium", "high") for codec in codecs}
    for image_id, record in matching.items():
        groups.update((image_id, r["mode"], r["level"], r["codec"])
                      for r in record["selections"] if "codec" in r)
    with (report / "timing-samples.csv").open() as handle:
        samples = list(csv.DictReader(handle))
    timing = protocol["timing"]
    expected_samples = {key + (block, index) for key in groups for block in range(timing["blocks"])
                        for index in range(timing["repetitions_per_block"])}
    actual_samples = {(int(r["image_id"]), r["mode"], r["level"], r["codec"], int(r["block"]), int(r["index"])) for r in samples}
    require(actual_samples == expected_samples and len(samples) == len(expected_samples), "Timing matrix is incomplete or duplicated")
    for row in samples:
        require(all(math.isfinite(float(row[field])) and float(row[field]) > 0 for field in ("encode_ms", "decode_ms")), "Invalid timing")
    require(sha(report / "timing-samples.csv") == read("timing-status.json")["sha256"], "Timing completion digest changed")
    accepted, rejected, audit_samples = set(), 0, 0
    with gzip.open(report / "timing-audit.jsonl.gz", "rt") as handle:
        for line in handle:
            record = json.loads(line)["record"]
            if record["status"] != "accepted":
                rejected += 1
                continue
            key = (record["image_id"], record["block"])
            require(key not in accepted, "Duplicate accepted timing block")
            require(record["configuration"] == timing, "Timing audit configuration changed")
            group_audits = record["groups"]
            group_keys = {(g["mode"], g["level"]) for g in group_audits}
            expected_groups = {(mode, level) for image_id, mode, level, codec in groups if image_id == key[0]}
            require(group_keys == expected_groups and len(group_audits) == len(group_keys), "Missing/duplicate paired operating-point groups")
            for group in group_audits:
                require(group["status"] == "accepted" and not group["before"]["interference"]
                        and not group["after"]["interference"], "Noisy group was accepted")
                paired = [r for r in record["rows"] if (r["mode"], r["level"]) == (group["mode"], group["level"])]
                require(len(paired) == len(codecs) and {r["codec"] for r in paired} == set(codecs), "Partial codec pairing")
                require(all(not row[side]["interference"] for row in paired for side in ("before", "after")), "Noisy row was accepted")
            accepted.add(key)
            audit_samples += sum(len(r["samples"]) for r in record["rows"])
    require(accepted == {(i, b) for i in ids for b in range(timing["blocks"])}, "Timing audit has missing blocks")
    require(audit_samples == len(samples), "Timing audit/CSV sample counts differ")
    print(f"PASS: {len(listed)} evidence files, {len(ids)} unique inputs, {len(quality)} quality points, "
          f"{len(samples)} timing observations, {rejected} retained rejected blocks.")
    print("Digests and matrix integrity verified. This check does not rerun codecs or bootstrap calculations.")


if __name__ == "__main__": main()

tools/plot_release_benchmark.py

O plot_release_benchmark.py desenha a figura das curvas de taxa e distorção usada no README.

O arquivo completo tem 41 linhas:

#!/usr/bin/env python3
"""Export measured rate-distortion curves as a standalone README figure."""
import csv
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from release_benchmark import REPORT, CODECS, WORK

LABELS = {"n148i_v1": "N.148i V1", "n148i_v2": "N.148i V2", "jpeg_turbo": "JPEG Turbo",
          "webp_m4": "WebP M4", "webp_m6": "WebP M6", "webp_m6_historical": "WebP M6 (historical)",
          "jxl_e3": "JPEG XL E3", "jxl_e7": "JPEG XL E7"}
COLORS = ["#999999", "#b32067", "#bd7620", "#3c9cc4", "#163e8c", "#8495ac", "#75a541", "#247650"]


def main():
    rows = list(csv.DictReader((REPORT / "aggregate-curves.csv").open()))
    plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 10, "svg.fonttype": "none"})
    fig, axes = plt.subplots(1, 3, figsize=(14, 4.7))
    for ax, metric, title in zip(axes, ("psnr_y_db", "ssim", "butteraugli"),
                               ("PSNR Y · higher is better", "SSIM · higher is better", "Butteraugli · lower is better")):
        for codec, color in zip(CODECS, COLORS):
            selected = sorted([r for r in rows if r["codec"] == codec and r["metric"] == metric], key=lambda r: int(r["point"]))
            x = [float(r["bpp"]) for r in selected]
            y = [float(r["quality_axis"]) * (-1 if metric == "butteraugli" else 1) for r in selected]
            ax.plot(x, y, color=color, marker="o", markersize=3, linewidth=2.8 if codec == "n148i_v2" else 1.3,
                    linestyle="--" if codec == "webp_m6_historical" else "-", label=LABELS[codec])
        ax.set_title(title, loc="left", fontsize=11, fontweight="bold")
        ax.set_xlabel("Bits per pixel")
        ax.grid(alpha=.18)
        ax.spines[["top", "right"]].set_visible(False)
    handles, labels = axes[0].get_legend_handles_labels()
    fig.legend(handles, labels, loc="lower center", ncol=4, frameon=False, bbox_to_anchor=(.5, -.02))
    fig.suptitle("N.148i V2 · 130 development images", x=.04, ha="left", fontsize=16, fontweight="bold")
    fig.tight_layout(rect=[0, .16, 1, .92])
    fig.savefig(REPORT / "rate-distortion.svg", bbox_inches="tight", metadata={"Date": None})
    WORK.mkdir(parents=True, exist_ok=True)
    fig.savefig(WORK / "rate-distortion-preview.png", bbox_inches="tight", dpi=140)
    print(REPORT / "rate-distortion.svg")


if __name__ == "__main__": main()

tools/render_release_readme.py

O render_release_readme.py gera as tabelas do README direto das análises, sem nenhum número digitado à mão.

O arquivo completo tem 156 linhas:

#!/usr/bin/env python3
"""Render README tables directly from the completed release analyses."""
from __future__ import annotations

import argparse
import json
from pathlib import Path

from release_benchmark import ROOT, REPORT, CODECS
from analyze_release_benchmark import METRICS

LABELS = {
    "n148i_v1": "N.148i V1", "n148i_v2": "**N.148i V2**",
    "jpeg_turbo": "JPEG Turbo 2.1.5", "webp_m4": "WebP 1.6.0 M4",
    "webp_m6": "WebP 1.6.0 M6", "webp_m6_historical": "WebP 1.3.2 M6",
    "jxl_e3": "JPEG XL 0.12.0 E3", "jxl_e7": "JPEG XL 0.12.0 E7",
}
METRIC_LABELS = {
    "psnr_y_db": "PSNR Y", "psnr_rgb_db": "PSNR RGB", "ssim": "SSIM",
    "ms_ssim": "MS-SSIM", "ssimulacra2": "SSIMULACRA2",
    "butteraugli": "Butteraugli", "psnr_chroma_db": "PSNR chroma",
}


def percentage(value):
    return "N/A" if value is None else f"{value:+.2f}%"


def confidence(values):
    return "N/A" if values is None else f"[{values[0]:+.2f}, {values[1]:+.2f}]%"


def load(name):
    return json.loads((REPORT / name).read_text())


def render():
    for phase in ("quality", "matching", "timing"):
        if load(f"{phase}-status.json")["status"] != "complete":
            raise RuntimeError(f"Incomplete {phase}; refusing to publish partial results")
    quality = load("quality-analysis.json")["comparisons"]
    timing = load("timing-analysis.json")["comparisons"]
    common = load("common-size-timing.json")
    curves = REPORT / "rate-distortion.svg"
    if not curves.exists():
        raise RuntimeError("Generate the rate-distortion figure first")
    lookup = {(x["candidate"], x["anchor"], x["metric"]): x for x in quality}
    v2 = [lookup["n148i_v2", "webp_m6", metric] for metric in METRICS]
    evolution = [lookup["n148i_v2", "n148i_v1", metric] for metric in METRICS]
    wins = sum(x["conclusion"] == "lower_rate" for x in v2)
    losses = sum(x["conclusion"] == "higher_rate" for x in v2)
    unresolved = len(v2) - wins - losses
    lines = ["### From the first public V1 to V2", ""]
    if all(item["conclusion"] == "lower_rate" for item in evolution):
        savings = [-item["bd_rate_pct"] for item in evolution]
        lines += [f"V2 achieves **{min(savings):.2f}%–{max(savings):.2f}% BD-rate savings** over the",
                  "original V1 across the seven quality measures on this corpus. All seven",
                  "family-adjusted intervals favor V2. These are direct V2/V1 comparisons",
                  "over shared quality ranges.", ""]
    lines += ["<details>", "<summary>Direct V2 versus V1 results</summary>", "",
              "| Metric | V2 BD-rate relative to V1 | Family 95% interval |",
              "|---|---:|---:|"]
    for item in evolution:
        lines.append(f"| {METRIC_LABELS[item['metric']]} | {percentage(item['bd_rate_pct'])} | "
                     f"{confidence(item['familywise95_pct'])} |")
    lines += ["", "</details>", "",
        "### Compression at equivalent measured quality", "",
        "**5,200 measured points · 130 images · 8 profiles · 7 metrics.**", "",
        "BD-rate relative to **WebP 1.6.0 M6**. Negative means fewer bits over",
        "the overlapping quality range; positive means more bits. These are",
        "aggregate curves, not a promise that every image improves.", "",
        "| Codec | PSNR Y | PSNR RGB | SSIM | MS-SSIM | SSIMULACRA2 | Butteraugli | Chroma |",
        "|---|---:|---:|---:|---:|---:|---:|---:|",
    ]
    for codec in CODECS:
        cells = ["0.00%" if codec == "webp_m6" else percentage(lookup[codec, "webp_m6", metric]["bd_rate_pct"])
                 for metric in METRICS]
        lines.append("| " + LABELS[codec] + " | " + " | ".join(cells) + " |")
    lines += ["", "![Measured rate-distortion curves](benchmarks/release/rate-distortion.svg)", "",
              "### How certain are V2's differences from WebP M6?", "",
              "10,000 paired image bootstrap replicates, stratified by content.",
              "The family intervals account for the seven quality comparisons.",
              "An interval crossing zero does not establish a gain or a loss.", "",
              "| Metric | V2 BD-rate | 95% interval | Family 95% interval | Interior-point omission range | Images won / tied / lost |",
              "|---|---:|---:|---:|---:|---:|"]
    for item in v2:
        sensitivity = [x["bd_rate_pct"] for x in item["interior_point_omission"] if x["bd_rate_pct"] is not None]
        span = confidence([min(sensitivity), max(sensitivity)]) if len(sensitivity) == 3 else "Incomplete overlap"
        lines.append(f"| {METRIC_LABELS[item['metric']]} | {percentage(item['bd_rate_pct'])} | "
                     f"{confidence(item['ci95_pct'])} | {confidence(item['familywise95_pct'])} | "
                     f"{span} | "
                     f"{item['images_won']} / {item['images_tied']} / {item['images_lost']} "
                     f"({item['images_valid']}/130 valid) |")
    lines += ["", f"For this development sample, the family intervals support **{wins}/7 lower-rate",
              f"results, {losses}/7 higher-rate results and {unresolved}/7 inconclusive results** against",
              "this WebP M6 configuration. Per-image wins use the point estimates;",
              "they are not separate significance tests. Sampling intervals do not",
              "include codec tuning bias or five-point interpolation error. The omission",
              "range recomputes BD-rate after dropping each interior point in turn; it",
              "is a sensitivity diagnostic, not a confidence interval. The",
              "[full quality analysis](benchmarks/release/quality-analysis.json) records",
              "missing overlaps and sensitivity to omitting each interior curve point.", "",
              "### Speed at comparable file sizes", "",
              "One logical CPU, one codec thread; 2 blocks × 7 measured repetitions.",
              f"The same **{common['count']}/130 images** appear in every row below: all eight",
              "profiles meet the medium size target and differ from WebP M6's actual",
              "file size by at most 2% per image. This is a conditional subset.", "",
              "Times are averages of per-image medians; negative time differences",
              "mean faster than WebP 1.6.0 M6. Brackets show 95% paired intervals.", "",
              "| Codec | Encode ms/image | Encode Δ [95% interval] | Decode ms/image | Decode Δ [95% interval] |",
              "|---|---:|---:|---:|---:|"]
    if common["count"]:
        for item in common["codecs"]:
            enc, dec = item["encode_ms"], item["decode_ms"]
            lines.append(f"| {LABELS[item['codec']]} | {enc['mean_ms']:.3f} | "
                         f"{percentage(enc['time_difference_pct'])} {confidence(enc['ci95_pct'])} | "
                         f"{dec['mean_ms']:.3f} | {percentage(dec['time_difference_pct'])} {confidence(dec['ci95_pct'])} |")
    else:
        lines.append("| No common matched subset | — | — | — | — |")
    lines += ["", "[Common-subset details](benchmarks/release/common-size-timing.json) include",
              "MPix/s, image identifiers, bytes and intervals adjusted for 14 comparisons.", "",
              "#### V2 versus WebP M6 across operating ranges", "",
              "Each row uses all eligible pairs for that target, with both target and",
              "actual pairwise tolerances enforced. Size tolerance is 2%; SSIM tolerance",
              "is 0.0005. These intervals account for six tests per matching mode.", "",
              "| Matched by | Level | Images | Encode Δ [family 95% interval] | Decode Δ [family 95% interval] |",
              "|---|---|---:|---:|---:|"]
    for mode in ("bytes", "ssim"):
        for level in ("low", "medium", "high"):
            entries = {x["operation"]: x for x in timing if x["anchor"] == "webp_m6" and
                       x["mode"] == mode and x["level"] == level}
            enc, dec = entries["encode_ms"], entries["decode_ms"]
            cells = []
            for entry in (enc, dec):
                cells.append(percentage(entry.get("time_difference_pct")) + " " + confidence(entry.get("familywise95_pct")))
            lines.append(f"| {'File size' if mode == 'bytes' else 'SSIM'} | {level.title()} | "
                         f"{enc['paired_images']}/130 | " + " | ".join(cells) + " |")
    lines += ["", "Nominal-quality timings, every external reference, exclusions and raw",
              "observations are retained in the [timing report](benchmarks/release/timing-analysis.json)",
              "and [raw samples](benchmarks/release/timing-samples.csv). Measurements cover",
              "this CPU only, with clock frequency managed by the operating system."]
    return "\n".join(lines) + "\n"


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--readme", type=Path, default=ROOT / "README.md")
    args = parser.parse_args()
    before, rest = args.readme.read_text().split("<!-- RELEASE_RESULTS_BEGIN -->", 1)
    _, after = rest.split("<!-- RELEASE_RESULTS_END -->", 1)
    args.readme.write_text(before + "<!-- RELEASE_RESULTS_BEGIN -->\n" + render() +
                           "<!-- RELEASE_RESULTS_END -->" + after)
    print(args.readme)


if __name__ == "__main__": main()

tools/validate_release.py

O validate_release.py roda os 29 portões de validação da entrega, como a ABI, a instalação, os programas consumidores e os sanitizadores.

O arquivo completo tem 431 linhas:

#!/usr/bin/env python3
"""Run the N.148i release, ABI, installation, and consumer validation gates.

Copyright (c) Micilini Roll. Licensed under the MIT License.
"""

from __future__ import annotations

import argparse
import json
import os
import re
import shlex
import shutil
import subprocess
import tempfile
from pathlib import Path
from typing import Any


PUBLIC_SYMBOLS = {
    "n148i_decode_memory",
    "n148i_encode_memory",
    "n148i_encode_options_init",
    "n148i_format_version",
    "n148i_free_buffer",
    "n148i_free_image",
    "n148i_library_version",
    "n148i_read_header",
    "n148i_result_string",
    "n148i_simd_force",
    "n148i_simd_level",
    "n148i_simd_name",
}


CONSUMER_SOURCE = r'''#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <n148i.h>

int main(void) {
    enum { WIDTH = 16, HEIGHT = 16 };
    uint8_t pixels[WIDTH * HEIGHT * 3];
    for (size_t index = 0; index < sizeof(pixels); index++)
        pixels[index] = (uint8_t) (index * 37u + 11u);
    n148i_image_t source = {pixels, WIDTH, HEIGHT, WIDTH * 3};
    n148i_encode_options_t options;
    n148i_encode_options_init(&options);
    uint8_t *encoded = NULL;
    size_t encoded_size = 0;
    n148i_image_t decoded = {0};
    if (n148i_encode_memory(&source, &options, &encoded, &encoded_size) !=
            N148I_OK || encoded_size == 0 ||
        n148i_decode_memory(encoded, encoded_size, &decoded) != N148I_OK ||
        decoded.width != WIDTH || decoded.height != HEIGHT) {
        n148i_free_image(&decoded);
        n148i_free_buffer(encoded);
        return EXIT_FAILURE;
    }
    printf("%s format=%u bytes=%zu\n", n148i_library_version(),
           n148i_format_version(), encoded_size);
    n148i_free_image(&decoded);
    n148i_free_buffer(encoded);
    return EXIT_SUCCESS;
}
'''


FEATURE_VALUE_ASSERTIONS = r'''#include <stdint.h>
#include <n148i.h>

_Static_assert(N148I_FEATURE_RANS == (UINT32_C(1) << 0), "RANS bit");
_Static_assert(N148I_FEATURE_CONTEXT == (UINT32_C(1) << 1), "context bit");
_Static_assert(N148I_FEATURE_INTRA == (UINT32_C(1) << 2), "intra bit");
_Static_assert(N148I_FEATURE_PERCEPTUAL_COLOR == (UINT32_C(1) << 3), "color bit");
_Static_assert(N148I_FEATURE_ADAPTIVE_QUANT == (UINT32_C(1) << 4), "quant bit");
_Static_assert(N148I_FEATURE_VARIABLE_TRANSFORM == (UINT32_C(1) << 5), "transform bit");
_Static_assert(N148I_FEATURE_RDO == (UINT32_C(1) << 6), "RDO bit");
_Static_assert(N148I_FEATURE_LOOP_FILTER == (UINT32_C(1) << 7), "filter bit");
_Static_assert(N148I_FEATURE_DIRECTIONAL_INTRA == (UINT32_C(1) << 8), "directional bit");
_Static_assert(N148I_FEATURE_INTRA_4X4 == (UINT32_C(1) << 9), "4x4 bit");
_Static_assert(N148I_FEATURE_CONTEXTUAL_RDO == (UINT32_C(1) << 10), "contextual RDO bit");
_Static_assert(N148I_FEATURE_PERCEPTUAL_TRELLIS == (UINT32_C(1) << 11), "trellis bit");
_Static_assert(N148I_FEATURE_RECONSTRUCTION_AWARE_CHROMA == (UINT32_C(1) << 12), "chroma reconstruction bit");
_Static_assert(N148I_FEATURE_JOINT_CHROMA_INTRA == (UINT32_C(1) << 13), "joint chroma bit");
_Static_assert(N148I_FEATURE_CALIBRATED_CHROMA_QUANT == (UINT32_C(1) << 14), "chroma quant bit");
_Static_assert(N148I_FEATURE_SEGMENTATION == (UINT32_C(1) << 15), "segmentation bit");
_Static_assert(N148I_FEATURE_ADAPTIVE_LOOP_FILTER == (UINT32_C(1) << 16), "adaptive filter bit");
_Static_assert(N148I_FEATURE_CALIBRATED_LUMA_QUANT == (UINT32_C(1) << 17), "luma quant bit");
_Static_assert(N148I_FEATURE_LUMA_TRANSFORM_16X16 == (UINT32_C(1) << 18), "16x16 bit");
_Static_assert(N148I_FEATURE_QUANT_ADAPTIVE_LUMA_FILTER == (UINT32_C(1) << 19), "luma filter bit");
_Static_assert(N148I_FEATURE_FILTERED_INTRA_REFERENCES == (UINT32_C(1) << 20), "reference filter bit");
_Static_assert(N148I_FEATURE_PLANAR_INTRA_PREDICTION == (UINT32_C(1) << 21), "planar bit");
_Static_assert(N148I_FEATURE_STRUCTURAL_RDO == (UINT32_C(1) << 22), "structural RDO bit");
_Static_assert(N148I_FEATURE_QUALITY_LAMBDA == (UINT32_C(1) << 23), "lambda bit");
_Static_assert(N148I_FEATURE_LUMA_TRANSFORM_32X32 == (UINT32_C(1) << 24), "32x32 bit");
_Static_assert(N148I_FEATURE_SECOND_ORDER_DC == (UINT32_C(1) << 25), "second-order DC bit");
_Static_assert(N148I_FEATURE_FINE_INTRA_DIRECTIONS == (UINT32_C(1) << 26), "fine direction bit");
_Static_assert(N148I_FEATURE_ADAPTIVE_ENTROPY == (UINT32_C(1) << 27), "adaptive entropy bit");
_Static_assert(N148I_FEATURE_RICH_COEFFICIENT_CONTEXTS == (UINT32_C(1) << 28), "rich context bit");
_Static_assert(N148I_FEATURE_MULTIPLE_INTRA_REFERENCES == (UINT32_C(1) << 29), "multiple reference bit");
_Static_assert(N148I_FEATURE_DIRECTIONAL_SCAN == (UINT32_C(1) << 30), "scan bit");
_Static_assert(N148I_FEATURE_DIRECTIONAL_TRANSFORM == (UINT32_C(1) << 31), "directional transform bit");
_Static_assert(N148I_FEATURE_ALL == UINT32_C(0x000000ff), "base feature mask");
_Static_assert(N148I_FORMAT_2_DEFAULT_FEATURES == UINT32_C(0x000000c7), "format 2 default");
_Static_assert(N148I_FORMAT_2_FEATURE_MASK == UINT32_C(0x000000ff), "format 2 mask");
_Static_assert(N148I_PROFILE_DIRECTIONAL_INTRA == UINT32_C(0x000003c7), "directional profile");
_Static_assert(N148I_PROFILE_CONTEXTUAL_RDO == UINT32_C(0x000007c7), "contextual profile");
_Static_assert(N148I_PROFILE_PERCEPTUAL_TRELLIS == UINT32_C(0x00000fc7), "trellis profile");
_Static_assert(N148I_FORMAT_3_DEFAULT_FEATURES == UINT32_C(0x000007c7), "format 3 default");
_Static_assert(N148I_FORMAT_3_FEATURE_MASK == UINT32_C(0x00000fc7), "format 3 mask");
_Static_assert(N148I_PROFILE_RECONSTRUCTION_AWARE_CHROMA == UINT32_C(0x000017c7), "chroma reconstruction profile");
_Static_assert(N148I_PROFILE_JOINT_CHROMA_INTRA == UINT32_C(0x000037c7), "joint chroma profile");
_Static_assert(N148I_PROFILE_CALIBRATED_CHROMA_QUANT == UINT32_C(0x000057c7), "chroma quant profile");
_Static_assert(N148I_PROFILE_CHROMA_SEGMENTATION == UINT32_C(0x0000d7c7), "segmentation profile");
_Static_assert(N148I_PROFILE_ADAPTIVE_CHROMA_FILTER == UINT32_C(0x0001d7c7), "adaptive chroma profile");
_Static_assert(N148I_FORMAT_4_DEFAULT_FEATURES == UINT32_C(0x000057c7), "format 4 default");
_Static_assert(N148I_FORMAT_4_FEATURE_MASK == UINT32_C(0x0001f7c7), "format 4 mask");
_Static_assert(N148I_PROFILE_CALIBRATED_LUMA_QUANT == UINT32_C(0x000257c7), "luma quant profile");
_Static_assert(N148I_PROFILE_VARIABLE_LUMA_TRANSFORM == UINT32_C(0x000657c7), "variable luma profile");
_Static_assert(N148I_PROFILE_PERCEPTUAL_LUMA_TRELLIS == UINT32_C(0x00065fc7), "luma trellis profile");
_Static_assert(N148I_PROFILE_QUANT_ADAPTIVE_LUMA_FILTER == UINT32_C(0x000e57c7), "luma filter profile");
_Static_assert(N148I_FORMAT_5_DEFAULT_FEATURES == UINT32_C(0x000657c7), "format 5 default");
_Static_assert(N148I_FORMAT_5_FEATURE_MASK == UINT32_C(0x000ff7c7), "format 5 mask");
_Static_assert(N148I_PROFILE_LUMA_TRANSFORM_32X32 == UINT32_C(0x010657c7), "32x32 profile");
_Static_assert(N148I_PROFILE_FILTERED_INTRA_REFERENCES == UINT32_C(0x001657c7), "filtered references profile");
_Static_assert(N148I_PROFILE_PLANAR_INTRA_PREDICTION == UINT32_C(0x002657c7), "planar profile");
_Static_assert(N148I_PROFILE_COMBINED_INTRA_PREDICTION == UINT32_C(0x003657c7), "combined prediction profile");
_Static_assert(N148I_PROFILE_STRUCTURAL_RDO == UINT32_C(0x006657c7), "structural profile");
_Static_assert(N148I_PROFILE_QUALITY_LAMBDA == UINT32_C(0x00a657c7), "lambda profile");
_Static_assert(N148I_FORMAT_6_DEFAULT_FEATURES == UINT32_C(0x002657c7), "format 6 default");
_Static_assert(N148I_FORMAT_6_FEATURE_MASK == UINT32_C(0x07fff7c7), "format 6 mask");
_Static_assert(N148I_PROFILE_ADAPTIVE_ENTROPY == UINT32_C(0x082657c7), "adaptive entropy profile");
_Static_assert(N148I_PROFILE_RICH_COEFFICIENT_CONTEXTS == UINT32_C(0x182657c7), "rich context profile");
_Static_assert(N148I_PROFILE_RATE_CALIBRATED_SEARCH == UINT32_C(0x18a657c7), "calibrated search profile");
_Static_assert(N148I_PROFILE_SPECTRAL_LUMA_QUANT == UINT32_C(0x18a657cf), "spectral luma profile");
_Static_assert(N148I_FORMAT_7_REFINED_SPECTRAL_LUMA_QUANT == UINT32_C(0x00000010), "refined spectral bit");
_Static_assert(N148I_PROFILE_REFINED_SPECTRAL_LUMA_QUANT == UINT32_C(0x18a657df), "refined spectral profile");
_Static_assert(N148I_FORMAT_7_STRUCTURAL_LUMA_QUANT == UINT32_C(0x00000020), "structural luma bit");
_Static_assert(N148I_PROFILE_STRUCTURAL_LUMA_QUANT == UINT32_C(0x18a6d7ff), "structural luma profile");
_Static_assert(N148I_FORMAT_7_BALANCED_RECONSTRUCTION == UINT32_C(0x80000000), "balanced reconstruction bit");
_Static_assert(N148I_PROFILE_BALANCED_RECONSTRUCTION == UINT32_C(0x98a6d7ff), "balanced reconstruction profile");
_Static_assert(N148I_FORMAT_7_DETAIL_RECONSTRUCTION == UINT32_C(0x40000000), "detail reconstruction bit");
_Static_assert(N148I_PROFILE_DETAIL_RECONSTRUCTION == UINT32_C(0xd8a6d7ff), "detail reconstruction profile");
_Static_assert(N148I_PROFILE_MULTIPLE_INTRA_REFERENCES == UINT32_C(0x382657c7), "multiple reference profile");
_Static_assert(N148I_PROFILE_DIRECTIONAL_SCAN == UINT32_C(0x782657c7), "scan profile");
_Static_assert(N148I_PROFILE_DIRECTIONAL_TRANSFORM == UINT32_C(0xf82657c7), "directional transform profile");
_Static_assert(N148I_FORMAT_7_DEFAULT_FEATURES == UINT32_C(0x18a657c7), "format 7 default");
_Static_assert((N148I_FORMAT_7_DEFAULT_FEATURES & N148I_FEATURE_PERCEPTUAL_TRELLIS) == 0, "format 7 default excludes trellis");
_Static_assert(N148I_FORMAT_7_FEATURE_MASK == UINT32_C(0xffffffff), "format 7 mask");
_Static_assert(N148I_FORMAT_7_FULL_TRELLIS_FEATURES == UINT32_C(0x18a65fc7), "format 7 full trellis");

int main(void) { return 0; }
'''


def parse_args() -> argparse.Namespace:
    root = Path(__file__).resolve().parents[1]
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--root", type=Path, default=root)
    parser.add_argument(
        "--output-dir", type=Path, default=root / "benchmarks/release",
    )
    parser.add_argument("--jobs", type=int, default=os.cpu_count() or 1)
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    root = args.root.resolve()
    header = (root / "include/n148i.h").read_text(encoding="utf-8")
    version_match = re.search(
        r'^#define N148I_VERSION_STRING "([^"]+)"$', header, re.MULTILINE)
    if not version_match:
        raise SystemExit("N148I_VERSION_STRING is missing from the public header")
    library_version = ".".join(re.search(r"^#define N148I_VERSION_" + part + r" (\d+)$", header, re.MULTILINE).group(1) for part in ("MAJOR", "MINOR", "PATCH"))
    output_dir = args.output_dir.resolve()
    work = root / ".build" / "release-validation"
    alias_root = Path(tempfile.mkdtemp(prefix="n148-release-prefix-"))
    expected_parent = (root / ".build").resolve()
    if work.resolve().parent != expected_parent:
        raise SystemExit(f"unsafe work directory: {work}")
    shutil.rmtree(work, ignore_errors=True)
    work.mkdir(parents=True)
    output_dir.mkdir(parents=True, exist_ok=True)

    transcript: list[str] = []
    results: dict[str, dict[str, Any]] = {}

    def run(
        name: str, command: list[str], *, cwd: Path = root,
        environment: dict[str, str] | None = None, timeout: int = 1800,
    ) -> subprocess.CompletedProcess[str]:
        env = {**os.environ, "LC_ALL": "C"}
        if environment:
            env.update(environment)
        transcript.append(f"$ {' '.join(shlex.quote(part) for part in command)}\n")
        completed = subprocess.run(
            command, cwd=cwd, env=env, check=False,
            stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
            encoding="utf-8", errors="replace", timeout=timeout,
        )
        transcript.extend((completed.stdout, completed.stderr, "\n"))
        results[name] = {
            "argv": command,
            "cwd": str(cwd),
            "exit_code": completed.returncode,
            "passed": completed.returncode == 0,
        }
        if completed.returncode != 0:
            raise RuntimeError(f"{name} failed with exit code {completed.returncode}")
        return completed

    failure: str | None = None
    try:
        jobs = str(args.jobs)
        run("naming_audit", ["python3", "tools/audit_naming.py"])
        run("make_normal", ["make", f"-j{jobs}", "compare", "validate", "libraries"])
        sentinel = run(
            "format_1_sentinel",
            [str(root / "compare"), "images/example.ppm", "50", "20"],
        )
        match = re.search(r"N148i\s+enc.*?\s+(\d+) B\s+PSNR", sentinel.stdout)
        sentinel_bytes = int(match.group(1)) if match else None
        if sentinel_bytes != 2290:
            raise RuntimeError(f"format 1 sentinel is {sentinel_bytes}, expected 2290")
        results["format_1_sentinel"]["bytes"] = sentinel_bytes

        validation = run("validation_suite", [str(root / "validate")], timeout=1800)
        if (
            "validation PASS (0 failures)" not in validation.stderr or
            ",FAIL" in validation.stdout
        ):
            raise RuntimeError("validation suite did not report zero failures")

        run(
            "make_without_threads",
            ["make", f"-j{jobs}", "NOTHREADS=1", "-B", "validate"],
        )
        no_threads = run(
            "validation_without_threads", [str(root / "validate")], timeout=1800,
        )
        if (
            "validation PASS (0 failures)" not in no_threads.stderr or
            ",FAIL" in no_threads.stdout
        ):
            raise RuntimeError("thread-free validation did not report zero failures")

        cmake_build = work / "cmake"
        run("cmake_configure", [
            "cmake", "-S", str(root), "-B", str(cmake_build),
            "-DCMAKE_BUILD_TYPE=Release",
        ])
        run("cmake_build", [
            "cmake", "--build", str(cmake_build), "--parallel", jobs,
        ])
        run("ctest", [
            "ctest", "--test-dir", str(cmake_build), "--output-on-failure",
        ], timeout=1800)

        sanitizer_build = work / "sanitizers"
        sanitizer_flags = "-fsanitize=address,undefined -fno-omit-frame-pointer"
        run("sanitizer_configure", [
            "cmake", "-S", str(root), "-B", str(sanitizer_build),
            "-DCMAKE_BUILD_TYPE=RelWithDebInfo",
            f"-DCMAKE_C_FLAGS={sanitizer_flags}",
            f"-DCMAKE_EXE_LINKER_FLAGS={sanitizer_flags}",
            f"-DCMAKE_SHARED_LINKER_FLAGS={sanitizer_flags}",
        ])
        run("sanitizer_build", [
            "cmake", "--build", str(sanitizer_build), "--parallel", jobs,
        ])
        sanitizer = run(
            "asan_ubsan_lsan", [str(sanitizer_build / "validate")],
            environment={
                "ASAN_OPTIONS": "detect_leaks=1:halt_on_error=1:strict_string_checks=1",
                "UBSAN_OPTIONS": "halt_on_error=1:print_stacktrace=1",
            }, timeout=3600,
        )
        if (
            "validation PASS (0 failures)" not in sanitizer.stderr or
            ",FAIL" in sanitizer.stdout
        ):
            raise RuntimeError("sanitizer validation did not report zero failures")

        # Restore the normal root artifacts after the thread-free Make build.
        run("make_normal_restore", [
            "make", f"-j{jobs}", "-B", "compare", "validate", "libraries",
        ])

        shared = root / f"libn148i.so.{library_version}"
        nm = run("dynamic_symbols", ["nm", "-D", "--defined-only", str(shared)])
        defined = {
            line.split()[-1].split("@", 1)[0]
            for line in nm.stdout.splitlines() if line.split()
        }
        exported = {name for name in defined if name.startswith("n148i_")}
        unexpected = defined - PUBLIC_SYMBOLS - {"N148I_2.0"}
        if exported != PUBLIC_SYMBOLS or unexpected:
            raise RuntimeError(
                f"exported symbols differ: missing={sorted(PUBLIC_SYMBOLS - exported)}, "
                f"extra={sorted((exported - PUBLIC_SYMBOLS) | unexpected)}"
            )
        results["dynamic_symbols"]["exported_symbols"] = sorted(exported)
        results["dynamic_symbols"]["exported_symbol_count"] = len(exported)

        dynamic = run("soname", ["readelf", "-d", str(shared)])
        expected_soname = f"libn148i.so.{library_version.split('.')[0]}"
        if f"Library soname: [{expected_soname}]" not in dynamic.stdout:
            raise RuntimeError(f"shared library SONAME differs from {expected_soname}")
        version_info = run("symbol_version_node", [
            "readelf", "--version-info", str(shared),
        ])
        if "N148I_2.0" not in version_info.stdout:
            raise RuntimeError("N148I_2.0 symbol version node is absent")

        install = work / "install"
        run("cmake_install", [
            "cmake", "--install", str(cmake_build), "--prefix", str(install),
        ])
        # pkgconf escapes each byte of a non-ASCII prefix independently under
        # this workspace path, yielding output that is neither valid UTF-8 nor
        # usable compiler flags. Exercise the installed tree through a stable
        # ASCII-only alias; the files and metadata remain the actual install.
        install_alias = alias_root / "install"
        install_alias.symlink_to(install, target_is_directory=True)
        pkg_env = {
            "PKG_CONFIG_PATH": str(install_alias / "lib/pkgconfig"),
            "LD_LIBRARY_PATH": str(install_alias / "lib"),
        }
        pkg = run("pkg_config", ["pkg-config", "--cflags", "--libs", "n148i"],
                  environment=pkg_env)

        consumer_dir = work / "consumers"
        consumer_dir.mkdir()
        consumer_source = consumer_dir / "consumer.c"
        consumer_source.write_text(CONSUMER_SOURCE, encoding="utf-8")
        pkg_binary = consumer_dir / "consumer-pkg-config"
        run("pkg_config_consumer_build", [
            "cc", str(consumer_source), *shlex.split(pkg.stdout), "-o", str(pkg_binary),
        ], environment=pkg_env)
        run("pkg_config_consumer_run", [str(pkg_binary)], environment=pkg_env)

        cmake_consumer = consumer_dir / "cmake"
        cmake_consumer.mkdir()
        shutil.copyfile(consumer_source, cmake_consumer / "consumer.c")
        (cmake_consumer / "CMakeLists.txt").write_text(
            "cmake_minimum_required(VERSION 3.16)\n"
            "project(n148i_external_consumer LANGUAGES C)\n"
            "find_package(n148i 2 CONFIG REQUIRED)\n"
            "add_executable(consumer consumer.c)\n"
            "target_link_libraries(consumer PRIVATE n148i::n148i)\n",
            encoding="utf-8",
        )
        cmake_consumer_build = consumer_dir / "cmake-build"
        run("cmake_consumer_configure", [
            "cmake", "-S", str(cmake_consumer), "-B", str(cmake_consumer_build),
            f"-DCMAKE_PREFIX_PATH={install_alias}",
        ])
        run("cmake_consumer_build", [
            "cmake", "--build", str(cmake_consumer_build), "--parallel", jobs,
        ])
        run(
            "cmake_consumer_run", [str(cmake_consumer_build / "consumer")],
            environment=pkg_env,
        )

        static_binary = consumer_dir / "consumer-static"
        run("static_consumer_build", [
            "cc", "-DN148I_STATIC_DEFINE", f"-I{install_alias / 'include'}",
            str(consumer_source), str(install_alias / "lib/static/libn148i.a"),
            "-pthread", "-lm", "-o", str(static_binary),
        ])
        run("static_consumer_run", [str(static_binary)])

        feature_source = consumer_dir / "feature-values.c"
        feature_source.write_text(FEATURE_VALUE_ASSERTIONS, encoding="utf-8")
        run("feature_mask_values", [
            "cc", "-std=c11", "-Wall", "-Wextra", "-Werror",
            f"-I{install_alias / 'include'}", str(feature_source),
            "-o", str(consumer_dir / "feature-values"),
        ])

        cpp_source = consumer_dir / "header.cpp"
        cpp_source.write_text(
            "#include <n148i.h>\n"
            "static_assert(N148I_FORMAT_VERSION == 7, \"format version\");\n"
            "int main() { return 0; }\n",
            encoding="utf-8",
        )
        run("cpp_header", [
            "c++", "-std=c++17", "-Wall", "-Wextra", "-Werror",
            f"-I{install_alias / 'include'}", "-c", str(cpp_source),
            "-o", str(consumer_dir / "header.o"),
        ])

        readme_binary = consumer_dir / "readme-example"
        run("readme_example_build", [
            "cc", str(root / "examples/memory_roundtrip.c"),
            *shlex.split(pkg.stdout), "-o", str(readme_binary),
        ], environment=pkg_env)
        run("readme_example_run", [str(readme_binary)], environment=pkg_env)
    except (OSError, RuntimeError, subprocess.TimeoutExpired) as error:
        failure = str(error)
        transcript.append(f"VALIDATION FAILURE: {failure}\n")

    shutil.rmtree(alias_root, ignore_errors=True)

    summary = {
        "status": "pass" if failure is None else "fail",
        "failure": failure,
        "public_symbols_expected": sorted(PUBLIC_SYMBOLS),
        "gates": results,
    }
    rendered_transcript = "".join(transcript)
    normalized_transcript = "\n".join(
        line.rstrip() for line in rendered_transcript.splitlines()
    ) + "\n"
    (output_dir / "validation.log").write_text(
        normalized_transcript, encoding="utf-8",
    )
    (output_dir / "validation-summary.json").write_text(
        json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8",
    )
    print(json.dumps(summary, ensure_ascii=False, indent=2))
    return 0 if failure is None else 1


if __name__ == "__main__":
    raise SystemExit(main())

tools/audit_naming.py

O audit_naming.py recusa nomes de rodadas de desenvolvimento no código ativo, deixando passar só os nomes que fazem parte do formato, como N148I_FORMAT_VERSION_7.

O arquivo completo tem 65 linhas:

#!/usr/bin/env python3
"""Reject implementation-round nomenclature in the active N.148i tree.

Normative names such as N148I_FORMAT_VERSION_7 are intentionally accepted:
their number determines the on-stream syntax. Historical documents and the
published benchmark archives are outside this implementation audit.

Copyright (c) Micilini Roll. Licensed under the MIT License.
"""

from __future__ import annotations

import re
from pathlib import Path


OLD_PATH = re.compile(r"(?:^|/)v[1-7]_(?:codec|intra)\.[ch]$")
OLD_CONTENT = (
    re.compile(r"\bN148I?_V[1-7](?:_|\b)"),
    re.compile(r"\bn148_v[1-7](?:_|\b)"),
    re.compile(r"\bN148V[1-7][A-Za-z0-9_]*"),
    re.compile(r"\bV[1-7]_[A-Za-z0-9_]"),
    re.compile(r"\bv[1-7]_[A-Za-z0-9_]"),
    re.compile(r"\bv[3-7]\b", re.IGNORECASE),
    re.compile(r"\b7\.[01]\.\d+\b"),
    re.compile(r"\b(?:phase|stage)[ _-]?[0-9]+\b", re.IGNORECASE),
)


def audited_paths(root: Path) -> list[Path]:
    paths: list[Path] = []
    for directory in ("src", "include", "examples"):
        base = root / directory
        paths.extend(path for path in base.rglob("*") if path.suffix in (".c", ".h", ".inc"))
    paths.extend((root / "packaging").glob("*.txt"))
    paths.extend((root / "Makefile", root / "CMakeLists.txt"))
    return sorted(set(paths))


def main() -> int:
    root = Path(__file__).resolve().parents[1]
    failures: list[str] = []
    for path in audited_paths(root):
        relative = path.relative_to(root).as_posix()
        if OLD_PATH.search(relative):
            failures.append(f"{relative}: phase-named implementation file")
        text = path.read_text(encoding="utf-8")
        for number, line in enumerate(text.splitlines(), 1):
            for pattern in OLD_CONTENT:
                match = pattern.search(line)
                if match:
                    failures.append(
                        f"{relative}:{number}: implementation-round token "
                        f"{match.group(0)!r}"
                    )
                    break
    if failures:
        print("\n".join(failures))
        return 1
    print(f"naming audit PASS ({len(audited_paths(root))} active files)")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

tools/describe_webp.c

O describe_webp.c é um programa pequeno em C que imprime a configuração que o WebP usa em cada qualidade, só para auditoria, e não faz parte da biblioteca.

O arquivo completo tem 37 linhas:

/* Benchmark configuration audit; not part of the N.148i library.
 * Copyright (c) 2026 Micilini Roll. MIT License. */
#include <stdio.h>
#include <webp/encode.h>
#include <webp/decode.h>

#define FIELD(name) printf(",\"" #name "\":%.9g", (double)config.name)
int main(void) {
    const int qualities[] = {30, 45, 60, 75, 90};
    printf("{\"encoder_version\":%d,\"decoder_version\":%d,\"configurations\":[",
           WebPGetEncoderVersion(), WebPGetDecoderVersion());
    int first = 1;
    for (int method = 4; method <= 6; method += 2) {
        for (int point = 0; point < 5; point++) {
            WebPConfig config;
            if (!WebPConfigInit(&config)) return 1;
            config.lossless = 0;
            config.quality = (float)qualities[point];
            config.method = method;
            config.thread_level = 0;
            if (!WebPValidateConfig(&config)) return 1;
            printf("%s{\"input_use_argb\":0", first ? "" : ","); first = 0;
            FIELD(lossless); FIELD(quality); FIELD(method); FIELD(image_hint);
            FIELD(target_size); FIELD(target_PSNR); FIELD(segments);
            FIELD(sns_strength); FIELD(filter_strength); FIELD(filter_sharpness);
            FIELD(filter_type); FIELD(autofilter); FIELD(alpha_compression);
            FIELD(alpha_filtering); FIELD(alpha_quality); FIELD(pass);
            FIELD(show_compressed); FIELD(preprocessing); FIELD(partitions);
            FIELD(partition_limit); FIELD(emulate_jpeg_size); FIELD(thread_level);
            FIELD(low_memory); FIELD(near_lossless); FIELD(exact);
            FIELD(use_delta_palette); FIELD(use_sharp_yuv); FIELD(qmin); FIELD(qmax);
            printf("}");
        }
    }
    printf("]}\n");
    return 0;
}

A pasta tests

A pasta tests é nova na V2 e testa as próprias ferramentas do benchmark.

tests/test_benchmark_math.py

O test_benchmark_math.py confere, com casos de resposta conhecida, as contas estatísticas da comparação.

O arquivo completo tem 50 linhas:

"""Analytical checks for the published comparison's statistics."""
import sys
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools"))
import numpy as np
from benchmark_math import bd_rate
from analyze_release_benchmark import bootstrap_counts, curve, interval
from analyze_release_timing import timing_bootstrap


class StatisticsTests(unittest.TestCase):
    def test_constant_rate_saving_and_reciprocity(self):
        reference = [(x, 2 ** x) for x in (1., 2., 3., 4., 5.)]
        candidate = [(x, rate * .8) for x, rate in reference]
        self.assertAlmostEqual(bd_rate(candidate, reference)[0], -20., places=10)
        self.assertAlmostEqual(bd_rate(reference, candidate)[0], 25., places=10)
        self.assertAlmostEqual(bd_rate(reference, reference)[0], 0., places=10)

    def test_no_extrapolation(self):
        a = [(1., 1.), (2., 2.), (3., 4.)]
        b = [(4., 1.), (5., 2.), (6., 4.)]
        self.assertIsNone(bd_rate(a, b))

    def test_whole_image_strata_and_pooled_mse(self):
        counts = bootstrap_counts(["a", "a", "b", "b", "b"], 100, 148)
        np.testing.assert_array_equal(counts[:, :2].sum(axis=1), 2)
        np.testing.assert_array_equal(counts[:, 2:].sum(axis=1), 3)
        np.testing.assert_array_equal(counts, bootstrap_counts(["a", "a", "b", "b", "b"], 100, 148))
        pixels = np.array([1., 3.])
        sizes = np.array([[2., 4., 8.], [2., 4., 8.]])
        mses = np.array([[1., .5, .25], [9., 4.5, 2.25]])
        result = curve(np.ones(2), pixels, sizes, mses, mse=True)
        self.assertAlmostEqual(result[0][0], 10 * np.log10(65025 / 7.))

    def test_paired_constant_effect_interval(self):
        weights = bootstrap_counts(["a"] * 6, 80, 123)
        pixels = np.arange(1., 7.)
        size = np.arange(1., 7.)[:, None] * np.array([1., 2., 4., 8., 16.])
        quality = np.tile(np.arange(1., 6.), (6, 1))
        values = [bd_rate(curve(w, pixels, size * .8, quality), curve(w, pixels, size, quality))[0] for w in weights]
        np.testing.assert_allclose(interval(values), [-20., -20.], atol=1e-10)

    def test_nested_paired_timing_preserves_known_ratio(self):
        reference = np.arange(1., 85.).reshape(6, 2, 7)
        values = timing_bootstrap(reference * .75, reference, ["a"] * 3 + ["b"] * 3, 256, 9)
        np.testing.assert_allclose(values, -25., atol=1e-10)


if __name__ == "__main__": unittest.main()

tests/test_timing_collection.py

O test_timing_collection.py confere que um codec com medições ruidosas invalida a comparação de tempo inteira daquele ponto de operação.

O arquivo completo tem 50 linhas:

"""A noisy codec invalidates its whole paired operating-point comparison."""
import sys
import unittest
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools"))
from time_release_benchmark import collect_group


class TimingCollectionTests(unittest.TestCase):
    def test_before_or_after_noise_repeats_every_codec(self):
        for noisy_side in ("before", "after"):
            with self.subTest(noisy_side=noisy_side):
                calls, audits = [], []

                def run(codec):
                    calls.append(codec)
                    row = {"codec": codec, "before": {"interference": []}, "after": {"interference": []}}
                    if len(calls) == 4:
                        row[noisy_side]["interference"] = [{"external_cpu": 1.0}]
                    return row

                accepted = collect_group(list(range(8)), run, lambda: {"interference": []},
                                         lambda: self.fail("Unexpected initial wait"), audits.append)
                self.assertEqual(calls, list(range(4)) + list(range(8)))
                self.assertEqual([a["status"] for a in audits], ["interference", "accepted"])
                self.assertEqual([r["codec"] for r in accepted["rows"]], list(range(8)))

    def test_waits_before_start_and_rejects_noise_at_group_end(self):
        observations, calls, pauses, audits = 0, [], [], []

        def observe():
            nonlocal observations
            observations += 1
            # Initial wait, then noise at the final observation of attempt 1.
            return {"interference": [{"external_cpu": 1.0}] if observations in (1, 11) else []}

        def run(codec):
            calls.append(codec)
            return {"codec": codec, "before": {"interference": []}, "after": {"interference": []}}

        result = collect_group(list(range(8)), run, observe, lambda: pauses.append(True), audits.append)
        self.assertEqual(len(pauses), 1)
        self.assertEqual(calls, list(range(8)) * 2)
        self.assertEqual([a["status"] for a in audits], ["interference", "accepted"])
        self.assertEqual(result["attempt"], 2)


if __name__ == "__main__":
    unittest.main()

Conferência: os 93 arquivos da V2

Para você conferir que nada ficou de fora, esta é a lista de todos os arquivos de código da V2 que apareceram neste artigo, com o número de linhas de cada um, o mesmo que o comando wc -l mostra:

Arquivo                                   │ Situação │  Linhas
──────────────────────────────────────────┼──────────┼────────
.gitattributes                            │ alterado │      15
.github/workflows/build-libraries.yml     │ alterado │      85
.gitignore                                │ alterado │      45
CMakeLists.txt                            │ alterado │     199
LICENSE                                   │ igual    │      46
Makefile                                  │ alterado │     142
cmake/n148i.map                           │ alterado │       7
cmake/n148i.pc.in                         │ alterado │      13
cmake/n148iConfig.cmake.in                │ igual    │      12
cmake/toolchains/mingw-w64-x86_64.cmake   │ igual    │      14
examples/CMakeLists.txt                   │ alterado │      17
examples/memory_roundtrip.c               │ igual    │      67
include/n148i.h                           │ alterado │     304
packaging/README-Darwin.txt               │ alterado │      22
packaging/README-Linux.txt                │ alterado │      23
packaging/README-Windows.txt              │ alterado │      28
src/adaptive_quant.c                      │ novo     │     151
src/adaptive_quant.h                      │ novo     │      48
src/bench_cli.c                           │ igual    │      63
src/benchmark_final_cli.c                 │ alterado │     902
src/chroma_profile.c                      │ novo     │      86
src/chroma_profile.h                      │ novo     │      63
src/compare_cli.c                         │ igual    │     396
src/cpu.c                                 │ igual    │      85
src/cpu.h                                 │ igual    │      30
src/dct.c                                 │ alterado │     504
src/dct.h                                 │ alterado │      62
src/dct32_q14.inc                         │ novo     │      37
src/dct_forward_transposes.inc            │ novo     │      53
src/decoder.c                             │ alterado │   1.059
src/decoder.h                             │ alterado │      39
src/directional_intra.c                   │ novo     │   6.145
src/directional_intra.h                   │ novo     │     169
src/encoder.c                             │ alterado │     695
src/encoder.h                             │ alterado │      42
src/entropy_payload.c                     │ novo     │   4.826
src/entropy_payload.h                     │ novo     │      80
src/entropy_profile.c                     │ novo     │     323
src/entropy_profile.h                     │ novo     │      72
src/fidelity_profile.c                    │ novo     │     121
src/fidelity_profile.h                    │ novo     │      62
src/header.c                              │ igual    │      90
src/header.h                              │ alterado │      36
src/huffman.c                             │ igual    │     248
src/huffman.h                             │ igual    │      35
src/intra.c                               │ novo     │   1.343
src/intra.h                               │ novo     │      53
src/loop_filter.c                         │ novo     │     637
src/loop_filter.h                         │ novo     │      63
src/luma_profile.c                        │ novo     │      89
src/luma_profile.h                        │ novo     │      51
src/luma_projection_avx2.inc              │ novo     │      62
src/main.c                                │ alterado │     318
src/n148i.c                               │ alterado │     993
src/parallel.c                            │ igual    │     197
src/parallel.h                            │ igual    │      26
src/perceptual.c                          │ novo     │     214
src/perceptual.h                          │ novo     │      28
src/ppm.c                                 │ alterado │   1.164
src/ppm.h                                 │ alterado │      64
src/predictive_codec.h                    │ novo     │     196
src/quantize4_avx2.inc                    │ novo     │      53
src/rans.c                                │ novo     │     633
src/rans.h                                │ novo     │     107
src/rdo.c                                 │ novo     │     336
src/rdo.h                                 │ novo     │      45
src/segmentation.c                        │ novo     │     442
src/segmentation.h                        │ novo     │      67
src/tables.c                              │ alterado │     209
src/tables.h                              │ alterado │      28
src/validate_cli.c                        │ alterado │   4.674
src/variable_transform.c                  │ novo     │     946
src/variable_transform.h                  │ novo     │      89
src/variable_zigzag_tables.inc            │ novo     │      94
tests/test_benchmark_math.py              │ novo     │      50
tests/test_timing_collection.py           │ novo     │      50
tools/analyze_release_benchmark.py        │ novo     │     170
tools/analyze_release_timing.py           │ novo     │     141
tools/audit_naming.py                     │ novo     │      65
tools/benchmark_host.py                   │ novo     │      58
tools/benchmark_math.py                   │ novo     │      60
tools/benchmark_metrics.py                │ novo     │     119
tools/compact_release_evidence.py         │ novo     │      70
tools/describe_webp.c                     │ novo     │      37
tools/match_release_points.py             │ novo     │     176
tools/plot_release_benchmark.py           │ novo     │      41
tools/prepare_release_benchmark.py        │ novo     │     165
tools/release_benchmark.py                │ novo     │     259
tools/render_release_readme.py            │ novo     │     156
tools/requirements-benchmark.txt          │ novo     │       6
tools/time_release_benchmark.py           │ novo     │     206
tools/validate_release.py                 │ novo     │     431
tools/verify_release_evidence.py          │ novo     │     115
──────────────────────────────────────────┼──────────┼────────
Total                                     │          │  33.157

Se você copiar os arquivos daqui, cada um deve terminar com a mesma quantidade de linhas da tabela, e o projeto deve compilar exatamente como o do repositório.

Lembrando que cada arquivo deste artigo foi conferido, byte por byte, contra o commit da V2 no repositório.

Compilando e rodando a V2

Com todos os arquivos na mão, seja copiando daqui ou baixando do repositório, a V2 compila com um compilador C e o CMake, que você baixa em cmake.org/download.

No Linux

Instale o compilador e o CMake com o gerenciador de pacotes da sua distribuição:

# Ubuntu, Debian e Linux Mint
sudo apt install build-essential cmake

# Fedora
sudo dnf install gcc cmake

# Arch Linux
sudo pacman -S gcc cmake

Se você montou o projeto copiando os arquivos daqui, crie antes as pastas images e output e baixe a imagem de exemplo do repositório, porque a bateria de validação precisa dela:

mkdir -p images output
curl -L -o images/example.ppm https://github.com/micilini/n148/raw/6193c19b2201e36e6dfd201f7bf1b2997ff6eefa/images/example.ppm

Se preferir, baixe a imagem pelo navegador, neste link direto, e salve dentro da pasta images.

Dentro da pasta do projeto, estes quatro comandos configuram, compilam, testam e instalam a biblioteca:

cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$PWD/install"
cmake --build build --config Release --parallel 2
ctest --test-dir build -C Release --output-on-failure
cmake --install build --config Release

Eu rodei esses comandos no Linux, com o código do commit 6193c19, e o final da saída do ctest foi este:

    Start 1: n148i.memory_roundtrip
1/5 Test #1: n148i.memory_roundtrip ...............   Passed    0.00 sec
    Start 2: n148i.shared_roundtrip
2/5 Test #2: n148i.shared_roundtrip ...............   Passed    0.00 sec
    Start 3: n148i.memory_roundtrip_small_stack
3/5 Test #3: n148i.memory_roundtrip_small_stack ...   Passed    0.00 sec
    Start 4: n148i.shared_roundtrip_small_stack
4/5 Test #4: n148i.shared_roundtrip_small_stack ...   Passed    0.01 sec
    Start 5: n148i.validation
5/5 Test #5: n148i.validation .....................   Passed   16.11 sec

100% tests passed, 0 tests failed out of 5

Total Test time (real) =  16.14 sec

O quinto teste é a bateria do validate_cli.c, que levou cerca de 16 segundos na minha máquina, e é ele que reclama com a mensagem could not load images/example.ppm quando a imagem de exemplo não está no lugar.

Eu também montei a V2 só com o código deste artigo, numa pasta vazia, mais a imagem de exemplo e a pasta output, e ela compilou, passou nos cinco testes e gerou o mesmo arquivo de 1.862 bytes que você vai ver logo abaixo. 🎯

Para comprimir uma imagem pela linha de comando, use qualquer arquivo PPM, como a imagem de exemplo da pasta images do repositório:

mkdir -p output
./build/n148i images/example.ppm 60

A saída na minha máquina foi esta:

=== N.148i encoder ===
Input:    images/example.ppm  (320 x 240)
Quality:  60
Chroma:   4:2:0
Format:   v7
Effort:   3
Profile:  default
Coding:   contextual byte rANS with intra prediction

Y plane:      320 x 240
Cb/Cr planes: 160 x 120

Encoded 1800 blocks
Feature flags:   0xd8a6d7ff
Entropy metadata: 545 bytes
Entropy data:   1285 bytes
Wrote output/image.n148i

=== N.148i decoder ===
Header:  v7, 320 x 240, quality 60, chroma 4:2:0, features 0xd8a6d7ff
Decoded 1800 blocks, consumed 1285 of 1285 bytes
Upsampling: bilinear
Wrote output/decoded.ppm

=== Results ===
Original PPM:   230415 bytes (225.0 KB)
N148i file:       1862 bytes (1.8 KB)
Compression:  123.7:1
PSNR:         36.23 dB

O programa escreve o arquivo comprimido em output/image.n148i e a imagem decodificada em output/decoded.ppm, e aceita também a cor, o formato, o perfil e o esforço, nesta ordem:

./build/n148i [input.ppm] [quality] [chroma] [format] [profile] [effort]

Se você preferir o Makefile, basta rodar make na pasta do projeto, e o executável n148i aparece na raiz, ligado à biblioteca estática.

No macOS

No Mac, instale as Command Line Tools com xcode-select --install e o CMake pelo site oficial ou pelo Homebrew, com brew install cmake.

Os comandos são os mesmos do Linux, e para gerar uma biblioteca universal, que roda no Intel e no Apple Silicon, a configuração ganha mais uma opção:

cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$PWD/install" -DCMAKE_OSX_ARCHITECTURES="x86_64;arm64"

No Apple Silicon, a V2 usa o código escalar com threads, e os testes nativos do macOS já estão configurados na integração contínua, mas ainda não tinham rodado quando a V2 foi publicada.

No Windows

No Windows, a pasta images com a imagem de exemplo e a pasta output também precisam existir antes dos testes, e a imagem pode ser baixada pelo mesmo link direto.

O caminho usado pela integração contínua é o compilador da Microsoft, que vem com as Build Tools for Visual Studio, em visualstudio.microsoft.com/visual-cpp-build-tools, marcando a opção Desenvolvimento para desktop com C++, e o CMake pelo site oficial, caso ele não venha junto.

No Developer Command Prompt for VS, dentro da pasta do projeto, os comandos ficam assim:

cmake -S . -B build -A x64 -DCMAKE_INSTALL_PREFIX="%CD%\install"
cmake --build build --config Release --parallel
ctest --test-dir build -C Release --output-on-failure
cmake --install build --config Release

Com o compilador da Microsoft, a V2 usa o código escalar e uma thread só, como explicam as notas da biblioteca, e a execução nativa no Windows também depende da integração contínua.

Do Linux, também dá para gerar a versão do Windows com o MinGW, usando o arquivo de toolchain da pasta cmake, e foi assim que a V2 foi validada para o Windows:

cmake -S . -B build-windows -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/mingw-w64-x86_64.cmake
cmake --build build-windows --config Release --parallel

Nesse caso, a DLL também precisa da libgcc_s_seh-1.dll do MinGW ao lado do programa, como explica o README-Windows.txt.

As ferramentas do benchmark

As ferramentas em Python precisam das bibliotecas listadas no requirements-benchmark.txt, que você instala com o comando abaixo, mas elas só servem para repetir o julgamento, e não para usar o codec:

pip install -r tools/requirements-benchmark.txt

A série inteira, num lugar só

Para fechar a Fase 5, aqui está a série completa, do primeiro pixel até este artigo:

Do pixel RGB do artigo 1 até a V2 do artigo 41: a jornada completa do N.148i até aqui.

Repositório no GitHub

E sim, você pode acompanhar a evolução desse CODEC de imagens em um repositório no GitHub, commit por commit 👋

O projeto é aberto, com licença MIT, então fique à vontade para estudar, compilar, medir e mandar sugestões. 🙌

Resumo

Recapitulando:

  • Contando só o código e os arquivos de build, a V2 tem 93 arquivos e 33.157 linhas, contra 49 arquivos da V1.
  • Da V1 para a V2, 27 arquivos foram alterados, 53 foram criados, 13 continuaram iguais e 9 ferramentas antigas do benchmark foram removidas.
  • A pasta src saiu de 24 para 58 arquivos, e o maior deles, o directional_intra.c, tem 6.145 linhas.
  • O validate_cli.c foi o arquivo que mais cresceu, de 417 para 4.674 linhas, porque cada ferramenta nova ganhou os seus próprios testes.
  • A V2 preservou o caminho inteiro da V1, com o Huffman e o formato 1, e por isso ainda lê todos os arquivos antigos.
  • Cada arquivo trouxe o link para o artigo que explica a lógica dele, do rANS do artigo 27 às reconstruções do artigo 38.
  • No Linux, a V2 compilou e passou nos cinco testes tanto com o código do commit 6193c19 quanto montada só a partir deste artigo.
  • Para o Windows, a V2 compila por compilação cruzada com o MinGW, e os builds nativos do Windows e do macOS estão configurados na integração contínua.
  • Todo o código deste artigo é idêntico, byte por byte, ao dos commits da V1 e da V2 no repositório.

E assim termina a Fase 5. 🏁

Ela nasceu de uma derrota para o JPEG XL, no artigo 25, e termina com um codec escrito do zero que, nas 130 imagens do julgamento, vence o WebP M6 sem nenhuma derrota e ganha do JPEG XL nas réguas clássicas.

Obrigado por chegar até aqui, artigo por artigo, e por acompanhar cada ideia, inclusive as que ficaram no cemitério. ❤️

A próxima fase ainda vai ser anunciada, mas uma coisa eu já posso adiantar: o N.148i não para por aqui.

Até a próxima! 👋

Criadores de Conteúdo

Foto do William Lima
William Lima
Fundador da Micilini

Inventor nato, escreve conteudos de programação para o portal da micilini.

Torne-se um MIC 🤖

Mais de 100 mic's já estão conectados na plataforma.