]> git.sesse.net Git - narabu/blob - narabu-encoder.cpp
36804d616f70681f411af412961a23ac87a542b4
[narabu] / narabu-encoder.cpp
1 #include <stdio.h>
2 #include <stdint.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <assert.h>
6 #include <math.h>
7 #include <SDL2/SDL.h>
8 #include <SDL2/SDL_error.h>
9 #include <SDL2/SDL_video.h>
10 #include <epoxy/gl.h>
11
12 #include <algorithm>
13 #include <chrono>
14 #include <memory>
15 #include <numeric>
16 #include <random>
17 #include <vector>
18 #include <unordered_map>
19
20 #include <movit/util.h>
21
22 #include "util.h"
23
24 #define WIDTH 1280
25 #define HEIGHT 720
26 #define WIDTH_BLOCKS (WIDTH/8)
27 #define WIDTH_BLOCKS_CHROMA (WIDTH/16)
28 #define HEIGHT_BLOCKS (HEIGHT/8)
29 #define NUM_BLOCKS (WIDTH_BLOCKS * HEIGHT_BLOCKS)
30 #define NUM_BLOCKS_CHROMA (WIDTH_BLOCKS_CHROMA * HEIGHT_BLOCKS)
31
32 #define NUM_SYMS 256
33 #define ESCAPE_LIMIT (NUM_SYMS - 1)
34 #define BLOCKS_PER_STREAM 320
35
36 static constexpr uint32_t prob_bits = 12;
37 static constexpr uint32_t prob_scale = 1 << prob_bits;
38
39 unsigned char rgb[WIDTH * HEIGHT * 3];
40 unsigned char pix_y[WIDTH * HEIGHT];
41 unsigned char pix_cb[(WIDTH/2) * HEIGHT];
42 unsigned char pix_cr[(WIDTH/2) * HEIGHT];
43
44 struct RansCountSSBO {
45         unsigned dist[4 * 256];
46         unsigned ransfreq[4 * 256];
47 };
48
49 struct RansDistUBO {
50         struct {
51                 uint32_t x_max, rcp_freq, bias, rcp_shift_and_cmpl_freq;
52         } ransdist[4 * 256];
53         struct {
54                 uint32_t val;
55                 uint32_t padding[3];  // std140 layout.
56         } sign_biases[4];
57 };
58
59 using namespace std;
60 using namespace std::chrono;
61
62 void write_varint(int x, FILE *fp)
63 {
64         while (x >= 128) {
65                 putc((x & 0x7f) | 0x80, fp);
66                 x >>= 7;
67         }
68         putc(x, fp);
69 }
70
71 void readpix(unsigned char *ptr, const char *filename)
72 {
73         FILE *fp = fopen(filename, "rb");
74         if (fp == nullptr) {
75                 perror(filename);
76                 exit(1);
77         }
78
79         fseek(fp, 0, SEEK_END);
80         long len = ftell(fp);
81         assert(len >= WIDTH * HEIGHT * 3);
82         fseek(fp, len - WIDTH * HEIGHT * 3, SEEK_SET);
83
84         fread(ptr, 1, WIDTH * HEIGHT * 3, fp);
85         fclose(fp);
86 }
87
88 // Should be done on the GPU, of course, but irrelevant for the demonstration.
89 void convert_ycbcr()
90 {
91         double coeff[3] = { 0.2126, 0.7152, 0.0722 };  // sum = 1.0
92         double cb_fac = 1.0 / (coeff[0] + coeff[1] + 1.0f - coeff[2]);  // 0.539
93         double cr_fac = 1.0 / (1.0f - coeff[0] + coeff[1] + coeff[2]);  // 0.635 
94
95         unique_ptr<float[]> temp_cb(new float[WIDTH * HEIGHT]);
96         unique_ptr<float[]> temp_cr(new float[WIDTH * HEIGHT]);
97         for (unsigned yb = 0; yb < HEIGHT; ++yb) {
98                 for (unsigned xb = 0; xb < WIDTH; ++xb) {
99                         int r = rgb[((yb * WIDTH) + xb) * 3 + 0];
100                         int g = rgb[((yb * WIDTH) + xb) * 3 + 1];
101                         int b = rgb[((yb * WIDTH) + xb) * 3 + 2];
102                         double y = std::min(std::max(coeff[0] * r + coeff[1] * g + coeff[2] * b, 0.0), 255.0);
103                         double cb = (b - y) * cb_fac + 128.0;
104                         double cr = (r - y) * cr_fac + 128.0;
105                         pix_y[(yb * WIDTH) + xb] = lrint(y);
106                         temp_cb[(yb * WIDTH) + xb] = cb;
107                         temp_cr[(yb * WIDTH) + xb] = cr;
108                 }
109         }
110
111         // Simple 4:2:2 subsampling with left convention.
112         for (unsigned yb = 0; yb < HEIGHT; ++yb) {
113                 for (unsigned xb = 0; xb < WIDTH / 2; ++xb) {
114                         int c0 = yb * WIDTH + std::max(int(xb) * 2 - 1, 0);
115                         int c1 = yb * WIDTH + xb * 2;
116                         int c2 = yb * WIDTH + xb * 2 + 1;
117                         
118                         double cb = 0.25 * temp_cb[c0] + 0.5 * temp_cb[c1] + 0.25 * temp_cb[c2];
119                         double cr = 0.25 * temp_cr[c0] + 0.5 * temp_cr[c1] + 0.25 * temp_cr[c2];
120                         cb = std::min(std::max(cb, 0.0), 255.0);
121                         cr = std::min(std::max(cr, 0.0), 255.0);
122                         pix_cb[(yb * WIDTH/2) + xb] = lrint(cb);
123                         pix_cr[(yb * WIDTH/2) + xb] = lrint(cr);
124                 }
125         }
126 }
127
128 int main(int argc, char **argv)
129 {
130         // Set up an OpenGL context using SDL.
131         if (SDL_Init(SDL_INIT_VIDEO) == -1) {
132                 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
133                 exit(1);
134         }
135         SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
136         SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
137         SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
138         SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
139         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
140         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
141
142         SDL_Window *window = SDL_CreateWindow("OpenGL window for unit test",
143                 SDL_WINDOWPOS_UNDEFINED,
144                 SDL_WINDOWPOS_UNDEFINED,
145                 32, 32,
146                 SDL_WINDOW_OPENGL);
147         SDL_GLContext context = SDL_GL_CreateContext(window);
148         assert(context != nullptr);
149
150         if (argc >= 2)
151                 readpix(rgb, argv[1]);
152         else
153                 readpix(rgb, "color.pnm");
154         convert_ycbcr();
155
156         // Compile the DCT shader.
157         string shader_src = ::read_file("encoder.shader");
158         GLuint shader_num = compile_shader(shader_src, GL_COMPUTE_SHADER);
159         GLuint glsl_program_num = glCreateProgram();
160         glAttachShader(glsl_program_num, shader_num);
161         glLinkProgram(glsl_program_num);
162
163         GLint success;
164         glGetProgramiv(glsl_program_num, GL_LINK_STATUS, &success);
165         if (success == GL_FALSE) {
166                 GLchar error_log[1024] = {0};
167                 glGetProgramInfoLog(glsl_program_num, 1024, nullptr, error_log);
168                 fprintf(stderr, "Error linking program: %s\n", error_log);
169                 exit(1);
170         }
171
172         // Compile the tally shader.
173         shader_src = ::read_file("tally.shader");
174         shader_num = compile_shader(shader_src, GL_COMPUTE_SHADER);
175         GLuint glsl_tally_program_num = glCreateProgram();
176         glAttachShader(glsl_tally_program_num, shader_num);
177         glLinkProgram(glsl_tally_program_num);
178
179         glGetProgramiv(glsl_tally_program_num, GL_LINK_STATUS, &success);
180         if (success == GL_FALSE) {
181                 GLchar error_log[1024] = {0};
182                 glGetProgramInfoLog(glsl_tally_program_num, 1024, nullptr, error_log);
183                 fprintf(stderr, "Error linking program: %s\n", error_log);
184                 exit(1);
185         }
186
187         // Compile the rANS shader.
188         shader_src = ::read_file("rans.shader");
189         shader_num = compile_shader(shader_src, GL_COMPUTE_SHADER);
190         GLuint glsl_rans_program_num = glCreateProgram();
191         glAttachShader(glsl_rans_program_num, shader_num);
192         glLinkProgram(glsl_rans_program_num);
193
194         glGetProgramiv(glsl_rans_program_num, GL_LINK_STATUS, &success);
195         if (success == GL_FALSE) {
196                 GLchar error_log[1024] = {0};
197                 glGetProgramInfoLog(glsl_rans_program_num, 1024, nullptr, error_log);
198                 fprintf(stderr, "Error linking program: %s\n", error_log);
199                 exit(1);
200         }
201         check_error();
202
203         // An SSBO for the raw rANS counts.
204         GLuint ssbo;
205         glGenBuffers(1, &ssbo);
206         glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo);
207         glNamedBufferStorage(ssbo, sizeof(RansCountSSBO), nullptr, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
208         check_error();
209
210         // UBO for the rANS distributions (copied from an SSBO).
211         GLuint dist_ssbo;
212         glGenBuffers(1, &dist_ssbo);
213         glBindBuffer(GL_SHADER_STORAGE_BUFFER, dist_ssbo);
214         glNamedBufferStorage(dist_ssbo, sizeof(RansDistUBO), nullptr, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
215         check_error();
216
217         GLuint dist_ubo;
218         glGenBuffers(1, &dist_ubo);
219         glBindBuffer(GL_UNIFORM_BUFFER, dist_ubo);
220         glNamedBufferStorage(dist_ubo, sizeof(RansDistUBO), nullptr, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
221         check_error();
222
223         // SSBOs for the rANS output (data and offsets).
224         GLuint output_ssbo;
225         glGenBuffers(1, &output_ssbo);
226         glBindBuffer(GL_SHADER_STORAGE_BUFFER, output_ssbo);
227         glNamedBufferStorage(output_ssbo, 45 * 64 * 1024, nullptr, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
228         check_error();
229
230         GLuint output_offset_ssbo;
231         glGenBuffers(1, &output_offset_ssbo);
232         glBindBuffer(GL_SHADER_STORAGE_BUFFER, output_offset_ssbo);
233         glNamedBufferStorage(output_offset_ssbo, 45 * 64 * sizeof(uint32_t), nullptr, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
234         check_error();
235
236         // Bind SSBOs.
237         glUseProgram(glsl_program_num);
238         glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 9, ssbo);
239
240         glUseProgram(glsl_tally_program_num);
241         glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 9, ssbo);
242         glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 12, dist_ssbo);
243
244         glUseProgram(glsl_rans_program_num);
245         glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 10, output_ssbo);
246         glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 11, output_offset_ssbo);
247         glBindBufferBase(GL_UNIFORM_BUFFER, 13, dist_ubo);
248
249         glUseProgram(glsl_program_num);
250         check_error();
251
252         // Upload luma.
253         GLuint y_tex;
254         glGenTextures(1, &y_tex);
255         glBindTexture(GL_TEXTURE_2D, y_tex);
256         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
257         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
258         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
259         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
260         glTexImage2D(GL_TEXTURE_2D, 0, GL_R8UI, WIDTH, HEIGHT, 0, GL_RED_INTEGER, GL_UNSIGNED_BYTE, pix_y);
261         check_error();
262
263         // Make destination textures.
264         GLuint dc_ac7_tex, ac1_ac6_tex, ac2_ac5_tex;
265         for (GLuint *tex : { &dc_ac7_tex, &ac1_ac6_tex, &ac2_ac5_tex }) {
266                 glGenTextures(1, tex);
267                 glBindTexture(GL_TEXTURE_2D, *tex);
268                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
269                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
270                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
271                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
272                 glTexImage2D(GL_TEXTURE_2D, 0, GL_R16UI, WIDTH / 8, HEIGHT, 0, GL_RED_INTEGER, GL_UNSIGNED_SHORT, nullptr);
273                 check_error();
274         }
275
276         GLuint ac3_tex, ac4_tex;
277         for (GLuint *tex : { &ac3_tex, &ac4_tex }) {
278                 glGenTextures(1, tex);
279                 glBindTexture(GL_TEXTURE_2D, *tex);
280                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
281                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
282                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
283                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
284                 glTexImage2D(GL_TEXTURE_2D, 0, GL_R8I, WIDTH / 8, HEIGHT, 0, GL_RED_INTEGER, GL_BYTE, nullptr);
285                 check_error();
286         }
287
288         glBindImageTexture(0, dc_ac7_tex, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R16UI);
289         glBindImageTexture(1, ac1_ac6_tex, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R16UI);
290         glBindImageTexture(2, ac2_ac5_tex, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R16UI);
291         glBindImageTexture(3, ac3_tex, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R8I);
292         glBindImageTexture(4, ac4_tex, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R8I);
293         glBindImageTexture(5, y_tex, 0, GL_FALSE, 0, GL_READ_ONLY, GL_R8UI);
294         check_error();
295
296         // Bind uniforms.
297         glUseProgram(glsl_program_num);
298         GLint dc_ac7_tex_uniform = glGetUniformLocation(glsl_program_num, "dc_ac7_tex");
299         GLint ac1_ac6_tex_uniform = glGetUniformLocation(glsl_program_num, "ac1_ac6_tex");
300         GLint ac2_ac5_tex_uniform = glGetUniformLocation(glsl_program_num, "ac2_ac5_tex");
301         GLint ac3_tex_uniform = glGetUniformLocation(glsl_program_num, "ac3_tex");
302         GLint ac4_tex_uniform = glGetUniformLocation(glsl_program_num, "ac4_tex");
303         GLint image_tex_uniform = glGetUniformLocation(glsl_program_num, "image_tex");
304         glUniform1i(dc_ac7_tex_uniform, 0);
305         glUniform1i(ac1_ac6_tex_uniform, 1);
306         glUniform1i(ac2_ac5_tex_uniform, 2);
307         glUniform1i(ac3_tex_uniform, 3);
308         glUniform1i(ac4_tex_uniform, 4);
309         glUniform1i(image_tex_uniform, 5);
310
311         glUseProgram(glsl_rans_program_num);
312         dc_ac7_tex_uniform = glGetUniformLocation(glsl_rans_program_num, "dc_ac7_tex");
313         ac1_ac6_tex_uniform = glGetUniformLocation(glsl_rans_program_num, "ac1_ac6_tex");
314         ac2_ac5_tex_uniform = glGetUniformLocation(glsl_rans_program_num, "ac2_ac5_tex");
315         ac3_tex_uniform = glGetUniformLocation(glsl_rans_program_num, "ac3_tex");
316         ac4_tex_uniform = glGetUniformLocation(glsl_rans_program_num, "ac4_tex");
317         image_tex_uniform = glGetUniformLocation(glsl_rans_program_num, "image_tex");
318         glUniform1i(dc_ac7_tex_uniform, 0);
319         glUniform1i(ac1_ac6_tex_uniform, 1);
320         glUniform1i(ac2_ac5_tex_uniform, 2);
321         glUniform1i(ac3_tex_uniform, 3);
322         glUniform1i(ac4_tex_uniform, 4);
323
324         steady_clock::time_point start = steady_clock::now();
325         unsigned num_iterations = 100;
326         for (unsigned i = 0; i < num_iterations; ++i) {
327                 glClearNamedBufferSubData(ssbo, GL_R8, 0, sizeof(RansCountSSBO), GL_RED, GL_UNSIGNED_BYTE, nullptr);
328                 glUseProgram(glsl_program_num);
329                 glDispatchCompute(WIDTH_BLOCKS / 16, HEIGHT_BLOCKS, 1);
330                 glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
331
332                 glUseProgram(glsl_tally_program_num);
333                 glDispatchCompute(4, 1, 1);
334                 glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
335         
336                 glCopyNamedBufferSubData(dist_ssbo, dist_ubo, 0, 0, sizeof(RansDistUBO));
337                 glMemoryBarrier(GL_UNIFORM_BARRIER_BIT);
338
339                 glUseProgram(glsl_rans_program_num);
340                 glDispatchCompute(NUM_BLOCKS / BLOCKS_PER_STREAM, 8, 5);
341         }
342         check_error();
343         glFinish();
344         check_error();
345         steady_clock::time_point now = steady_clock::now();
346
347 #if 0
348         printf("%ld bytes + %ld escape bits (%ld) = %ld total bytes\n",
349                 tot_bytes - extra_bits / 8,
350                 extra_bits,
351                 extra_bits / 8,
352                 tot_bytes);
353
354         printf("\n");
355 #endif
356
357         printf("Each iteration took %.3f ms.\n", 1e3 * duration<double>(now - start).count() / num_iterations);
358
359         FILE *codedfp = fopen("coded.dat", "wb");
360         if (codedfp == nullptr) {
361                 perror("coded.dat");
362                 exit(1);
363         }
364
365         // Write out the distributions.
366         const RansCountSSBO *rans_count = (const RansCountSSBO *)glMapNamedBufferRange(ssbo, 0, sizeof(RansCountSSBO), GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
367         const RansDistUBO *rans_dist = (const RansDistUBO *)glMapNamedBufferRange(dist_ssbo, 0, sizeof(RansDistUBO), GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
368         for (unsigned r = 0; r < 2; ++r) {  // Hack to write fake chroma tables.
369                 // TODO: rather gamma-k or something
370                 for (unsigned i = 0; i < 4; ++i) {
371                         printf("writing table %d\n", i);
372                         for (unsigned j = 0; j < NUM_SYMS; ++j) {
373                                 printf("%d,%d: freq=%d  x_max=%d, rcp_freq=%08x, bias=%d, rcp_shift=%d, cmpl_freq=%d\n",
374                                         i, j, rans_count->ransfreq[i * 256 + j],
375                                         rans_dist->ransdist[i * 256 + j].x_max,
376                                         rans_dist->ransdist[i * 256 + j].rcp_freq,
377                                         rans_dist->ransdist[i * 256 + j].bias,
378                                         rans_dist->ransdist[i * 256 + j].rcp_shift_and_cmpl_freq & 0xffff,
379                                         rans_dist->ransdist[i * 256 + j].rcp_shift_and_cmpl_freq >> 16);
380                                 write_varint(rans_count->ransfreq[i * 256 + j], codedfp);
381                         }
382                 }
383         }
384
385         // Write out the actual data.
386         // TODO: Do the deduplication.
387
388         const uint32_t *offsets = (const uint32_t *)glMapNamedBufferRange(output_offset_ssbo, 0, 45 * 64 * sizeof(uint32_t), GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
389 #if 0
390         for (int i = 0; i < 45*64; ++i) {
391                 printf("%d,%d,%d: %u\n", i / 64, (i / 8) % 8, i % 8, 1024 * (i + 1) - offsets[i]);
392         }
393 #endif
394
395         const uint8_t *data = (const uint8_t *)glMapNamedBufferRange(output_ssbo, 0, 45 * 64 * 1024, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
396
397         string last_block;
398         for (unsigned y = 0; y < 8; ++y) {
399                 for (unsigned x = 0; x < 8; ++x) {
400                         for (unsigned int stream_idx = 0; stream_idx < 45; ++stream_idx) {
401                                 const uint8_t *out_end = data + (stream_idx * 64 + y * 8 + x + 1) * 1024;
402                                 const uint8_t *ptr = data + offsets[stream_idx * 64 + y * 8 + x];
403                                 uint32_t num_rans_bytes = out_end - ptr;
404                                 assert(num_rans_bytes <= 1024);
405
406                                 if (num_rans_bytes == last_block.size() &&
407                                     memcmp(last_block.data(), ptr, last_block.size()) == 0) {
408                                         write_varint(0, codedfp);
409                                 } else {
410                                         last_block = string((const char *)ptr, num_rans_bytes);
411                                         write_varint(num_rans_bytes, codedfp);
412                                         fwrite(ptr, 1, num_rans_bytes, codedfp);
413                                 }
414                         }
415                 }
416         }
417         fclose(codedfp);
418 }