Segmentação: quatro tipos de região, quatro quantizações

Segmentação: quatro tipos de região, quatro quantizações

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

Este é o trigésimo sexto artigo da nossa série, e o décimo da Fase 5.

Até aqui, o N.148i usou a mesma régua de quantização na imagem inteira, então o céu liso e a grama cheia de detalhes receberam exatamente os mesmos passos.

Hoje vamos dividir a imagem em quatro tipos de região, do mais calmo ao mais agitado, de forma a dar a cada tipo a sua própria quantização. 🗺️

E aviso logo que esta é a história de uma ideia que fazia todo o sentido no papel, foi testada duas vezes no N.148i, e nas duas vezes não entrou no perfil padrão, até voltar no final por uma porta lateral.

Sendo assim, pega o café e vem comigo, que hoje teremos uma reviravolta daquelas! ☕

Lembrando como os exemplos funcionam

Assim como nos artigos anteriores, os programas em C que aparecem aqui são exemplos pequenos e independentes, feitos para mostrar a ideia funcionando, e não são o código do N.148i.

O segundo programa volta para o programa de laboratório do artigo 32, em tons de cinza, com dez modos, planar, blocos 4x4 e RDO, e ele também não é o N.148i nem uma versão pequena dele.

As imagens dos exemplos não vêm de arquivos: elas são criadas dentro do próprio programa por pequenas funções em C, onde cada função recebe a posição de um pixel e devolve o brilho dele usando uma fórmula simples.

O olho não enxerga tudo igual

Imagina que você derrubou uma gota de café na camisa, e agora pensa em duas camisas diferentes.

Numa camisa branca e lisa, a mancha aparece de longe, mas numa camisa toda estampada, cheia de flores e listras, a mesma mancha praticamente some no meio do desenho. 👕

O olho humano funciona assim com as imagens: um erro numa região lisa, como um céu limpo, chama atenção na hora, enquanto o mesmo erro no meio de uma textura, como grama ou cascalho, fica escondido pelos detalhes que já estão ali.

Esse efeito tem um nome, mascaramento visual, porque a textura funciona como uma máscara que esconde os erros que caem dentro dela.

O mascaramento visual: a mesma mancha aparece numa camisa lisa e some numa camisa estampada, e o mesmo vale para os erros de compressão.

Gastar os bits onde o olho vê

Se os erros na textura ficam escondidos, faz sentido usar passos de quantização um pouco maiores nas regiões agitadas, economizando bits ali, e passos um pouco menores nas regiões lisas, onde qualquer erro aparece.

Pensa num pintor com pouco tempo para pintar uma casa: ele capricha na parede lisa da frente, onde cada falha aparece, e passa mais rápido pelo muro de pedra do fundo, onde ninguém vai perceber uma pincelada torta. 🖌️

A quantização adaptativa gasta os bits como um pintor com pouco tempo: capricha onde a falha aparece e passa rápido onde a textura quase não aparece muito.

Essa técnica se chama quantização adaptativa, e a forma de organizar a imagem para usá-la se chama segmentação: o encoder divide a imagem em regiões, coloca cada região num tipo, e cada tipo recebe uma escala que multiplica os passos de quantização.

escala abaixo de 100  →  passos menores  →  mais detalhe, mais bits
escala igual a 100    →  passos normais
escala acima de 100   →  passos maiores  →  menos detalhe, menos bits

passo da região = (passo normal · escala + 50) / 100

Como dividir a imagem em quatro tipos?

A primeira decisão é o tamanho das regiões, e o N.148i usa regiões de 16x16 pixels, grandes o bastante para que o mapa não custe caro e pequenas o bastante para separar o céu da grama.

A segunda decisão é como medir se uma região é calma ou agitada, e uma ideia esperta é medir aquilo que a DCT realmente vai receber: para cada pedaço de 8x8 da região, o encoder tenta os quatro palpites clássicos e anota o menor erro, e a soma desses erros vira a nota de dificuldade da região.

Isso é melhor que olhar só a variação dos pixels, porque um degradê suave varia bastante, mas é fácil de prever, e o que importa para a quantização é o que sobra depois do palpite.

Separando as notas em quatro grupos

Com uma nota para cada região, falta separar as notas em quatro grupos, e para isso o encoder usa um método de agrupamento bem simples.

Pensa em mil livros espalhados no chão que você quer dividir em quatro prateleiras pela grossura: você chuta quatro grossuras de referência, coloca cada livro na prateleira com a referência mais parecida, depois troca cada referência pela média dos livros que caíram nela, e repete até ninguém mais mudar de prateleira. 📚

Esse método tem o nome de k-médias, e no final as quatro prateleiras são colocadas em ordem, para que o tipo 0 seja sempre o mais calmo e o tipo 3 sempre o mais agitado.

O agrupamento por k-médias funciona como separar livros em quatro prateleiras: cada livro vai para a referência mais parecida, e as referências são recalculadas até ninguém mudar de lugar.

Contando o mapa ao decoder

O decoder não precisa saber como o encoder calculou as notas, ele só precisa receber o tipo de cada região e as quatro escalas.

Como regiões vizinhas costumam ser do mesmo tipo, o mapa é gravado como a diferença em relação ao vizinho da esquerda, e na maior parte das vezes essa diferença é zero, que é um símbolo baratíssimo para o rANS.

Esse detalhe deixa uma porta aberta muito útil: como o jeito de montar o mapa não faz parte do formato, um encoder futuro pode inventar um jeito melhor de escolher os tipos sem mudar uma linha do decoder.

Preparando o ambiente para os exemplos

Os exemplos deste artigo são programas em C puro, e assim como nos artigos anteriores eles não dependem de nenhuma biblioteca externa, apenas da biblioteca padrão que já acompanha qualquer compilador C.

Se você já preparou o ambiente em algum dos artigos anteriores desta fase, pode pular esta seção, e se ainda não preparou, crie uma pasta, por exemplo exemplos-segmentacao, e siga as instruções do seu sistema.

No Linux

A maioria das distribuições já traz o GCC instalado, mas se o seu sistema não tiver, basta instalar com o gerenciador de pacotes:

# Ubuntu, Debian e Linux Mint
sudo apt install build-essential

# Fedora
sudo dnf install gcc

# Arch Linux
sudo pacman -S gcc

O -lm que aparece nos comandos de compilação liga a biblioteca matemática, onde moram funções como log e cos, e no Linux ela não entra automaticamente.

No macOS

No Mac o compilador vem junto com as Command Line Tools da Apple, que você instala abrindo o Terminal e rodando:

xcode-select --install

Se preferir, também dá para instalar o Xcode completo pela App Store ou pelo site da Apple, em developer.apple.com/xcode, e depois compilar com o clang, que é o compilador padrão do macOS.

No Windows

O primeiro caminho é o MSYS2, que traz o GCC para o Windows. Baixe o instalador em msys2.org, abra o terminal chamado MSYS2 UCRT64 e instale o compilador com este comando:

pacman -S mingw-w64-ucrt-x86_64-gcc

O segundo caminho é o compilador da Microsoft, que vem junto com as Build Tools for Visual Studio, disponíveis em visualstudio.microsoft.com/visual-cpp-build-tools, onde durante a instalação basta marcar a opção Desenvolvimento para desktop com C++ e depois usar o Developer Command Prompt for VS pelo menu Iniciar.

Primeiro experimento: o mapa da imagem

O primeiro programa pega a imagem do laboratório e faz as quatro etapas da segmentação: calcula a nota de dificuldade de cada região de 16x16, separa as notas em quatro tipos com o k-médias, escolhe uma escala para cada tipo e calcula quanto o mapa custaria no arquivo.

As escalas seguem a regra da primeira segmentação do N.148i: quanto mais longe a nota de um tipo estiver da média da imagem, mais longe a escala fica de 100, com limites que protegem os tipos calmos e seguram o tipo mais agitado.

A saída mostra quatro coisas:

  • Quantas rodadas o k-médias levou para parar de mudar.
  • Uma tabela com a nota central de cada tipo, quantas regiões caíram nele e a escala escolhida.
  • O mapa desenhado com um número por região, do 0, mais calmo, até o 3, mais agitado.
  • Quantas regiões têm o mesmo tipo do vizinho e quanto o mapa custa em bytes.

Salve o arquivo como mapa_de_segmentos.c:

/*
 * mapa_de_segmentos.c
 *
 * Splits the laboratory image (sky, sun, grass and building) into 16x16
 * regions and sorts every region into one of four classes, from the
 * calmest (0) to the busiest (3):
 *
 *   1. each region gets a "difficulty" score: for each of its four 8x8
 *      cells, the program tries the four classic guesses (DC, vertical,
 *      horizontal, TrueMotion) from the pixels around it and keeps the
 *      smallest error, a rough measure of what the DCT will receive;
 *   2. the scores are grouped into four classes with a simple clustering
 *      method that starts with four centres and moves each one to the
 *      average of the scores closest to it, until nothing changes;
 *   3. each class gets a quantization scale: below 100 means finer steps,
 *      above 100 means coarser steps;
 *   4. the map is written as the difference from the left neighbor, which
 *      costs very few bits when neighbors belong to the same class.
 *
 * This is an educational example. It is not the code used inside N.148i.
 */
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define W        512
#define H        512
#define REGIONS  (W / 16)
#define CLASSES  4

static uint32_t rng = 2463534242u;
static int noise(int amplitude) {
    rng ^= rng << 13; rng ^= rng >> 17; rng ^= rng << 5;
    return (int)(rng % (uint32_t)(2 * amplitude + 1)) - amplitude;
}

/* The same image as the laboratory of the previous articles. */
static void make_image(uint8_t *image) {
    for (int y = 0; y < H; y++)
        for (int x = 0; x < W; x++) {
            int v;
            if (y < H / 2) {
                v = 150 + y / 6;
                int dx = x - 380, dy = y - 90;
                if (dx * dx + dy * dy < 45 * 45) v = 245;
            } else if (x < W / 2) {
                v = 90 + (int)(25 * sin(x * 0.35) * cos(y * 0.27)) + noise(30);
            } else {
                v = 120;
                if ((x % 40) > 12 && (x % 40) < 30 && (y % 36) > 10 && (y % 36) < 26) v = 40;
            }
            image[y * W + x] = (uint8_t)(v < 0 ? 0 : (v > 255 ? 255 : v));
        }
}

static int pixel(const uint8_t *image, int x, int y) {
    if (x < 0 || y < 0) return 128;          /* outside the image: neutral */
    return image[y * W + x];
}

/* Smallest guess error of one 8x8 cell, each pixel error clipped to 32 so
   a single sharp edge does not dominate the score. */
static long cell_score(const uint8_t *image, int x0, int y0) {
    long best = -1;
    int sum = 0;
    for (int i = 0; i < 8; i++) sum += pixel(image, x0 + i, y0 - 1) + pixel(image, x0 - 1, y0 + i);
    int dc = (sum + 8) / 16, corner = pixel(image, x0 - 1, y0 - 1);
    for (int mode = 0; mode < 4; mode++) {
        long error = 0;
        for (int y = 0; y < 8; y++)
            for (int x = 0; x < 8; x++) {
                int top = pixel(image, x0 + x, y0 - 1), left = pixel(image, x0 - 1, y0 + y);
                int guess = mode == 0 ? dc : mode == 1 ? top : mode == 2 ? left : left + top - corner;
                int e = abs(image[(y0 + y) * W + x0 + x] - guess);
                error += e > 32 ? 32 : e;
            }
        if (best < 0 || error < best) best = error;
    }
    return best;
}

static int nearest(long score, const long centre[CLASSES]) {
    int best = 0;
    for (int c = 1; c < CLASSES; c++)
        if (labs(score - centre[c]) < labs(score - centre[best])) best = c;
    return best;
}

static int compare_long(const void *a, const void *b) {
    long x = *(const long *)a, y = *(const long *)b;
    return (x > y) - (x < y);
}

int main(void) {
    static uint8_t image[W * H];
    long score[REGIONS * REGIONS], sorted[REGIONS * REGIONS], centre[CLASSES];
    int level[REGIONS * REGIONS];
    make_image(image);

    for (int ry = 0; ry < REGIONS; ry++)
        for (int rx = 0; rx < REGIONS; rx++) {
            long s = 0;
            for (int c = 0; c < 4; c++) s += cell_score(image, rx * 16 + (c % 2) * 8, ry * 16 + (c / 2) * 8);
            score[ry * REGIONS + rx] = s;
        }

    /* Clustering: start the four centres at the 1/8, 3/8, 5/8 and 7/8 points
       of the sorted scores, then move each centre to the average of its
       members until the centres stop moving. */
    int n = REGIONS * REGIONS;
    memcpy(sorted, score, sizeof(sorted));
    qsort(sorted, n, sizeof(long), compare_long);
    for (int c = 0; c < CLASSES; c++) centre[c] = sorted[(2 * c + 1) * n / (2 * CLASSES)];
    for (int round = 1; round <= 20; round++) {
        long sum[CLASSES] = {0}, count[CLASSES] = {0};
        for (int i = 0; i < n; i++) { int c = nearest(score[i], centre); sum[c] += score[i]; count[c]++; }
        int moved = 0;
        for (int c = 0; c < CLASSES; c++) {
            if (!count[c]) continue;
            long next = (sum[c] + count[c] / 2) / count[c];
            if (next != centre[c]) moved = 1;
            centre[c] = next;
        }
        if (!moved) { printf("clustering settled after %d rounds\n\n", round); break; }
    }

    /* The centres can swap places while they move, so they are put back in
       order: class 0 is always the calmest and class 3 the busiest. */
    qsort(centre, CLASSES, sizeof(long), compare_long);

    long count[CLASSES] = {0};
    double mean = 0.0;
    for (int i = 0; i < n; i++) { level[i] = nearest(score[i], centre); count[level[i]]++; mean += centre[level[i]]; }
    mean /= n;

    /* Scales in the spirit of the first N.148i segmentation: farther from the
       average difficulty means farther from 100, with limits that protect
       the calm classes and cap the busiest one. */
    int scale[CLASSES];
    long range = centre[CLASSES - 1] - centre[0];
    for (int c = 0; c < CLASSES; c++) {
        double delta = range ? 32.0 * (centre[c] - mean) / range : 0.0;
        int s = (int)lround(100 + delta);
        if (s < 75) s = 75;
        if (s > 125) s = 125;
        if (c == 0 && s > 88) s = 88;
        if (c == 1 && s > 95) s = 95;
        if (c == 3 && s > 118) s = 118;
        scale[c] = s;
    }
    printf("class  centre  regions  scale\n");
    for (int c = 0; c < CLASSES; c++)
        printf("  %d   %6ld   %6ld   %4d\n", c, centre[c], count[c], scale[c]);

    printf("\nThe map, one character per 16x16 region (0 = calm ... 3 = busy)\n\n");
    for (int ry = 0; ry < REGIONS; ry++) {
        printf("   ");
        for (int rx = 0; rx < REGIONS; rx++) putchar('0' + level[ry * REGIONS + rx]);
        printf("\n");
    }

    /* The map is written as (class - prediction) mod 4, where the prediction
       is the class on the left, or the one above at the start of a row. */
    long symbols[CLASSES] = {0};
    for (int i = 0; i < n; i++) {
        int rx = i % REGIONS, ry = i / REGIONS;
        int prediction = i == 0 ? 1 : (rx > 0 ? level[i - 1] : level[(ry - 1) * REGIONS]);
        symbols[(level[i] - prediction + CLASSES) % CLASSES]++;
    }
    double bits = 0.0;
    for (int s = 0; s < CLASSES; s++)
        if (symbols[s]) bits += symbols[s] * -log2((double)symbols[s] / n);
    printf("\nmap symbols: %ld same as the neighbor, %ld different\n", symbols[0], n - symbols[0]);
    printf("cost of the map: %.0f bytes for %d regions (%.2f bits each)\n", bits / 8.0, n, bits / n);
    return 0;
}

Compile e rode com o comando do seu sistema:

# Linux
gcc -std=c99 -O2 -Wall mapa_de_segmentos.c -o mapa_de_segmentos -lm
./mapa_de_segmentos

# macOS
clang -std=c99 -O2 -Wall mapa_de_segmentos.c -o mapa_de_segmentos
./mapa_de_segmentos

# Windows (terminal MSYS2 UCRT64)
gcc -std=c99 -O2 -Wall mapa_de_segmentos.c -o mapa_de_segmentos.exe
./mapa_de_segmentos.exe

# Windows (Developer Command Prompt do Visual Studio)
cl /O2 mapa_de_segmentos.c
mapa_de_segmentos.exe

E a saída será esta:

clustering settled after 10 rounds

class  centre  regions  scale
  0       17      659     88
  1      323       94     94
  2     1390       15    102
  3     4355      256    118

The map, one character per 16x16 region (0 = calm ... 3 = busy)

   20000000000000000000000000000000
   00000000000000000000000000000000
   00000000000000000000000010000000
   00000000000000000000022002000000
   00000000000000000000020000200000
   00000000000000000000010000100000
   00000000000000000000010000100000
   00000000000000000000020002100000
   00000000000000000000001011000000
   00000000000000000000000000000000
   00000000000000000000000000000000
   00000000000000000000000000000000
   00000000000000000000000000000000
   00000000000000000000000000000000
   00000000000000000000000000000000
   00000000000000000000000000000000
   33333333333333332000000000000000
   33333333333333331010100101001010
   33333333333333332011110111101111
   33333333333333332010100101001010
   33333333333333331000000000000000
   33333333333333331010100101001010
   33333333333333330000000000000000
   33333333333333332011110111101111
   33333333333333332010100101001010
   33333333333333331000000000000000
   33333333333333331010100101001010
   33333333333333332011110111101111
   33333333333333332010100101001010
   33333333333333331000000000000000
   33333333333333331010100101001010
   33333333333333330000000000000000

map symbols: 864 same as the neighbor, 160 different
cost of the map: 110 bytes for 1024 regions (0.86 bits each)

Lendo o primeiro experimento

O mapa desenhou a imagem direitinho: o céu ficou quase todo com o tipo 0, a grama da metade de baixo à esquerda ficou toda com o tipo 3, e o contorno do sol apareceu como um anel de tipos 1 e 2 no meio do céu. 🎯

No prédio, as paredes lisas ficaram com o tipo 0, e as regiões que encostam nas janelas ficaram com os tipos 1 e 2, formando aquele padrão quadriculado que acompanha a grade das janelas.

Repara também no primeiro caractere do mapa, um 2 no canto de cima à esquerda do céu: ali não existem vizinhos, então os palpites usam o valor neutro 128, que fica longe do azul do céu e deixa a região com cara de difícil.

As escalas ficaram como a regra pediu, com 88 para o céu, 94 e 102 para os tipos do meio e 118 para a grama, e o mapa inteiro custou 110 bytes, menos de um bit por região, porque 864 das 1.024 regiões tinham o mesmo tipo do vizinho.

Segundo experimento: segmentação no laboratório

Agora vamos usar o mapa de verdade no programa de laboratório: cada bloco multiplica os seus passos de quantização pela escala da região onde ele está, tanto no encoder quanto no decoder, e o custo do mapa entra no tamanho do arquivo.

O programa compara seis esquemas, que só mudam as quatro escalas:

Esquema                     │ Escalas (tipo 0 → tipo 3) │ Ideia
────────────────────────────┼───────────────────────────┼─────────────────────────────────
no segmentation (art. 32)   │ sem mapa                  │ o ponto de partida
map, all scales 100         │ 100  100  100  100        │ só o custo de gravar o mapa
texture coarser             │  88   94  102  118        │ mascaramento: textura mais grossa
texture coarser, stronger   │  76   88  104  125        │ a mesma ideia com o dobro da força
reversed: texture finer     │ 112  106   98   82        │ o contrário: textura mais fina
gentle (eighth root)        │  99   99  101  104        │ uma versão bem suave

O último esquema usa a raiz oitava da nota de dificuldade, que é o estilo da segmentação que aparece na versão final do N.148i (toma essa spoiler rs), e por isso as escalas mal saem do 100.

Além do PSNR, este programa mede a qualidade com o SSIM, uma métrica que compara pequenas janelas de 8x8 da imagem com o original, olhando se o brilho médio, o contraste e o desenho de cada janela continuam parecidos, e quanto mais perto de 1, melhor.

A saída começa com as escalas de cada esquema, depois mostra uma tabela para cada intensidade de quantização, com os bytes, o PSNR, o SSIM e a conferência do decoder, e termina com duas tabelas que comparam cada esquema com o ponto de partida para a mesma qualidade, uma pelo PSNR e outra pelo SSIM.

Salve o arquivo como segmentacao_laboratorio.c:

/*
 * segmentacao_laboratorio.c
 *
 * The laboratory program of article 32 (ten modes, planar, 4x4 blocks and
 * RDO), now with a segmentation map: every 16x16 region belongs to one of
 * four classes, from calm to busy, and each class multiplies the luma
 * quantization steps of its blocks by its own scale.
 *
 * The map is built like in the previous example (a difficulty score per
 * region, four-centre clustering, classes in order), written as the
 * difference from the neighbor, and its cost is part of the file size.
 *
 * The schemes change only the four scales: neutral (all 100), coarser in
 * the busy texture, the same idea stronger, the opposite direction, and a
 * very gentle version in the style of the final N.148i.
 *
 * Quality is measured with PSNR and with SSIM, a metric that compares the
 * local brightness, contrast and structure of small windows.
 *
 * This is an educational example. It is not the code used inside N.148i.
 */
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define WIDTH       512
#define HEIGHT      512
#define CELLS_X     (WIDTH / 8)
#define CELLS_Y     (HEIGHT / 8)
#define UNITS_X     (WIDTH / 4)
#define UNITS_Y     (HEIGHT / 4)
#define ALPHABET    16
#define MODES       10
#define PI          3.14159265358979323846

enum { DC, V, H, TM, DL, DR, VR, HD, VL, HU };

static const int ZIGZAG8[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
};
static const int ZIGZAG4[16] = { 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15 };

/* The luminance table from Annex K of the JPEG standard (quality 50). */
static const int QUANT_BASE[64] = {
    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
};
static int QUANT8[64], QUANT4[16];

/* ------------------------------------------------------------------------ */
/* The same synthetic photo: sky, sun, grass and a building.                */

static uint32_t rng;
static int noise(int amplitude) {
    rng ^= rng << 13; rng ^= rng >> 17; rng ^= rng << 5;
    return (int)(rng % (uint32_t)(2 * amplitude + 1)) - amplitude;
}

static void make_image(uint8_t *image) {
    rng = 2463534242u;
    for (int y = 0; y < HEIGHT; y++) {
        for (int x = 0; x < WIDTH; x++) {
            int v;
            if (y < HEIGHT / 2) {
                v = 150 + y / 6;
                int dx = x - 380, dy = y - 90;
                if (dx * dx + dy * dy < 45 * 45) v = 245;
            } else if (x < WIDTH / 2) {
                v = 90 + (int)(25 * sin(x * 0.35) * cos(y * 0.27)) + noise(30);
            } else {
                v = 120;
                if ((x % 40) > 12 && (x % 40) < 30 && (y % 36) > 10 && (y % 36) < 26) v = 40;
            }
            if (v < 0) v = 0;
            if (v > 255) v = 255;
            image[y * WIDTH + x] = (uint8_t)v;
        }
    }
}

static int clamp_byte(int v) { return v < 0 ? 0 : (v > 255 ? 255 : v); }

/* A strength of 1.0 uses the JPEG table as it is, 2.0 doubles every step. */
static void set_strength(double strength) {
    for (int i = 0; i < 64; i++) {
        int q = (int)lround(QUANT_BASE[i] * strength);
        QUANT8[i] = q < 1 ? 1 : q;
    }
    for (int v = 0; v < 4; v++)
        for (int u = 0; u < 4; u++) QUANT4[v * 4 + u] = QUANT8[(2 * v) * 8 + 2 * u];
}

/* ------------------------------------------------------------------------ */
/* DCT of size n (4 or 8), done one direction at a time.                    */

static double basis8[8][8], basis4[4][4];

static void init_basis(void) {
    for (int u = 0; u < 8; u++)
        for (int x = 0; x < 8; x++)
            basis8[u][x] = (u == 0 ? sqrt(1.0 / 8) : sqrt(2.0 / 8)) * cos((2 * x + 1) * u * PI / 16);
    for (int u = 0; u < 4; u++)
        for (int x = 0; x < 4; x++)
            basis4[u][x] = (u == 0 ? sqrt(1.0 / 4) : sqrt(2.0 / 4)) * cos((2 * x + 1) * u * PI / 8);
}

static double base_of(int n, int u, int x) { return n == 8 ? basis8[u][x] : basis4[u][x]; }

/* forward: out = B * in * B^T. inverse: out = B^T * in * B. */
static void transform(int n, const double *in, double *out, int inverse) {
    double tmp[64];
    for (int r = 0; r < n; r++)
        for (int c = 0; c < n; c++) {
            double sum = 0.0;
            for (int k = 0; k < n; k++)
                sum += (inverse ? base_of(n, k, c) : base_of(n, c, k)) * in[r * n + k];
            tmp[r * n + c] = sum;
        }
    for (int r = 0; r < n; r++)
        for (int c = 0; c < n; c++) {
            double sum = 0.0;
            for (int k = 0; k < n; k++)
                sum += (inverse ? base_of(n, k, r) : base_of(n, r, k)) * tmp[k * n + c];
            out[r * n + c] = sum;
        }
}

static int current_scale;   /* set by the segmentation, see below */
static int step_at(int n, int k) {
    int base = n == 8 ? QUANT8[ZIGZAG8[k]] : QUANT4[ZIGZAG4[k]];
    int step = (base * current_scale + 50) / 100;
    return step < 1 ? 1 : (step > 255 ? 255 : step);
}
static int natural_at(int n, int k) { return n == 8 ? ZIGZAG8[k] : ZIGZAG4[k]; }

/* ------------------------------------------------------------------------ */
/* Which pixels the decoder already has, one flag per 4x4 unit.             */

static uint8_t done[UNITS_X * UNITS_Y];

static int known(int x, int y) {
    if (x < 0 || y < 0 || x >= WIDTH || y >= HEIGHT) return 0;
    return done[(y / 4) * UNITS_X + x / 4];
}

static void mark_done(int x0, int y0, int n, uint8_t value) {
    for (int y = y0; y < y0 + n; y += 4)
        for (int x = x0; x < x0 + n; x += 4) done[(y / 4) * UNITS_X + x / 4] = value;
}

/* ------------------------------------------------------------------------ */
/* The ten guesses of article 31, with planar in the place of TrueMotion    */
/* on 8x8 blocks.                                                           */

typedef struct { int top[16], left[16], corner, n, has_top, has_left; } Refs;

static Refs gather(const uint8_t *image, int x0, int y0, int n) {
    Refs r;
    r.n = n;
    r.has_top = known(x0, y0 - 1);
    r.has_left = known(x0 - 1, y0);
    for (int i = 0; i < 2 * n; i++) {
        if (!r.has_top) r.top[i] = 128;
        else if (known(x0 + i, y0 - 1)) r.top[i] = image[(y0 - 1) * WIDTH + x0 + i];
        else r.top[i] = r.top[i - 1];
        if (!r.has_left) r.left[i] = 128;
        else if (known(x0 - 1, y0 + i)) r.left[i] = image[(y0 + i) * WIDTH + x0 - 1];
        else r.left[i] = r.left[i - 1];
    }
    r.corner = r.has_top && r.has_left ? image[(y0 - 1) * WIDTH + x0 - 1] : 128;
    return r;
}

static int avg2(int a, int b) { return (a + b + 1) >> 1; }
static int avg3(int a, int b, int c) { return (a + 2 * b + c + 2) >> 2; }
static int top_at(const Refs *r, int i)  { return r->top[i < 0 ? 0 : (i > 2 * r->n - 1 ? 2 * r->n - 1 : i)]; }
static int left_at(const Refs *r, int i) { return r->left[i < 0 ? 0 : (i > 2 * r->n - 1 ? 2 * r->n - 1 : i)]; }
static int border(const Refs *r, int c) {
    if (c == 0) return r->corner;
    return c > 0 ? top_at(r, c - 1) : left_at(r, -c - 1);
}
static int border_half(const Refs *r, int twice) {
    int low = twice >= 0 ? twice / 2 : -((-twice + 1) / 2);
    if (twice - 2 * low == 0) return border(r, low);
    return avg2(border(r, low), border(r, low + 1));
}
static int top_half(const Refs *r, int twice) {
    int i = twice / 2;
    return twice % 2 == 0 ? top_at(r, i) : avg2(top_at(r, i), top_at(r, i + 1));
}
static int left_half(const Refs *r, int twice) {
    int i = twice / 2;
    return twice % 2 == 0 ? left_at(r, i) : avg2(left_at(r, i), left_at(r, i + 1));
}

static void predict(const Refs *r, int mode, int *out) {
    int n = r->n, dc = 128, top_sum = 0, left_sum = 0;
    for (int i = 0; i < n; i++) { top_sum += r->top[i]; left_sum += r->left[i]; }
    if (r->has_top && r->has_left) dc = (top_sum + left_sum + n) / (2 * n);
    else if (r->has_top) dc = (top_sum + n / 2) / n;
    else if (r->has_left) dc = (left_sum + n / 2) / n;
    for (int y = 0; y < n; y++)
        for (int x = 0; x < n; x++) {
            int v;
            switch (mode) {
            case DC: v = dc; break;
            case V:  v = r->top[x]; break;
            case H:  v = r->left[y]; break;
            case TM:
                if (n == 8)
                    v = ((n - 1 - x) * r->left[y] + (x + 1) * r->top[n] +
                         (n - 1 - y) * r->top[x] + (y + 1) * r->left[n] + n) / (2 * n);
                else
                    v = r->left[y] + r->top[x] - r->corner;
                break;
            case DL: v = avg3(top_at(r, x + y), top_at(r, x + y + 1), top_at(r, x + y + 2)); break;
            case DR: v = avg3(border(r, x - y - 1), border(r, x - y), border(r, x - y + 1)); break;
            case VR: v = border_half(r, 2 * x - y + 1); break;
            case HD: v = border_half(r, x - 2 * y - 1); break;
            case VL: v = top_half(r, 2 * x + y + 1); break;
            default: v = left_half(r, 2 * y + x + 1); break;
            }
            out[y * n + x] = clamp_byte(v);
        }
}

/* SATD scaled so that 4x4 and 8x8 blocks can be compared, as in article 31. */
static void hadamard(int *v, int n, int stride) {
    for (int span = 1; span < n; span *= 2)
        for (int first = 0; first < n; first += span * 2)
            for (int i = first; i < first + span; i++) {
                int a = v[i * stride], b = v[(i + span) * stride];
                v[i * stride] = a + b;
                v[(i + span) * stride] = a - b;
            }
}

static long satd(const int *error, int n) {
    int t[64];
    long total = 0;
    memcpy(t, error, sizeof(int) * n * n);
    for (int row = 0; row < n; row++) hadamard(t + row * n, n, 1);
    for (int col = 0; col < n; col++) hadamard(t + col, n, n);
    for (int i = 0; i < n * n; i++) total += labs((long)t[i]);
    return total * (8 / n);
}

/* ------------------------------------------------------------------------ */
/* Price tables: how many bits each symbol costs in each context.           */

#define COEF_CONTEXTS 26          /* 13 for 8x8 blocks and 13 for 4x4 ones */
#define MODE_CONTEXTS (MODES + 2)

static long coef_count[COEF_CONTEXTS][ALPHABET];
static long mode_count[MODE_CONTEXTS][ALPHABET];
static long split_count[3][ALPHABET];
static double coef_price[COEF_CONTEXTS][ALPHABET];
static double mode_price[MODE_CONTEXTS][ALPHABET];
static double split_price[3][ALPHABET];
static uint8_t mode_map[UNITS_X * UNITS_Y];   /* the mode of every 4x4 unit */

static int size_of(int value) {
    int magnitude = abs(value), bits = 0;
    while (magnitude) { bits++; magnitude >>= 1; }
    return bits < ALPHABET ? bits : ALPHABET - 1;
}

static int coef_context(int n, int k, int previous) {
    int band = n == 8 ? (k >= 6) + (k >= 15) + (k >= 28) : (k >= 3) + (k >= 6) + (k >= 10);
    int ctx = k == 0 ? 0 : 1 + band * 3 + (previous == 0 ? 0 : (previous <= 2 ? 1 : 2));
    return (n == 8 ? 0 : 13) + ctx;
}

static int mode_context(int ux, int uy) {
    int has_left = ux > 0, has_top = uy > 0;
    int left = has_left ? mode_map[uy * UNITS_X + ux - 1] : -1;
    int top = has_top ? mode_map[(uy - 1) * UNITS_X + ux] : -1;
    if (!has_left && !has_top) return 0;
    if (has_left && has_top && left != top) return MODES + 1;
    return 1 + (has_left ? left : top);
}

/* Estimated bits of one block of coefficients, from the price tables. */
static double block_bits(int n, const short *q) {
    double bits = 0.0;
    int previous = 0;
    for (int k = 0; k < n * n; k++) {
        int s = size_of(q[k]);
        bits += coef_price[coef_context(n, k, previous)][s] + s;
        previous = s;
    }
    return bits;
}

/* Turns counts into prices. Half a count is added to every symbol, so that
   a symbol never seen still has a finite (and high) price. */
static void counts_to_prices(long (*count)[ALPHABET], double (*price)[ALPHABET], int contexts) {
    for (int c = 0; c < contexts; c++) {
        double total = 0.0;
        for (int s = 0; s < ALPHABET; s++) total += count[c][s] + 0.5;
        for (int s = 0; s < ALPHABET; s++) price[c][s] = -log2((count[c][s] + 0.5) / total);
    }
}

/* ------------------------------------------------------------------------ */
/* Coding one block.                                                        */

typedef struct {
    short q[64];
    int guess[64];
    int pixels[64];       /* the rebuilt block */
    double sse, bits;
} Coded;

static void read_block(const uint8_t *image, int x0, int y0, int n, int *out) {
    for (int y = 0; y < n; y++)
        for (int x = 0; x < n; x++) out[y * n + x] = image[(y0 + y) * WIDTH + x0 + x];
}

static void rebuild(int n, Coded *c) {
    double coef[64], block[64];
    for (int k = 0; k < n * n; k++) coef[natural_at(n, k)] = (double)c->q[k] * step_at(n, k);
    transform(n, coef, block, 1);
    for (int i = 0; i < n * n; i++) c->pixels[i] = clamp_byte(c->guess[i] + (int)lrint(block[i]));
}

static double sse_of(int n, const int *a, const int *b) {
    double total = 0.0;
    for (int i = 0; i < n * n; i++) total += (double)(a[i] - b[i]) * (a[i] - b[i]);
    return total;
}

static void code(int n, const int *real, const int *guess, Coded *c) {
    double residual[64], coef[64], ideal[64];
    memcpy(c->guess, guess, sizeof(int) * n * n);
    for (int i = 0; i < n * n; i++) residual[i] = real[i] - guess[i];
    transform(n, residual, coef, 0);
    for (int k = 0; k < n * n; k++) {
        ideal[k] = coef[natural_at(n, k)] / step_at(n, k);
        c->q[k] = (short)lrint(ideal[k]);
    }
    rebuild(n, c);
    c->sse = sse_of(n, real, c->pixels);
    c->bits = block_bits(n, c->q);
}

static void paint(uint8_t *image, int x0, int y0, int n, const int *pixels) {
    for (int y = 0; y < n; y++)
        for (int x = 0; x < n; x++) image[(y0 + y) * WIDTH + x0 + x] = (uint8_t)pixels[y * n + x];
}

static void set_modes(int ux, int uy, int units, int mode) {
    for (int dy = 0; dy < units; dy++)
        for (int dx = 0; dx < units; dx++) mode_map[(uy + dy) * UNITS_X + ux + dx] = (uint8_t)mode;
}

/* ------------------------------------------------------------------------ */
/* The encoder.                                                             */

typedef struct {
    uint8_t split;
    uint8_t mode[4];
    short q[4][64];       /* q[0] holds the 8x8 block when not split */
} Cell;

static Cell cells[CELLS_X * CELLS_Y];

/* ------------------------------------------------------------------------ */
/* Segmentation: one class per 16x16 region and one scale per class.        */

#define REGIONS_X (WIDTH / 16)
#define CLASSES   4

typedef struct {
    const char *name;
    int segmented;        /* 0: no map at all */
    int policy;           /* how the four scales are chosen */
} Scheme;

enum { NEUTRAL, TEXTURE_COARSER, STRONGER, REVERSED, GENTLE };

static uint8_t region_class[REGIONS_X * REGIONS_X];
static int class_scale[CLASSES] = { 100, 100, 100, 100 };

static int pixel_or_neutral(const uint8_t *image, int x, int y) {
    return x < 0 || y < 0 ? 128 : image[y * WIDTH + x];
}

/* The difficulty score of example 1: the smallest guess error of each 8x8
   cell among DC, vertical, horizontal and TrueMotion, clipped per pixel. */
static long region_score(const uint8_t *image, int rx, int ry) {
    long total = 0;
    for (int c = 0; c < 4; c++) {
        int x0 = rx * 16 + (c % 2) * 8, y0 = ry * 16 + (c / 2) * 8, sum = 0;
        for (int i = 0; i < 8; i++) sum += pixel_or_neutral(image, x0 + i, y0 - 1) + pixel_or_neutral(image, x0 - 1, y0 + i);
        int dc = (sum + 8) / 16, corner = pixel_or_neutral(image, x0 - 1, y0 - 1);
        long best = -1;
        for (int mode = 0; mode < 4; mode++) {
            long error = 0;
            for (int y = 0; y < 8; y++)
                for (int x = 0; x < 8; x++) {
                    int top = pixel_or_neutral(image, x0 + x, y0 - 1), left = pixel_or_neutral(image, x0 - 1, y0 + y);
                    int guess = mode == 0 ? dc : mode == 1 ? top : mode == 2 ? left : left + top - corner;
                    int e = abs(image[(y0 + y) * WIDTH + x0 + x] - guess);
                    error += e > 32 ? 32 : e;
                }
            if (best < 0 || error < best) best = error;
        }
        total += best;
    }
    return total;
}

static int compare_long(const void *a, const void *b) {
    long x = *(const long *)a, y = *(const long *)b;
    return (x > y) - (x < y);
}

static int nearest_centre(long score, const long centre[CLASSES]) {
    int best = 0;
    for (int c = 1; c < CLASSES; c++)
        if (labs(score - centre[c]) < labs(score - centre[best])) best = c;
    return best;
}

static int clamp_scale(int s) { return s < 75 ? 75 : (s > 125 ? 125 : s); }

/* Builds the map from the original image and chooses the four scales. */
static void build_map(const uint8_t *image, int policy) {
    const int n = REGIONS_X * REGIONS_X;
    static long score[REGIONS_X * REGIONS_X], sorted[REGIONS_X * REGIONS_X];
    long centre[CLASSES];
    for (int i = 0; i < n; i++) score[i] = region_score(image, i % REGIONS_X, i / REGIONS_X);
    memcpy(sorted, score, sizeof(sorted));
    qsort(sorted, n, sizeof(long), compare_long);
    for (int c = 0; c < CLASSES; c++) centre[c] = sorted[(2 * c + 1) * n / (2 * CLASSES)];
    for (int round = 0; round < 20; round++) {
        long sum[CLASSES] = {0}, count[CLASSES] = {0};
        int moved = 0;
        for (int i = 0; i < n; i++) { int c = nearest_centre(score[i], centre); sum[c] += score[i]; count[c]++; }
        for (int c = 0; c < CLASSES; c++) {
            if (!count[c]) continue;
            long next = (sum[c] + count[c] / 2) / count[c];
            if (next != centre[c]) moved = 1;
            centre[c] = next;
        }
        if (!moved) break;
    }
    qsort(centre, CLASSES, sizeof(long), compare_long);
    double mean = 0.0, log_mean = 0.0;
    for (int i = 0; i < n; i++) {
        region_class[i] = (uint8_t)nearest_centre(score[i], centre);
        mean += centre[region_class[i]];
        log_mean += log(centre[region_class[i]] / 256.0 + 29.26);
    }
    mean /= n;
    log_mean /= n;
    long range = centre[CLASSES - 1] - centre[0];
    for (int c = 0; c < CLASSES; c++) {
        /* the first N.148i segmentation: distance from the average, with caps */
        int s = clamp_scale((int)lround(100 + (range ? 32.0 * (centre[c] - mean) / range : 0.0)));
        if (c == 0 && s > 88) s = 88;
        if (c == 1 && s > 95) s = 95;
        if (c == 3 && s > 118) s = 118;
        switch (policy) {
        case NEUTRAL:         class_scale[c] = 100; break;
        case TEXTURE_COARSER: class_scale[c] = s; break;
        case STRONGER:        class_scale[c] = clamp_scale(100 + 2 * (s - 100)); break;
        case REVERSED:        class_scale[c] = clamp_scale(100 - (s - 100)); break;
        default:              /* gentle: the eighth root of the difficulty */
            class_scale[c] = clamp_scale((int)lround(100.0 * exp((log(centre[c] / 256.0 + 29.26) - log_mean) / 8.0)));
            break;
        }
    }
}

/* Every block uses the scale of the 16x16 region it sits in. */
static void use_region_of(int x, int y) { current_scale = class_scale[region_class[(y / 16) * REGIONS_X + x / 16]]; }

/* Picks the best mode for one block and codes it: by SATD in the quick
   pass, by J = D + lambda * R otherwise. */
static double best_block(int use_satd, const uint8_t *original, const uint8_t *rebuilt,
                         int x0, int y0, int n, double lambda, uint8_t *mode, Coded *out) {
    int real[64], guess[64], error[64];
    double best = -1.0;
    Refs r = gather(rebuilt, x0, y0, n);
    read_block(original, x0, y0, n, real);
    int ctx = mode_context(x0 / 4, y0 / 4);
    for (int m = 0; m < MODES; m++) {
        predict(&r, m, guess);
        double score;
        if (use_satd) {
            for (int i = 0; i < n * n; i++) error[i] = real[i] - guess[i];
            score = (double)satd(error, n);
        } else {
            Coded c;
            code(n, real, guess, &c);
            score = c.sse + lambda * (c.bits + mode_price[ctx][m]);
        }
        if (best < 0.0 || score < best) { best = score; *mode = (uint8_t)m; }
    }
    predict(&r, *mode, guess);
    code(n, real, guess, out);
    if (use_satd) return best;
    return out->sse + lambda * (out->bits + mode_price[ctx][*mode]);
}

static void encode(const uint8_t *original, uint8_t *rebuilt, int use_satd, double lambda) {
    memset(done, 0, sizeof(done));
    memset(mode_map, 0, sizeof(mode_map));
    for (int cy = 0; cy < CELLS_Y; cy++)
        for (int cx = 0; cx < CELLS_X; cx++) {
            Cell *cell = &cells[cy * CELLS_X + cx];
            int x0 = cx * 8, y0 = cy * 8;
            use_region_of(x0, y0);
            int left = cx > 0 ? cells[cy * CELLS_X + cx - 1].split : 0;
            int top = cy > 0 ? cells[(cy - 1) * CELLS_X + cx].split : 0;

            Coded whole;
            uint8_t whole_mode;
            double whole_score = best_block(use_satd, original, rebuilt, x0, y0, 8, lambda, &whole_mode, &whole);
            if (!use_satd) whole_score += lambda * split_price[left + top][0];

            Coded quarter[4];
            uint8_t quarter_mode[4];
            double split_score = use_satd ? 0.0 : lambda * split_price[left + top][1];
            for (int s = 0; s < 4; s++) {
                int sx = x0 + (s % 2) * 4, sy = y0 + (s / 2) * 4;
                split_score += best_block(use_satd, original, rebuilt, sx, sy, 4, lambda, &quarter_mode[s], &quarter[s]);
                paint(rebuilt, sx, sy, 4, quarter[s].pixels);
                mark_done(sx, sy, 4, 1);
                set_modes(sx / 4, sy / 4, 1, quarter_mode[s]);
            }

            if (split_score < whole_score) {
                cell->split = 1;
                for (int s = 0; s < 4; s++) {
                    cell->mode[s] = quarter_mode[s];
                    memcpy(cell->q[s], quarter[s].q, sizeof(quarter[s].q));
                }
            } else {
                cell->split = 0;
                cell->mode[0] = whole_mode;
                memcpy(cell->q[0], whole.q, sizeof(whole.q));
                paint(rebuilt, x0, y0, 8, whole.pixels);
                mark_done(x0, y0, 8, 1);
                set_modes(x0 / 4, y0 / 4, 2, whole_mode);
            }
        }
}

/* The decoder gets only the cells and the map, and rebuilds everything. */
static void decode(uint8_t *image) {
    memset(done, 0, sizeof(done));
    for (int cy = 0; cy < CELLS_Y; cy++)
        for (int cx = 0; cx < CELLS_X; cx++) {
            const Cell *cell = &cells[cy * CELLS_X + cx];
            int count = cell->split ? 4 : 1, n = cell->split ? 4 : 8;
            use_region_of(cx * 8, cy * 8);
            for (int s = 0; s < count; s++) {
                int x0 = cx * 8 + (cell->split ? (s % 2) * 4 : 0);
                int y0 = cy * 8 + (cell->split ? (s / 2) * 4 : 0);
                Coded c;
                Refs r = gather(image, x0, y0, n);
                predict(&r, cell->mode[s], c.guess);
                memcpy(c.q, cell->q[s], sizeof(c.q));
                rebuild(n, &c);
                paint(image, x0, y0, n, c.pixels);
                mark_done(x0, y0, n, 1);
            }
        }
}

/* ------------------------------------------------------------------------ */
/* Counting the symbols that were really chosen, and the ideal size.        */

static void count_cells(void) {
    memset(coef_count, 0, sizeof(coef_count));
    memset(mode_count, 0, sizeof(mode_count));
    memset(split_count, 0, sizeof(split_count));
    for (int cy = 0; cy < CELLS_Y; cy++)
        for (int cx = 0; cx < CELLS_X; cx++) {
            const Cell *cell = &cells[cy * CELLS_X + cx];
            int left = cx > 0 ? cells[cy * CELLS_X + cx - 1].split : 0;
            int top = cy > 0 ? cells[(cy - 1) * CELLS_X + cx].split : 0;
            split_count[left + top][cell->split]++;
            for (int s = 0; s < (cell->split ? 4 : 1); s++) {
                int n = cell->split ? 4 : 8, previous = 0;
                int ux = cx * 2 + (cell->split ? s % 2 : 0), uy = cy * 2 + (cell->split ? s / 2 : 0);
                for (int k = 0; k < n * n; k++) {
                    int sym = size_of(cell->q[s][k]);
                    coef_count[coef_context(n, k, previous)][sym]++;
                    previous = sym;
                }
                mode_count[mode_context(ux, uy)][cell->mode[s]]++;
                set_modes(ux, uy, cell->split ? 1 : 2, cell->mode[s]);
            }
        }
}

static double ideal_bits(long (*count)[ALPHABET], int contexts) {
    double bits = 0.0;
    for (int c = 0; c < contexts; c++) {
        long total = 0;
        for (int s = 0; s < ALPHABET; s++) total += count[c][s];
        for (int s = 0; s < ALPHABET; s++)
            if (count[c][s]) bits += count[c][s] * -log2((double)count[c][s] / total);
    }
    return bits;
}

static double total_bytes(void) {
    double value_bits = 0.0;
    count_cells();
    for (int c = 0; c < CELLS_X * CELLS_Y; c++)
        for (int s = 0; s < (cells[c].split ? 4 : 1); s++)
            for (int k = 0; k < (cells[c].split ? 16 : 64); k++) value_bits += size_of(cells[c].q[s][k]);
    return (ideal_bits(coef_count, COEF_CONTEXTS) + value_bits +
            ideal_bits(mode_count, MODE_CONTEXTS) + ideal_bits(split_count, 3)) / 8.0;
}

static double psnr(const uint8_t *a, const uint8_t *b) {
    double se = 0.0;
    for (long i = 0; i < (long)WIDTH * HEIGHT; i++) se += (double)(a[i] - b[i]) * (a[i] - b[i]);
    return 10.0 * log10(255.0 * 255.0 / (se / ((double)WIDTH * HEIGHT)));
}

/* Cost of the map: each class written as (class - prediction) mod 4, where
   the prediction is the class on the left, or the one above at the start of
   a row, plus one byte for each of the four scales. */
static double map_bytes(void) {
    const int n = REGIONS_X * REGIONS_X;
    long symbols[CLASSES] = {0};
    for (int i = 0; i < n; i++) {
        int rx = i % REGIONS_X, ry = i / REGIONS_X;
        int prediction = i == 0 ? 1 : (rx > 0 ? region_class[i - 1] : region_class[(ry - 1) * REGIONS_X]);
        symbols[(region_class[i] - prediction + CLASSES) % CLASSES]++;
    }
    double bits = 0.0;
    for (int s = 0; s < CLASSES; s++)
        if (symbols[s]) bits += symbols[s] * -log2((double)symbols[s] / n);
    return bits / 8.0 + CLASSES;
}

/* SSIM over 8x8 windows that move 4 pixels at a time: it compares the
   average, the contrast and the pattern of each window with the original. */
static double ssim(const uint8_t *a, const uint8_t *b) {
    const double c1 = (0.01 * 255) * (0.01 * 255), c2 = (0.03 * 255) * (0.03 * 255);
    double total = 0.0;
    long windows = 0;
    for (int y0 = 0; y0 + 8 <= HEIGHT; y0 += 4)
        for (int x0 = 0; x0 + 8 <= WIDTH; x0 += 4) {
            double ma = 0, mb = 0, va = 0, vb = 0, cov = 0;
            for (int y = y0; y < y0 + 8; y++)
                for (int x = x0; x < x0 + 8; x++) { ma += a[y * WIDTH + x]; mb += b[y * WIDTH + x]; }
            ma /= 64; mb /= 64;
            for (int y = y0; y < y0 + 8; y++)
                for (int x = x0; x < x0 + 8; x++) {
                    double da = a[y * WIDTH + x] - ma, db = b[y * WIDTH + x] - mb;
                    va += da * da; vb += db * db; cov += da * db;
                }
            va /= 63; vb /= 63; cov /= 63;
            total += ((2 * ma * mb + c1) * (2 * cov + c2)) / ((ma * ma + mb * mb + c1) * (va + vb + c2));
            windows++;
        }
    return total / windows;
}

static double run(const uint8_t *image, uint8_t *rebuilt, uint8_t *decoded, const Scheme *sc,
                  double strength, double *quality, double *structure, int *same) {
    set_strength(strength);
    double lambda = 0.85 * QUANT8[0] * QUANT8[0];
    if (sc->segmented) build_map(image, sc->policy);
    else { memset(region_class, 0, sizeof(region_class)); for (int c = 0; c < CLASSES; c++) class_scale[c] = 100; }

    /* First pass: a quick SATD encode, whose symbols become the prices. */
    memset(rebuilt, 0, (size_t)WIDTH * HEIGHT);
    encode(image, rebuilt, 1, lambda);
    count_cells();
    counts_to_prices(coef_count, coef_price, COEF_CONTEXTS);
    counts_to_prices(mode_count, mode_price, MODE_CONTEXTS);
    counts_to_prices(split_count, split_price, 3);

    memset(rebuilt, 0, (size_t)WIDTH * HEIGHT);
    memset(decoded, 0, (size_t)WIDTH * HEIGHT);
    encode(image, rebuilt, 0, lambda);
    decode(decoded);
    *same = memcmp(rebuilt, decoded, (size_t)WIDTH * HEIGHT) == 0;
    *quality = psnr(image, decoded);
    *structure = ssim(image, decoded);
    return total_bytes() + (sc->segmented ? map_bytes() : 0.0);
}

static void compare(const char *metric, const Scheme *schemes, int count, double value[6][3],
                    double bytes[6][3], const double curve_value[5], const double curve_bytes[5],
                    const double strengths[3]) {
    printf("Bytes against no segmentation at the same %s (negative = smaller file)\n\n", metric);
    printf("  %-26s %10.1f %10.1f %10.1f\n", "strength", strengths[0], strengths[1], strengths[2]);
    for (int i = 1; i < count; i++) {
        printf("  %-26s", schemes[i].name);
        for (int t = 0; t < 3; t++) {
            double p = value[i][t];
            int segment = -1;
            for (int c = 0; c < 4; c++)
                if (p <= curve_value[c] && p >= curve_value[c + 1]) segment = c;
            if (segment < 0) { printf(" %10s", "-"); continue; }
            double f = (p - curve_value[segment + 1]) / (curve_value[segment] - curve_value[segment + 1]);
            double reference = exp(log(curve_bytes[segment + 1]) + f * (log(curve_bytes[segment]) - log(curve_bytes[segment + 1])));
            printf(" %+9.1f%%", 100.0 * (bytes[i][t] / reference - 1.0));
        }
        printf("\n");
    }
    printf("\n");
}

int main(void) {
    static uint8_t image[WIDTH * HEIGHT], rebuilt[WIDTH * HEIGHT], decoded[WIDTH * HEIGHT];
    init_basis();
    make_image(image);

    const Scheme schemes[] = {
        { "no segmentation (art. 32)", 0, NEUTRAL },
        { "map, all scales 100",       1, NEUTRAL },
        { "texture coarser",           1, TEXTURE_COARSER },
        { "texture coarser, stronger", 1, STRONGER },
        { "reversed: texture finer",   1, REVERSED },
        { "gentle (eighth root)",      1, GENTLE },
    };
    const int count = (int)(sizeof(schemes) / sizeof(schemes[0]));
    const double strengths[3] = { 0.5, 1.0, 2.0 };
    double bytes[6][3], quality[6][3], structure[6][3];

    /* The reference curves: no segmentation at five strengths. */
    const double curve_strengths[5] = { 0.25, 0.5, 1.0, 2.0, 4.0 };
    double curve_bytes[5], curve_psnr[5], curve_ssim[5];
    for (int t = 0; t < 5; t++) {
        int same;
        curve_bytes[t] = run(image, rebuilt, decoded, &schemes[0], curve_strengths[t],
                             &curve_psnr[t], &curve_ssim[t], &same);
    }

    for (int i = 1; i < count; i++) {
        build_map(image, schemes[i].policy);
        printf("%-26s scales %3d %3d %3d %3d\n", schemes[i].name,
               class_scale[0], class_scale[1], class_scale[2], class_scale[3]);
    }
    printf("\n");

    for (int t = 0; t < 3; t++) {
        printf("strength %.1f\n", strengths[t]);
        printf("  %-26s %8s %7s %8s  %s\n", "scheme", "bytes", "PSNR", "SSIM", "decoder");
        for (int i = 0; i < count; i++) {
            int same;
            bytes[i][t] = run(image, rebuilt, decoded, &schemes[i], strengths[t],
                              &quality[i][t], &structure[i][t], &same);
            printf("  %-26s %8.0f %7.2f %8.4f  %s\n", schemes[i].name, bytes[i][t],
                   quality[i][t], structure[i][t], same ? "same image" : "DIFFERENT");
        }
        printf("\n");
    }
    compare("PSNR", schemes, count, quality, bytes, curve_psnr, curve_bytes, strengths);
    compare("SSIM", schemes, count, structure, bytes, curve_ssim, curve_bytes, strengths);
    return 0;
}

Compile e rode com o comando do seu sistema:

# Linux
gcc -std=c99 -O2 -Wall segmentacao_laboratorio.c -o segmentacao_laboratorio -lm
./segmentacao_laboratorio

# macOS
clang -std=c99 -O2 -Wall segmentacao_laboratorio.c -o segmentacao_laboratorio
./segmentacao_laboratorio

# Windows (terminal MSYS2 UCRT64)
gcc -std=c99 -O2 -Wall segmentacao_laboratorio.c -o segmentacao_laboratorio.exe
./segmentacao_laboratorio.exe

# Windows (Developer Command Prompt do Visual Studio)
cl /O2 segmentacao_laboratorio.c
segmentacao_laboratorio.exe

O programa leva alguns segundos para terminar, e a saída será esta abaixo:

map, all scales 100        scales 100 100 100 100
texture coarser            scales  88  94 102 118
texture coarser, stronger  scales  76  88 104 125
reversed: texture finer    scales 112 106  98  82
gentle (eighth root)       scales  99  99 101 104

strength 0.5
  scheme                        bytes    PSNR     SSIM  decoder
  no segmentation (art. 32)     23754   35.92   0.9800  same image
  map, all scales 100           23867   35.92   0.9800  same image
  texture coarser               22983   35.01   0.9749  same image
  texture coarser, stronger     22248   34.73   0.9735  same image
  reversed: texture finer       25666   37.09   0.9842  same image
  gentle (eighth root)          23594   35.70   0.9790  same image

strength 1.0
  scheme                        bytes    PSNR     SSIM  decoder
  no segmentation (art. 32)     14344   32.05   0.9476  same image
  map, all scales 100           14458   32.05   0.9476  same image
  texture coarser               13049   31.61   0.9402  same image
  texture coarser, stronger     12637   31.48   0.9376  same image
  reversed: texture finer       16560   32.68   0.9566  same image
  gentle (eighth root)          14026   31.93   0.9458  same image

strength 2.0
  scheme                        bytes    PSNR     SSIM  decoder
  no segmentation (art. 32)      8321   29.89   0.9097  same image
  map, all scales 100            8434   29.89   0.9097  same image
  texture coarser                7554   29.78   0.9027  same image
  texture coarser, stronger      7426   29.79   0.9010  same image
  reversed: texture finer        9614   30.11   0.9169  same image
  gentle (eighth root)           8203   29.86   0.9086  same image

Bytes against no segmentation at the same PSNR (negative = smaller file)

  strength                          0.5        1.0        2.0
  map, all scales 100             +0.5%      +0.8%      +1.4%
  texture coarser                 +8.9%      +1.8%      -4.8%
  texture coarser, stronger       +9.3%      +1.7%      -6.9%
  reversed: texture finer         +1.4%      +6.4%      +9.4%
  gentle (eighth root)            +2.2%      +0.9%      -0.2%

Bytes against no segmentation at the same SSIM (negative = smaller file)

  strength                          0.5        1.0        2.0
  map, all scales 100             +0.5%      +0.8%      +1.4%
  texture coarser                 +4.7%      +1.2%      +1.0%
  texture coarser, stronger       +3.7%      +1.7%      +1.9%
  reversed: texture finer         -1.8%      +0.3%      +4.2%
  gentle (eighth root)            +1.0%      +0.4%      +0.2%

Lendo o segundo experimento

Vamos ler as duas tabelas do final, um esquema de cada vez.

O mapa tem um preço

Com todas as escalas em 100, a imagem sai idêntica ao ponto de partida, e mesmo assim o arquivo fica entre 0,5% e 1,4% maior, que representa apenas o custo de gravar o mapa e as escalas.

Esse é o tamanho do buraco que qualquer escolha de escalas precisa tapar antes de começar a dar lucro. 💸

Textura mais grossa: só ajuda quando os bits estão caros

A ideia do mascaramento economizou bytes de verdade, mas também derrubou o PSNR, e na comparação com a mesma qualidade ela só ganhou na intensidade 2,0, com 4,8% de economia, enquanto nas outras duas ficou pior, chegando a 8,9% a mais na intensidade 0,5.

Pelo SSIM, ela ficou pior nas três intensidades, e a versão com o dobro da força repetiu o mesmo padrão, ganhando um pouco mais no PSNR da intensidade 2,0 e perdendo no resto.

O contrário também não resolve

Deixar a textura mais fina e o céu mais grosso piorou o PSNR em todas as intensidades, chegando a 9,4% a mais, e só ajudou o SSIM na qualidade mais alta.

O suave quase não mexe

A versão com a raiz oitava ficou praticamente empatada com o ponto de partida, entre 0,2% de economia e 2,2% a mais, e isso faz sentido, porque com escalas entre 99 e 104 a imagem quase não muda, e o que aparece é basicamente o custo do mapa.

O que o laboratório não consegue medir

A segmentação aposta no olho humano, e as nossas duas réguas enxergam pouco do mascaramento: o PSNR trata um erro na grama exatamente igual a um erro no céu, e o SSIM olha janelas pequenas sem saber o quanto um erro chama atenção para uma pessoa.

Então o laboratório mostra o custo da ideia com bastante clareza, mas não consegue mostrar todo o possível benefício, e para isso é preciso usar métricas que tentam imitar o olho humano, que é exatamente o que o N.148i fez.

E no N.148i, como ficou?

A ideia de quantizar cada região de um jeito foi testada duas vezes no N.148i, com métodos diferentes, e as duas histórias nos ensinaram bastante.

Primeira tentativa: a quantização adaptativa

A primeira versão entrou na quinta etapa da Fase 5, com quatro multiplicadores normativos, de 0,90, 0,97, 1,08 e 1,18, escolhidos para cada região de 16x16 e aplicados tanto ao brilho quanto à cor.

Para medir a agitação, ela usava a curvatura da imagem, que é quanto o brilho muda de direção de um pixel para o outro, porque isso separa uma textura densa de um degradê suave melhor do que medir só a variação.

Métrica        │ Diferença
───────────────┼────────────
PSNR (RGB)     │ +3,72%   pior
PSNR (Y)       │ +3,95%   pior
SSIM           │ +0,70%   pior
MS-SSIM        │ -0,22%
SSIMULACRA2    │ -0,80%
Butteraugli    │ -0,35%

As três métricas perceptuais melhoraram um pouco, mas o PSNR piorou bastante, e por isso a ferramenta ficou só como experimento opcional, desligada no perfil padrão.

O tropeço mais interessante dessa etapa veio antes: o primeiro detector de agitação usava a média das diferenças entre vizinhos, e ele melhorava o MS-SSIM em 4,10% nas três imagens de ajuste, mas nas dez imagens, mesmo com multiplicadores mais suaves, o Butteraugli piorou 1,74%.

A causa era que esse detector confundia bordas fortes com textura, então ele engrossava a quantização justamente em cima dos contornos, que são o primeiro lugar para onde o olho humano olha. 👀

O primeiro detector do N.148i confundia bordas fortes com textura, e engrossava a quantização justamente onde o olho mais presta atenção.

Segunda tentativa: a segmentação de verdade

A segunda versão veio na rodada da cor, já com o desenho do nosso primeiro experimento: análise da imagem inteira, nota de dificuldade pelo menor erro dos quatro palpites clássicos, agrupamento em quatro tipos ordenados, mapa gravado pela diferença com o vizinho e quatro escalas entre 75 e 125 guardadas no arquivo, aplicadas só ao brilho.

A calibração em três imagens já mostrava o dilema:

Escalas (tipo 0 → 3)       │ RGB      │ Y        │ MS-SSIM  │ Observação
───────────────────────────┼──────────┼──────────┼──────────┼──────────────────────────
100, 100, 100, 100         │ +0,60%   │    -     │    -     │ só o custo do mapa
94, 98, 103, 108           │ +1,61%   │ +2,30%   │ -0,89%   │ suave
88, 95, 106, 118           │ +3,38%   │ +4,90%   │ -2,50%   │ mais forte
ao contrário               │ -1,04%   │ -3,26%   │ +6,11%   │ ganha PSNR, perde o resto

A última linha é a troca que o projeto tinha proibido desde o começo: recuperar o PSNR entregando de volta a vantagem nas métricas perceptuais, que pioraram entre 2,5% e 6,4%.

A versão escolhida para o teste oficial parecia promissora nas três imagens, com as três métricas perceptuais melhorando cerca de 3%, entretanto, olhando as dez imagens o resultado foi outro:

Métrica        │ Diferença  │ Imagem por imagem
───────────────┼────────────┼───────────────────
PSNR (RGB)     │ +3,36%     │ perdeu nas 10
PSNR (Y)       │ +3,98%     │ perdeu nas 10
SSIM           │ -0,20%     │ empate
MS-SSIM        │ -1,80%     │ ganhou em 6
SSIMULACRA2    │ -1,93%     │ ganhou em 5
Butteraugli    │ +4,36%     │ perdeu em 7

O registro anotou que a calibração em três imagens não se generalizou: o PSNR perdeu em todas as imagens, e o Butteraugli, que tinha melhorado no ajuste, piorou mais de 4% no teste completo, então a segmentação também foi rejeitada do perfil padrão.

Logo depois, o filtro em laço que usava o tipo de cada região para escolher a sua força, que vimos no artigo 34, também foi testado e rejeitado.

A volta pela porta lateral

A história não termina aí, porque no perfil padrão final do N.148i V2 a segmentação está ligada, só que de um jeito bem diferente 😉

Uma das tabelas de quantização de brilho que vamos conhecer no próximo artigo, a tabela estrutural, exige que o mapa de segmentos exista, e o encoder do perfil padrão monta o mapa pela variância de cada região, ou pelo erro dos palpites quando ele é menor, com escalas calculadas pela raiz oitava da dificuldade, bem parecidas com as do nosso esquema mais suave.

Ou seja, a ideia de quatro quantizações bem diferentes foi rejeitada duas vezes, e o que sobreviveu foi a estrutura do mapa no formato, usada com muita delicadeza e a serviço de outra ferramenta.

E isso só foi possível por causa daquela porta que o formato deixou aberta: o decoder sempre leu só o mapa e as escalas, então um encoder novo pôde mudar completamente o jeito de escolher os tipos sem mudar o decoder.

Resumo

Recapitulando:

  • O mascaramento visual faz os erros sumirem dentro de texturas e aparecerem em regiões lisas, como uma mancha numa camisa lisa ou estampada.
  • A quantização adaptativa usa passos menores nas regiões lisas e maiores nas agitadas, gastando os bits onde o olho vê.
  • A segmentação divide a imagem em regiões de 16x16, mede a dificuldade de cada uma e as separa em quatro tipos com o k-médias.
  • Cada tipo recebe uma escala que multiplica os passos de quantização, e o mapa é gravado pela diferença com o vizinho, custando menos de um bit por região.
  • No laboratório, só o mapa já custou entre 0,5% e 1,4%, e engrossar a textura só compensou quando os bits estavam caros.
  • O PSNR e o SSIM enxergam pouco do mascaramento, então a ideia precisa ser julgada com métricas que tentam imitar o olho.
  • No N.148i, a quantização adaptativa melhorou as métricas perceptuais um pouco, mas piorou o PSNR em 3,72%, e ficou desligada.
  • A segmentação de verdade parecia ótima em três imagens e, nas dez, perdeu no PSNR em todas e piorou o Butteraugli em 4,36%.
  • Confundir bordas com textura foi um dos tropeços, porque as bordas são o primeiro lugar para onde o olho humano olha.
  • O mapa de segmentos voltou no perfil final, com escalas bem suaves, como parte da tabela estrutural do próximo artigo.

Ao longo desta fase, a tabela de quantização do brilho foi a mesma do JPEG desde o artigo 10, e a rodada da cor terminou dizendo que o próximo passo precisava mirar justamente a luminância.

No próximo artigo vamos trocar essa tabela por três tabelas novas, uma calibrada, uma espectral e uma estrutural, todas pensadas para o resíduo da predição, e não para a imagem original como no JPEG.

Prepara o café ☕, porque a velha tabela do JPEG vai se aposentar 😂

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.