| 1 |
#!/usr/bin/env python3 |
| 2 |
|
| 3 |
import argparse |
| 4 |
import math |
| 5 |
|
| 6 |
|
| 7 |
# Note: we use a pure gamma 2.2 function, rather than the piece-wise |
| 8 |
# sRGB transfer function, since that is what all compositors do. |
| 9 |
|
| 10 |
def srgb_to_linear(f: float) -> float: |
| 11 |
assert(f >= 0 and f <= 1.0) |
| 12 |
return math.pow(f, 2.2) |
| 13 |
|
| 14 |
|
| 15 |
def linear_to_srgb(f: float) -> float: |
| 16 |
return math.pow(f, 1 / 2.2) |
| 17 |
|
| 18 |
|
| 19 |
def main() -> None: |
| 20 |
parser = argparse.ArgumentParser() |
| 21 |
parser.add_argument('c_output', type=argparse.FileType('w')) |
| 22 |
parser.add_argument('h_output', type=argparse.FileType('w')) |
| 23 |
opts = parser.parse_args() |
| 24 |
|
| 25 |
linear_table: list[int] = [] |
| 26 |
|
| 27 |
for i in range(256): |
| 28 |
linear_table.append(int(srgb_to_linear(float(i) / 255) * 65535 + 0.5)) |
| 29 |
|
| 30 |
|
| 31 |
opts.h_output.write("#pragma once\n") |
| 32 |
opts.h_output.write("#include <stdint.h>\n") |
| 33 |
opts.h_output.write("\n") |
| 34 |
opts.h_output.write('/* 8-bit input, 16-bit output */\n') |
| 35 |
opts.h_output.write("extern const uint16_t srgb_decode_8_to_16_table[256];") |
| 36 |
|
| 37 |
opts.h_output.write('\n') |
| 38 |
opts.h_output.write('static inline uint16_t\n') |
| 39 |
opts.h_output.write('srgb_decode_8_to_16(uint8_t v)\n') |
| 40 |
opts.h_output.write('{\n') |
| 41 |
opts.h_output.write(' return srgb_decode_8_to_16_table[v];\n') |
| 42 |
opts.h_output.write('}\n') |
| 43 |
|
| 44 |
opts.h_output.write('\n') |
| 45 |
opts.h_output.write('/* 8-bit input, 8-bit output */\n') |
| 46 |
opts.h_output.write("extern const uint8_t srgb_decode_8_to_8_table[256];\n") |
| 47 |
|
| 48 |
opts.h_output.write('\n') |
| 49 |
opts.h_output.write('static inline uint8_t\n') |
| 50 |
opts.h_output.write('srgb_decode_8_to_8(uint8_t v)\n') |
| 51 |
opts.h_output.write('{\n') |
| 52 |
opts.h_output.write(' return srgb_decode_8_to_8_table[v];\n') |
| 53 |
opts.h_output.write('}\n') |
| 54 |
|
| 55 |
opts.c_output.write('#include "srgb.h"\n') |
| 56 |
opts.c_output.write('\n') |
| 57 |
|
| 58 |
opts.c_output.write("const uint16_t srgb_decode_8_to_16_table[256] = {\n") |
| 59 |
for i in range(256): |
| 60 |
opts.c_output.write(f' {linear_table[i]},\n') |
| 61 |
opts.c_output.write('};\n') |
| 62 |
|
| 63 |
opts.c_output.write("const uint8_t srgb_decode_8_to_8_table[256] = {\n") |
| 64 |
for i in range(256): |
| 65 |
opts.c_output.write(f' {linear_table[i] >> 8},\n') |
| 66 |
opts.c_output.write('};\n') |
| 67 |
|
| 68 |
|
| 69 |
if __name__ == '__main__': |
| 70 |
main() |