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