okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-5b adfcf9028 into f-own-int (round 16: the strata-image test program and its parts, DiT runner, sampler, noise, PNG writer; hooked into no build)e4309aaf3

main
4.8 KiB128 linesraw
1// src/image/png/png_write.cpp - see include/strata/image/png_write.hpp.
2#include "strata/image/png_write.hpp"
3
4#include <algorithm>
5#include <array>
6#include <cstddef>
7#include <cstdio>
8#include <cstring>
9
10namespace strata::image {
11namespace {
12
13const std::array<uint32_t, 256>& crc_table() {
14    static const std::array<uint32_t, 256> t = [] {
15        std::array<uint32_t, 256> r{};
16        for (uint32_t i = 0; i < 256; ++i) {
17            uint32_t c = i;
18            for (int k = 0; k < 8; ++k) c = (c & 1u) ? 0xEDB88320u ^ (c >> 1) : c >> 1;
19            r[i] = c;
20        }
21        return r;
22    }();
23    return t;
24}
25
26void put32(std::vector<uint8_t>& o, uint32_t v) {
27    o.push_back((uint8_t) (v >> 24));
28    o.push_back((uint8_t) (v >> 16));
29    o.push_back((uint8_t) (v >> 8));
30    o.push_back((uint8_t) v);
31}
32
33// one chunk: length, type, data, CRC over type + data
34void chunk(std::vector<uint8_t>& o, const char type[4], const uint8_t* data, size_t n) {
35    put32(o, (uint32_t) n);
36    const size_t at = o.size();
37    o.insert(o.end(), type, type + 4);
38    if (n) o.insert(o.end(), data, data + n);
39    put32(o, png_crc32(o.data() + at, n + 4));
40}
41
42}  // namespace
43
44uint32_t png_crc32(const uint8_t* p, size_t n, uint32_t crc) {
45    const auto& t = crc_table();
46    uint32_t c = crc ^ 0xFFFFFFFFu;
47    for (size_t i = 0; i < n; ++i) c = t[(c ^ p[i]) & 0xFFu] ^ (c >> 8);
48    return c ^ 0xFFFFFFFFu;
49}
50
51uint32_t png_adler32(const uint8_t* p, size_t n, uint32_t a) {
52    uint32_t s1 = a & 0xFFFFu, s2 = a >> 16;
53    while (n > 0) {
54        const size_t k = n < 5552 ? n : 5552;   // the largest run before the sums can overflow 32 bits
55        for (size_t i = 0; i < k; ++i) {
56            s1 += p[i];
57            s2 += s1;
58        }
59        s1 %= 65521u;
60        s2 %= 65521u;
61        p += k;
62        n -= k;
63    }
64    return (s2 << 16) | s1;
65}
66
67std::vector<uint8_t> png_encode(const uint8_t* pixels, int w, int h, int channels, const std::string& parameters) {
68    if (w <= 0 || h <= 0 || (channels != 1 && channels != 3 && channels != 4)) return {};
69    // the raw stream: per row the filter byte 0, then the row's bytes
70    const size_t row = (size_t) w * channels;
71    std::vector<uint8_t> raw;
72    raw.reserve((row + 1) * h);
73    for (int y = 0; y < h; ++y) {
74        raw.push_back(0);
75        raw.insert(raw.end(), pixels + (size_t) y * row, pixels + (size_t) (y + 1) * row);
76    }
77    // zlib: CMF 0x78 (deflate, 32 KB window), FLG 0x01 (fastest; 0x7801 % 31 == 0), stored blocks of <= 65535 bytes,
78    // Adler-32 of the raw stream, big-endian
79    std::vector<uint8_t> z{0x78, 0x01};
80    for (size_t at = 0;;) {   // raw holds at least one row
81        const size_t len = std::min<size_t>(65535, raw.size() - at);
82        const bool last = at + len == raw.size();
83        z.push_back(last ? 1 : 0);                 // BFINAL, BTYPE 00 (stored); the rest of the byte is padding
84        z.push_back((uint8_t) len);
85        z.push_back((uint8_t) (len >> 8));
86        z.push_back((uint8_t) ~len);
87        z.push_back((uint8_t) (~len >> 8));
88        z.insert(z.end(), raw.begin() + (ptrdiff_t) at, raw.begin() + (ptrdiff_t) (at + len));
89        at += len;
90        if (last) break;
91    }
92    const uint32_t ad = png_adler32(raw.data(), raw.size());
93    put32(z, ad);
94
95    static const uint8_t sig[8] = {0x89, 'P', 'N', 'G', '\r', '\n', 0x1A, '\n'};
96    static const uint8_t ctype[5] = {0, 0, 4, 2, 6};   // by channel count: grey, grey+alpha, RGB, RGBA
97    std::vector<uint8_t> o(sig, sig + 8);
98    uint8_t ihdr[13];
99    for (int i = 0; i < 4; ++i) {
100        ihdr[i] = (uint8_t) ((uint32_t) w >> (24 - 8 * i));
101        ihdr[4 + i] = (uint8_t) ((uint32_t) h >> (24 - 8 * i));
102    }
103    ihdr[8] = 8;                      // bit depth
104    ihdr[9] = ctype[channels];
105    ihdr[10] = ihdr[11] = ihdr[12] = 0;   // deflate, adaptive filtering (type 0 per row), no interlace
106    chunk(o, "IHDR", ihdr, 13);
107    if (!parameters.empty()) {        // as stb_image_write in sd.cpp: keyword "parameters", a NUL, the text
108        std::vector<uint8_t> t((const uint8_t*) "parameters", (const uint8_t*) "parameters" + 10);
109        t.push_back(0);
110        t.insert(t.end(), parameters.begin(), parameters.end());
111        chunk(o, "tEXt", t.data(), t.size());
112    }
113    chunk(o, "IDAT", z.data(), z.size());
114    chunk(o, "IEND", nullptr, 0);
115    return o;
116}
117
118std::string png_write_file(const std::string& path, const uint8_t* pixels, int w, int h, int channels,
119                           const std::string& parameters) {
120    const std::vector<uint8_t> png = png_encode(pixels, w, h, channels, parameters);
121    if (png.empty()) return "png_write: bad image shape";
122    FILE* f = std::fopen(path.c_str(), "wb");
123    if (!f) return "png_write: cannot create " + path;
124    const bool ok = std::fwrite(png.data(), 1, png.size(), f) == png.size();
125    return std::fclose(f) == 0 && ok ? std::string() : "png_write: cannot write " + path;
126}
127
128}  // namespace strata::image