Tabelas de quantização para o resíduo: calibrada, espectral e estrutural

Tabelas de quantização para o resíduo: calibrada, espectral e estrutural

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

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

Desde o artigo 10, o brilho das nossas imagens é quantizado com a tabela de luminância do JPEG, e nesse tempo todo o codec mudou quase tudo em volta dela: ganhou predição, RDO, blocos de tamanhos diferentes, filtro em laço e uma cor bem mais cuidadosa.

Só que a tabela continuou a mesma, e no final do artigo 35 o próprio registro do N.148i avisou que o próximo ganho precisava vir justamente do brilho.

Hoje vamos aposentar a tabela do JPEG e conhecer as três tabelas que tomaram o lugar dela no N.148i: a calibrada, a espectral e a estrutural. 📏

Sendo assim, pega o café e vem comigo! ☕

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.

Uma roupa feita para outra pessoa

A tabela do JPEG foi criada há mais de trinta anos, a partir de testes com pessoas olhando imagens, para quantizar a DCT de blocos da própria foto.

Ela tem passos pequenos nas frequências baixas e passos bem grandes nas frequências altas, porque o olho humano percebe pouco os detalhes muito finos, então fazia sentido economizar justamente ali.

Só que, com a predição, o N.148i não aplica a DCT no bloco da foto: ele aplica no resíduo, que é o que sobrou depois do palpite, e o resíduo é um sinal bem diferente.

O palpite já cuidou do brilho médio e de boa parte das variações suaves, então as frequências baixas do resíduo ficam bem menores do que eram na foto, e usar a tabela do JPEG nesse sinal é como vestir uma roupa feita sob medida para outra pessoa. 👔

A pergunta que eu levanto neste artigo é bem simples: se o sinal mudou, qual deveria ser a tabela?

A tabela do JPEG foi feita sob medida para a DCT da própria foto, e o resíduo da predição é um sinal bem diferente.

Medir antes de cortar o tecido

Um alfaiate não corta a roupa antes de tirar as medidas (ao menos que o mesmo seja um gênio incompreendido), e com a tabela de quantização vale a mesma regra: antes de criar uma tabela nova, é preciso medir o resíduo de verdade.

A medida mais útil é o desvio padrão de cada uma das 64 frequências, que diz o tamanho típico daquele coeficiente: quando ele é grande, o coeficiente costuma ter valores altos, e quando ele é pequeno, o coeficiente quase sempre fica perto de zero.

Antes de criar uma tabela nova, o codec mede o tamanho típico de cada uma das 64 frequências do resíduo.

Com essas medidas na mão, existe um jeito bem direto de montar uma tabela, chamado aqui de tabela estatística: cada passo fica proporcional ao desvio padrão da sua frequência, mantendo o passo do DC igual ao do JPEG.

Só que seguir só a estatística ignora tudo o que o JPEG aprendeu sobre o olho humano, então uma alternativa mais cuidadosa é misturar as duas tabelas, ficando com uma parte de cada uma.

Misturando duas tabelas

A mistura usada pelo N.148i é uma mistura geométrica, que funciona por multiplicação, e não por soma:

mistura = (tabela do JPEG)^(1 - a) · (tabela estatística)^a

a = 0      →  a tabela do JPEG, sem mudar nada
a = 0,125  →  12,5% do caminho em direção à estatística
a = 0,25   →  25% do caminho
a = 1      →  a tabela estatística pura

A mistura geométrica é melhor que a média comum para passos de quantização, porque ela trata dobrar um passo e cortar um passo pela metade como mudanças do mesmo tamanho.

Pensa em misturar duas tintas: com 12,5% de amarelo num balde de azul, a tinta continua parecendo azul, só que com um tom um pouco diferente, e é assim que a tabela calibrada do N.148i nasceu. 🎨

A tabela calibrada é uma mistura: quase toda a tabela do JPEG, com 12,5% do caminho em direção à tabela tirada do resíduo.

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-tabelas, 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 pow 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: medindo o resíduo

O primeiro programa pega a imagem do laboratório e, para cada bloco de 8x8, calcula a DCT duas vezes: uma vez do próprio bloco, como o JPEG faz, e outra vez do resíduo que sobra depois do melhor dos quatro palpites clássicos.

Para o exemplo ficar curto, os palpites usam os pixels vizinhos originais, sem quantização, já que aqui só queremos medir o formato do sinal.

A saída mostra seis tabelas de 8x8, sempre com o DC no canto de cima à esquerda e as frequências mais altas no canto de baixo à direita:

  • O desvio padrão da DCT dos próprios blocos, que é o que o JPEG enxerga.
  • O desvio padrão da DCT do resíduo, que é o que um codec com predição enxerga.
  • A tabela de luminância do JPEG.
  • A tabela estatística, com passos proporcionais ao desvio padrão do resíduo.
  • As misturas geométricas de 12,5% e de 25% entre a tabela do JPEG e a estatística.

Salve o arquivo como estatistica_do_residuo.c:

/*
 * estatistica_do_residuo.c
 *
 * Measures what the DCT really receives in a codec with prediction.
 *
 * For every 8x8 block of the laboratory image, the program computes the DCT
 * twice:
 *
 *   - of the block itself, as the JPEG does;
 *   - of the residual, after the best of the four classic guesses (DC,
 *     vertical, horizontal and TrueMotion) made from the pixels around it.
 *
 * Then it prints, for each of the 64 frequencies, the standard deviation of
 * the coefficients (how big they usually are), next to the JPEG luminance
 * table, and builds new tables from the measured residual:
 *
 *   statistical : steps proportional to the residual standard deviation,
 *                 with the same DC step as the JPEG table;
 *   blends      : a mix between the JPEG table and the statistical one.
 *
 * To keep the example short, the guesses use the original neighbors here.
 *
 * 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>

#define W  512
#define H  512
#define PI 3.14159265358979323846

static const int JPEG_LUMA[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 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 double basis[8][8];

static void dct(const double in[64], double out[64]) {
    double tmp[64];
    for (int y = 0; y < 8; y++)
        for (int u = 0; u < 8; u++) {
            double s = 0.0;
            for (int x = 0; x < 8; x++) s += basis[u][x] * in[y * 8 + x];
            tmp[y * 8 + u] = s;
        }
    for (int v = 0; v < 8; v++)
        for (int u = 0; u < 8; u++) {
            double s = 0.0;
            for (int y = 0; y < 8; y++) s += basis[v][y] * tmp[y * 8 + u];
            out[v * 8 + u] = s;
        }
}

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

static void print_table(const char *title, const double t[64], int decimals) {
    printf("%s\n", title);
    for (int v = 0; v < 8; v++) {
        printf("  ");
        for (int u = 0; u < 8; u++) printf(decimals ? "%7.2f" : "%5.0f", t[v * 8 + u]);
        printf("\n");
    }
    printf("\n");
}

int main(void) {
    static uint8_t image[W * H];
    double sum_block[64] = {0}, square_block[64] = {0};
    double sum_residual[64] = {0}, square_residual[64] = {0};
    long blocks = 0;
    for (int u = 0; u < 8; u++)
        for (int x = 0; x < 8; x++)
            basis[u][x] = (u == 0 ? sqrt(1.0 / 8) : sqrt(2.0 / 8)) * cos((2 * x + 1) * u * PI / 16);
    make_image(image);

    for (int by = 0; by < H / 8; by++)
        for (int bx = 0; bx < W / 8; bx++) {
            int x0 = bx * 8, y0 = by * 8;
            double block[64], coef[64], best_residual[64];
            for (int y = 0; y < 8; y++)
                for (int x = 0; x < 8; x++) block[y * 8 + x] = image[(y0 + y) * W + x0 + x] - 128.0;

            /* the best of the four classic guesses, by the smallest error */
            int sum = 0, corner = pixel(image, x0 - 1, y0 - 1);
            for (int i = 0; i < 8; i++) sum += pixel(image, x0 + i, y0 - 1) + pixel(image, x0 - 1, y0 + i);
            double best_error = -1.0;
            for (int mode = 0; mode < 4; mode++) {
                double residual[64], error = 0.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 ? (sum + 8) / 16 : mode == 1 ? top : mode == 2 ? left : left + top - corner;
                        guess = guess < 0 ? 0 : (guess > 255 ? 255 : guess);
                        residual[y * 8 + x] = image[(y0 + y) * W + x0 + x] - guess;
                        error += fabs(residual[y * 8 + x]);
                    }
                if (best_error < 0 || error < best_error) {
                    best_error = error;
                    for (int i = 0; i < 64; i++) best_residual[i] = residual[i];
                }
            }

            dct(block, coef);
            for (int i = 0; i < 64; i++) { sum_block[i] += coef[i]; square_block[i] += coef[i] * coef[i]; }
            dct(best_residual, coef);
            for (int i = 0; i < 64; i++) { sum_residual[i] += coef[i]; square_residual[i] += coef[i] * coef[i]; }
            blocks++;
        }

    double std_block[64], std_residual[64], jpeg[64], statistical[64], blend12[64], blend25[64];
    for (int i = 0; i < 64; i++) {
        double mb = sum_block[i] / blocks, mr = sum_residual[i] / blocks;
        std_block[i] = sqrt(square_block[i] / blocks - mb * mb);
        std_residual[i] = sqrt(square_residual[i] / blocks - mr * mr);
        jpeg[i] = JPEG_LUMA[i];
    }
    /* steps proportional to the residual, with the JPEG DC step */
    for (int i = 0; i < 64; i++) statistical[i] = JPEG_LUMA[0] * std_residual[i] / std_residual[0];
    /* geometric blends: jpeg^(1 - a) * statistical^a */
    for (int i = 0; i < 64; i++) {
        blend12[i] = pow(jpeg[i], 0.875) * pow(statistical[i], 0.125);
        blend25[i] = pow(jpeg[i], 0.75) * pow(statistical[i], 0.25);
    }

    printf("%ld blocks of 8x8\n\n", blocks);
    print_table("Standard deviation of the DCT of the blocks themselves (what the JPEG sees)", std_block, 1);
    print_table("Standard deviation of the DCT of the residual (what a codec with prediction sees)", std_residual, 1);
    print_table("JPEG luminance table", jpeg, 0);
    print_table("Statistical table: steps proportional to the residual, same DC step", statistical, 0);
    print_table("Blend with 12.5% of the statistical table", blend12, 0);
    print_table("Blend with 25% of the statistical table", blend25, 0);
    return 0;
}

Compile e rode com o comando do seu sistema:

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

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

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

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

E a saída será esta:

4096 blocks of 8x8

Standard deviation of the DCT of the blocks themselves (what the JPEG sees)
   345.42  52.88  27.61  13.99  13.49  11.33  13.02  11.79
    46.83  26.09  14.33  10.12   9.75   9.43   9.42   9.18
    28.29  15.16  10.69   9.38   9.37   9.34   9.15   9.23
    17.61  11.21   9.50   8.71   9.40   8.84   8.75   9.19
    14.44   9.90   9.44   9.00   9.18   8.93   8.86   8.66
    13.13   9.90   8.87   8.89   8.88   8.74   8.86   8.97
    14.00   9.97   9.40   9.27   9.01   9.16   8.76   9.03
    11.73   9.04   8.95   9.07   8.66   8.81   8.78   8.35

Standard deviation of the DCT of the residual (what a codec with prediction sees)
    43.58  33.30  17.70  12.15  11.85  11.59  11.54  11.66
    28.57  26.07  14.37  10.15   9.76   9.44   9.42   9.18
    17.48  15.15  10.70   9.39   9.38   9.34   9.15   9.23
    12.78  11.22   9.51   8.71   9.41   8.84   8.75   9.19
    11.55   9.91   9.45   8.99   9.18   8.94   8.86   8.66
    11.49   9.90   8.88   8.89   8.88   8.74   8.86   8.97
    12.26   9.98   9.39   9.27   9.01   9.16   8.76   9.03
    11.21   9.04   8.95   9.07   8.66   8.81   8.78   8.35

JPEG luminance table
     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

Statistical table: steps proportional to the residual, same DC step
     16   12    7    4    4    4    4    4
     10   10    5    4    4    3    3    3
      6    6    4    3    3    3    3    3
      5    4    3    3    3    3    3    3
      4    4    3    3    3    3    3    3
      4    4    3    3    3    3    3    3
      5    4    3    3    3    3    3    3
      4    3    3    3    3    3    3    3

Blend with 12.5% of the statistical table
     16   11    9   14   19   30   37   44
     12   12   12   15   20   41   42   39
     13   12   13   19   29   40   47   39
     12   14   17   22   36   58   54   43
     15   18   28   39   47   70   67   52
     19   26   39   44   54   67   73   61
     36   45   53   58   67   77   76   66
     50   61   62   64   72   65   67   64

Blend with 25% of the statistical table
     16   11    9   12   16   23   27   31
     12   11   11   13   16   29   29   27
     12   11   11   15   22   28   32   28
     11   12   14   17   26   38   36   30
     13   14   20   28   32   45   43   35
     16   20   27   30   36   44   47   40
     27   31   36   39   44   49   49   43
     35   40   41   42   46   42   43   42

Lendo o primeiro experimento

Compare as duas primeiras tabelas no canto de cima à esquerda: o DC dos próprios blocos tem desvio padrão de 345, e o DC do resíduo tem só 43,6, porque o palpite já tirou quase todo o brilho médio de cada bloco. 🎯

As frequências baixas também encolheram, como a primeira da linha de cima, que caiu de 52,9 para 33,3, e isso mostra que o palpite também cuidou das variações mais suaves.

Já as frequências altas praticamente não mudaram, ficando em torno de 9 nas duas tabelas, e o motivo é a grama do laboratório, feita de ruído puro, que nenhum palpite consegue prever.

Agora olha a tabela do JPEG: os passos sobem de 16 até mais de 100 nas frequências altas, enquanto o resíduo tem quase o mesmo tamanho em todas elas, então a tabela trata as frequências altas como se elas fossem muito menos importantes do que o sinal mostra.

A tabela estatística vai para o extremo oposto, com passos de 3 e 4 nas frequências altas, e as duas misturas ficam no meio do caminho, com a de 12,5% ainda bem parecida com o JPEG e a de 25% já bem mais baixa nas frequências altas.

Numa foto de verdade o resíduo é diferente do nosso laboratório, e no N.148i o desvio padrão caiu de 41,96 no DC para só 2,39 na última frequência, porque fotos têm muito menos ruído puro que a nossa grama.

Segundo experimento: oito tabelas no laboratório

Agora vamos codificar a imagem do laboratório com oito tabelas diferentes de luminância, todas usando a mesma regra de intensidade dos artigos anteriores:

Esquema                       │ De onde vem a tabela
──────────────────────────────┼──────────────────────────────────────────────────
JPEG table (art. 10 to 36)    │ a tabela do JPEG, usada até aqui
blend 12.5%                   │ mistura de 12,5% com a estatística do laboratório
blend 25%                     │ mistura de 25%
statistical 100%              │ a tabela estatística pura
flat (16 everywhere)          │ o mesmo passo, 16, em todas as frequências
N.148i calibrated             │ a tabela calibrada do N.148i V2
N.148i spectral               │ a tabela espectral do N.148i V2
N.148i structural             │ a tabela estrutural do N.148i V2

O programa mede o resíduo do próprio laboratório do mesmo jeito que o primeiro exemplo, e as três tabelas do N.148i entram como números copiados, então elas foram calibradas para outras imagens e para outro codec, e aqui estão só emprestadas.

Para cada intensidade, a saída mostra uma tabela com estas colunas:

  • bytes, PSNR e SSIM: o tamanho e as duas medidas de qualidade dos artigos anteriores.
  • grass detail: quanto da textura da grama sobreviveu, a mesma medida do artigo 32.
  • decoder: se o decoder chegou exatamente na mesma imagem que o encoder.

No final, duas tabelas comparam cada esquema com a tabela do JPEG para a mesma qualidade, uma pelo PSNR e outra pelo SSIM, e um traço quer dizer que a qualidade daquele esquema ficou fora da curva de comparação.

Salve o arquivo como tabelas_laboratorio.c:

/*
 * tabelas_laboratorio.c
 *
 * The laboratory program of article 32 (ten modes, planar, 4x4 blocks and
 * RDO), coded with eight different luminance quantization tables:
 *
 *   - the JPEG table, used by the laboratory since article 10;
 *   - three tables built from the residual this laboratory really produces
 *     (measured the same way as in the previous example): a 12.5% and a 25%
 *     blend with the JPEG table, and the pure statistical table;
 *   - a flat table, with the same step at every frequency;
 *   - three tables borrowed from N.148i V2: calibrated, spectral and
 *     structural.
 *
 * 4x4 blocks read every other entry of the 8x8 table, as in article 31.
 * Quality is measured with PSNR, SSIM and the grass detail of article 32.
 *
 * 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 double JPEG_LUMA[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
};
/* Three luminance tables of N.148i V2, copied as data. */
static const double N148_CALIBRATED[64] = {
    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
};
static const double N148_SPECTRAL[64] = {
    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
};
static const double N148_STRUCTURAL[64] = {
    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
};
static double QUANT_BASE[64];          /* the table of the current scheme */
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 step_at(int n, int k) { return n == 8 ? QUANT8[ZIGZAG8[k]] : QUANT4[ZIGZAG4[k]]; }
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];

/* ------------------------------------------------------------------------ */
/* Measuring the residual and building tables from it, as in example 1.     */

typedef struct {
    const char *name;
    int kind;
} Scheme;

enum { JPEG, BLEND_12, BLEND_25, STATISTICAL, FLAT, CALIBRATED, SPECTRAL, STRUCTURAL };

static double residual_std[64];

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

static void measure_residual(const uint8_t *image) {
    double sum[64] = {0}, square[64] = {0}, block[64], coef[64];
    long blocks = 0;
    for (int y0 = 0; y0 < HEIGHT; y0 += 8)
        for (int x0 = 0; x0 < WIDTH; x0 += 8) {
            int total = 0, corner = pixel_or_neutral(image, x0 - 1, y0 - 1);
            for (int i = 0; i < 8; i++) total += pixel_or_neutral(image, x0 + i, y0 - 1) + pixel_or_neutral(image, x0 - 1, y0 + i);
            double best_error = -1.0;
            for (int mode = 0; mode < 4; mode++) {
                double residual[64], error = 0.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 = clamp_byte(mode == 0 ? (total + 8) / 16 : mode == 1 ? top : mode == 2 ? left : left + top - corner);
                        residual[y * 8 + x] = image[(y0 + y) * WIDTH + x0 + x] - guess;
                        error += fabs(residual[y * 8 + x]);
                    }
                if (best_error < 0 || error < best_error) {
                    best_error = error;
                    for (int i = 0; i < 64; i++) block[i] = residual[i];
                }
            }
            transform(8, block, coef, 0);
            for (int i = 0; i < 64; i++) { sum[i] += coef[i]; square[i] += coef[i] * coef[i]; }
            blocks++;
        }
    for (int i = 0; i < 64; i++) {
        double mean = sum[i] / blocks;
        residual_std[i] = sqrt(square[i] / blocks - mean * mean);
    }
}

static void choose_table(int kind) {
    for (int i = 0; i < 64; i++) {
        double statistical = JPEG_LUMA[0] * residual_std[i] / residual_std[0];
        switch (kind) {
        case JPEG:        QUANT_BASE[i] = JPEG_LUMA[i]; break;
        case BLEND_12:    QUANT_BASE[i] = pow(JPEG_LUMA[i], 0.875) * pow(statistical, 0.125); break;
        case BLEND_25:    QUANT_BASE[i] = pow(JPEG_LUMA[i], 0.75) * pow(statistical, 0.25); break;
        case STATISTICAL: QUANT_BASE[i] = statistical; break;
        case FLAT:        QUANT_BASE[i] = JPEG_LUMA[0]; break;
        case CALIBRATED:  QUANT_BASE[i] = N148_CALIBRATED[i]; break;
        case SPECTRAL:    QUANT_BASE[i] = N148_SPECTRAL[i]; break;
        default:          QUANT_BASE[i] = N148_STRUCTURAL[i]; break;
        }
    }
}

/* 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;
            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 rebuilds everything by itself. */
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;
            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)));
}

/* 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;
}

/* How much of the grass texture survived, as in article 32. */
static double grass_detail(const uint8_t *original, const uint8_t *decoded) {
    double a = 0.0, b = 0.0;
    for (int y = HEIGHT / 2; y < HEIGHT - 1; y++)
        for (int x = 0; x < WIDTH / 2 - 1; x++) {
            int i = y * WIDTH + x;
            a += abs(original[i + 1] - original[i]) + abs(original[i + WIDTH] - original[i]);
            b += abs(decoded[i + 1] - decoded[i]) + abs(decoded[i + WIDTH] - decoded[i]);
        }
    return 100.0 * b / a;
}

static double run(const uint8_t *image, uint8_t *rebuilt, uint8_t *decoded, const Scheme *sc,
                  double strength, double *quality, double *structure, double *detail, int *same) {
    choose_table(sc->kind);
    set_strength(strength);
    double lambda = 0.85 * QUANT8[0] * QUANT8[0];

    /* 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);
    *detail = grass_detail(image, decoded);
    return total_bytes();
}

static void compare(const char *metric, const Scheme *schemes, int count, double value[8][3],
                    double bytes[8][3], const double curve_value[5], const double curve_bytes[5],
                    const double strengths[3]) {
    printf("Bytes against the JPEG table at the same %s (negative = smaller file)\n\n", metric);
    printf("  %-28s %10.1f %10.1f %10.1f\n", "strength", strengths[0], strengths[1], strengths[2]);
    for (int i = 1; i < count; i++) {
        printf("  %-28s", 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);
    measure_residual(image);

    const Scheme schemes[] = {
        { "JPEG table (art. 10 to 36)", JPEG },
        { "blend 12.5%",                BLEND_12 },
        { "blend 25%",                  BLEND_25 },
        { "statistical 100%",           STATISTICAL },
        { "flat (16 everywhere)",       FLAT },
        { "N.148i calibrated",          CALIBRATED },
        { "N.148i spectral",            SPECTRAL },
        { "N.148i structural",          STRUCTURAL },
    };
    const int count = (int)(sizeof(schemes) / sizeof(schemes[0]));
    const double strengths[3] = { 0.5, 1.0, 2.0 };
    double bytes[8][3], quality[8][3], structure[8][3];

    /* The reference curves: the JPEG table 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++) {
        double detail;
        int same;
        curve_bytes[t] = run(image, rebuilt, decoded, &schemes[0], curve_strengths[t],
                             &curve_psnr[t], &curve_ssim[t], &detail, &same);
    }

    for (int t = 0; t < 3; t++) {
        printf("strength %.1f\n", strengths[t]);
        printf("  %-28s %8s %7s %8s %13s  %s\n", "scheme", "bytes", "PSNR", "SSIM", "grass detail", "decoder");
        for (int i = 0; i < count; i++) {
            double detail;
            int same;
            bytes[i][t] = run(image, rebuilt, decoded, &schemes[i], strengths[t],
                              &quality[i][t], &structure[i][t], &detail, &same);
            printf("  %-28s %8.0f %7.2f %8.4f %12.1f%%  %s\n", schemes[i].name, bytes[i][t],
                   quality[i][t], structure[i][t], detail, 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 tabelas_laboratorio.c -o tabelas_laboratorio -lm
./tabelas_laboratorio

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

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

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

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

strength 0.5
  scheme                          bytes    PSNR     SSIM  grass detail  decoder
  JPEG table (art. 10 to 36)      23754   35.92   0.9800        100.6%  same image
  blend 12.5%                     26498   38.72   0.9888        103.0%  same image
  blend 25%                       29825   41.70   0.9937        101.7%  same image
  statistical 100%                50820   52.31   0.9977        100.0%  same image
  flat (16 everywhere)            33668   46.06   0.9961        100.3%  same image
  N.148i calibrated               22014   36.03   0.9802        103.7%  same image
  N.148i spectral                 22492   37.29   0.9847        104.6%  same image
  N.148i structural               22934   38.59   0.9880        102.9%  same image

strength 1.0
  scheme                          bytes    PSNR     SSIM  grass detail  decoder
  JPEG table (art. 10 to 36)      14344   32.05   0.9476         74.4%  same image
  blend 12.5%                     17453   33.38   0.9639         93.3%  same image
  blend 25%                       20688   35.77   0.9790        104.2%  same image
  statistical 100%                41846   48.10   0.9974        100.1%  same image
  flat (16 everywhere)            24825   40.35   0.9915        101.3%  same image
  N.148i calibrated               13146   31.82   0.9459         77.4%  same image
  N.148i spectral                 13669   32.17   0.9533         91.0%  same image
  N.148i structural               14151   32.84   0.9619        103.6%  same image

strength 2.0
  scheme                          bytes    PSNR     SSIM  grass detail  decoder
  JPEG table (art. 10 to 36)       8321   29.89   0.9097         47.6%  same image
  blend 12.5%                      9729   30.48   0.9230         58.2%  same image
  blend 25%                       11880   31.41   0.9421         76.8%  same image
  statistical 100%                32098   41.90   0.9949        100.4%  same image
  flat (16 everywhere)            15890   34.19   0.9702        106.4%  same image
  N.148i calibrated                6950   29.42   0.9007         44.5%  same image
  N.148i spectral                  6524   29.25   0.8976         44.7%  same image
  N.148i structural                5775   29.07   0.8921         42.1%  same image

Bytes against the JPEG table at the same PSNR (negative = smaller file)

  strength                            0.5        1.0        2.0
  blend 12.5%                       -4.2%      +2.3%      +0.8%
  blend 25%                         -8.3%     -11.2%      -2.6%
  statistical 100%                      -          -      -2.3%
  flat (16 everywhere)                  -     -17.8%     -16.1%
  N.148i calibrated                 -7.9%      -2.8%      +1.4%
  N.148i spectral                  -12.1%      -6.1%      +2.1%
  N.148i structural                -16.5%     -11.0%      -3.0%

Bytes against the JPEG table at the same SSIM (negative = smaller file)

  strength                            0.5        1.0        2.0
  blend 12.5%                       -8.7%      -5.6%      -3.4%
  blend 25%                         -7.9%     -11.6%     -10.4%
  statistical 100%                      -          -          -
  flat (16 everywhere)                  -     -19.4%     -22.1%
  N.148i calibrated                 -7.7%      -6.0%      -4.2%
  N.148i spectral                  -15.0%     -12.9%      -5.7%
  N.148i structural                -19.5%     -21.0%      -9.3%

Lendo o segundo experimento

Vamos ler as duas tabelas do final, porque elas comparam todo mundo com a mesma qualidade.

A estatística pura exagera

A tabela estatística pura deixou a imagem quase perfeita, com mais de 48 dB de PSNR na intensidade padrão, mas gastou três vezes mais bytes que a tabela do JPEG, e por isso quase sempre aparece com um traço: a qualidade dela ficou alta demais para caber na curva de comparação.

Seguir só o tamanho dos coeficientes leva a passos minúsculos nas frequências altas, e o arquivo explode.

As misturas e a tabela plana

A mistura de 25% economizou 11,2% pelo PSNR e 11,6% pelo SSIM na intensidade padrão, enquanto a de 12,5% ficou dividida, ganhando pelo SSIM e oscilando pelo PSNR.

E a grande surpresa foi a tabela plana, com o mesmo passo em todas as frequências: ela foi a melhor do laboratório pelo PSNR, com 17,8% de economia na intensidade padrão, e pelo SSIM ela economizou 19,4%, perdendo só para a tabela estrutural nessa mesma intensidade. 😮

Isso tem uma explicação conhecida: quando a régua é o erro de cada pixel, a forma mais eficiente de quantizar é usar o mesmo passo em todas as frequências, e a tabela do JPEG faz o contrário de propósito, porque ela foi feita para o olho humano, e não para o PSNR.

As tabelas do N.148i em ordem

As três tabelas emprestadas do N.148i melhoraram a cada versão, na mesma ordem em que nasceram: na intensidade padrão, pelo SSIM, a calibrada economizou 6,0%, a espectral 12,9% e a estrutural 21,0%.

Repara também na coluna grass detail da intensidade padrão: a tabela do JPEG deixou só 74,4% da textura da grama, e a estrutural manteve 103,6%, porque os passos das frequências altas dela são bem menores.

E a estrutural é, das três, a mais parecida com a tabela plana, com passos entre 17 e 54, enquanto a do JPEG vai de 10 até 121.

Por que o N.148i não usa a tabela plana?

Se a tabela plana foi tão bem, por que o N.148i não usa simplesmente o mesmo passo em tudo?

Porque o nosso laboratório tem dois pontos cegos: ele é em tons de cinza, então nenhum byte gasto no brilho faz falta para a cor, e as nossas duas réguas não tentam imitar o olho humano, que enxerga pouco as frequências mais altas.

No N.148i, os dois pontos cegos aparecem na hora, como você vai ver agora, e é por isso que as tabelas dele foram ficando mais planas aos poucos, protegendo as frequências baixas e sem nunca chegar no plano total.

O relevo das tabelas: a do JPEG sobe muito nas frequências altas, e as tabelas do N.148i foram ficando cada vez mais planas, sem chegar na tabela plana.

E no N.148i, como ficou?

A troca da tabela de brilho aconteceu em duas etapas: a tabela calibrada, numa rodada dedicada à luminância, e depois as tabelas espectral e estrutural, no formato 7, que é o formato final da V2.

A tabela calibrada

Antes de criar qualquer tabela, o N.148i ganhou um gancho interno que anota o resíduo depois da decisão final do RDO, e ele foi rodado nas dez imagens de desenvolvimento, em cinco qualidades, juntando 538.614 blocos de 8x8 e 281.144 blocos de 4x4.

No 8x8, o desvio padrão do resíduo caiu de 41,96 no DC para 2,39 na última frequência, enquanto os passos do JPEG sobem de 16 até 99 nessa mesma diagonal, ou seja, o sinal e a tabela andavam em direções opostas.

A primeira tabela derivada seguia o desvio padrão, com o DC do JPEG, e as misturas geométricas foram testadas em três imagens, primeiro mostrando que uma cópia exata da tabela do JPEG dava ganho zero em todos os canais, o que provou que a troca de tabela não mudava nada sozinha.

Candidata                          │ Y         │ Cor       │ MS-SSIM
───────────────────────────────────┼───────────┼───────────┼──────────
mistura de 12,5%                   │ -10,86%   │ +9,37%    │ +2,80%
mistura de 25%                     │ -19,06%   │ +22,58%   │ +8,15%
só as frequências baixas mais finas│  +4,29%   │    -      │ +2,51%
mistura de 12,5% vezes 1,4 (aceita)│  -6,89%   │ -7,94%    │ +1,90%

A mistura de 25% parecia fantástica para o brilho, com 19% de economia, mas ela gastava tantos bits no brilho que a cor piorava 22,6% e o MS-SSIM piorava 8,15%, que é exatamente o ponto cego do nosso laboratório em tons de cinza.

A versão aceita multiplica a mistura de 12,5% por 1,4, deixando todos os passos 40% maiores para devolver o equilíbrio entre o brilho e a cor, mas mantendo o formato novo das frequências, e o registro resumiu a lição assim: seguir cegamente a energia dos coeficientes, ou a ordem perceptual do JPEG, não basta!

Métrica        │ Ganho
───────────────┼──────────
PSNR (RGB)     │  -7,75%
PSNR (Y)       │  -7,42%
PSNR (Cb)      │ -10,15%
PSNR (Cr)      │ -10,28%
SSIM           │  -4,33%
MS-SSIM        │  -0,36%
SSIMULACRA2    │  +1,64%   empate na maioria das imagens
Butteraugli    │  -2,88%

Foi um dos maiores ganhos de uma única ferramenta em toda a Fase 5, e contra o WebP o RGB caiu de 20,90% para 11,46% atrás, e o brilho de 30,61% para 20,78% atrás. 🎉

O SSIMULACRA2 ficou como ressalva, com o resultado geral um pouco pior, mas com sete das dez imagens empatadas e sem significância estatística, e o registro anotou isso em vez de esconder.

Para conferir se a tabela não estava só decorando as imagens da calibração, ela foi medida em 20 imagens novas, e o ganho foi de 7,58% no RGB e 7,60% no brilho, praticamente igual ao teste oficial.

A tabela espectral

No formato 7, o N.148i ganhou uma tabela opcional chamada espectral, que segundo o próprio código tira bits das primeiras frequências e entrega para os detalhes finos do brilho, com um formato guiado por um diagnóstico da imagem reconstruída com o mesmo tamanho de arquivo.

Logo depois veio uma versão refinada, que aumenta em cerca de 8% os passos das frequências mais baixas, mantém os do meio e diminui em cerca de 4% os das frequências mais altas.

Tabela calibrada (formato 5)          Tabela espectral (formato 7)

22  15  14  20  28  44  53  60        26  17  16  20  28  44  53  48
16  16  18  23  29  58  58  53        19  19  18  23  29  58  46  42
18  16  19  27  42  56  65  53        21  16  19  27  42  45  52  42
18  20  25  32  51  80  73  57        18  20  25  32  41  64  58  46
21  25  39  55  65  96  90  67        21  25  39  44  52  77  72  46
27  36  54  61  74  91  95  77        27  36  43  49  59  73  65  52
49  60  71  77  89 101  97  81        49  48  57  62  71  69  66  55
67  80  82  83  92  82  82  77        54  64  66  66  63  56  56  52

Repara que o DC subiu de 22 para 26, enquanto o canto das frequências mais altas caiu de 77 para 52, e esse é o formato da troca: um pouco menos de precisão no brilho médio, em troca de bem mais detalhe fino.

A tabela estrutural

A última tabela, chamada estrutural, foi derivada da energia de erro das próprias funções de base do N.148i, quer dizer, de quanto erro nos pixels cada passo de cada frequência realmente produz, com seis frequências baixas protegidas.

Tabela estrutural (formato 7)

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

É a mais plana das tabelas do N.148i, com passos entre 17 e 54, e ela não anda sozinha: o formato exige que ela venha junto com o RDO, a cor calibrada, os blocos de 16x16 e o mapa de segmentos do artigo passado.

O encoder do perfil estrutural também toma algumas decisões próprias, como a segmentação suave pela raiz oitava, seis modos de predição candidatos no esforço padrão, um refinamento dos coeficientes com contexto e uma estimativa do erro do RGB que já considera a cor reconstruída.

A tabela estrutural faz parte do perfil padrão final do N.148i V2, que ainda acrescenta as duas reconstruções do próximo artigo por cima dela.

Para as tabelas espectral e estrutural, este artigo descreve o que o código e a especificação do formato garantem, e o ganho delas aparece somado com o resto da V2 no julgamento final do artigo 40, contra o JPEG, o WebP e o JPEG XL.

Resumo

Recapitulando:

  • A tabela do JPEG foi feita para a DCT da própria foto, e com a predição o N.148i quantiza o resíduo, que é um sinal bem diferente.
  • Medir o desvio padrão de cada frequência mostra o tamanho típico de cada coeficiente do resíduo.
  • A tabela estatística segue essas medidas, e a mistura geométrica fica no meio do caminho entre ela e a tabela do JPEG.
  • No primeiro experimento, a predição derrubou o DC de 345 para 43,6, mas não mexeu nas frequências altas da grama, que é ruído puro.
  • No laboratório, a tabela plana foi a melhor pelo PSNR e ficou entre as melhores pelo SSIM, porque essas réguas medem o erro de cada pixel e o laboratório não tem cor.
  • As tabelas do N.148i melhoraram na ordem em que nasceram, e a estrutural, a mais plana delas, economizou 21% pelo SSIM no laboratório.
  • No N.148i, a mistura de 25% ganhava 19% no brilho e piorava a cor em 22,6%, e a versão aceita foi a mistura de 12,5% multiplicada por 1,4.
  • A tabela calibrada rendeu 7,75% no RGB e 10% na cor, e o resultado se repetiu em 20 imagens novas.
  • A espectral troca precisão nas frequências baixas por detalhe fino, e a estrutural, derivada da energia de erro das bases do N.148i, faz parte do perfil padrão final.

Com as tabelas certas, o N.148i passou a guardar bem mais detalhe fino, mas a imagem ainda é reconstruída pelo decoder do jeito tradicional, juntando o palpite e o resíduo...

No próximo artigo vamos conhecer as duas últimas ferramentas da V2, a reconstrução balanceada e a reconstrução de detalhe, que formam o perfil padrão final do codec.

Prepara mais uma chícara café ☕, porque estamos chegando na reta final da Fase 5.

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.