9 #include <SDL2/SDL_error.h>
10 #include <SDL2/SDL_events.h>
11 #include <SDL2/SDL_image.h>
12 #include <SDL2/SDL_keyboard.h>
13 #include <SDL2/SDL_mouse.h>
14 #include <SDL2/SDL_video.h>
24 #define BUFFER_OFFSET(i) ((char *)nullptr + (i))
28 // Operating point 3 (10 Hz on CPU, excluding preprocessing).
29 constexpr float patch_overlap_ratio = 0.75f;
30 constexpr unsigned coarsest_level = 5;
31 constexpr unsigned finest_level = 1;
32 constexpr unsigned patch_size_pixels = 12;
34 // Some global OpenGL objects.
35 GLuint nearest_sampler, linear_sampler, mipmap_sampler;
38 string read_file(const string &filename)
40 FILE *fp = fopen(filename.c_str(), "r");
42 perror(filename.c_str());
46 int ret = fseek(fp, 0, SEEK_END);
48 perror("fseek(SEEK_END)");
54 ret = fseek(fp, 0, SEEK_SET);
56 perror("fseek(SEEK_SET)");
62 ret = fread(&str[0], size, 1, fp);
68 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
69 size, filename.c_str());
78 GLuint compile_shader(const string &shader_src, GLenum type)
80 GLuint obj = glCreateShader(type);
81 const GLchar* source[] = { shader_src.data() };
82 const GLint length[] = { (GLint)shader_src.size() };
83 glShaderSource(obj, 1, source, length);
86 GLchar info_log[4096];
87 GLsizei log_length = sizeof(info_log) - 1;
88 glGetShaderInfoLog(obj, log_length, &log_length, info_log);
89 info_log[log_length] = 0;
90 if (strlen(info_log) > 0) {
91 fprintf(stderr, "Shader compile log: %s\n", info_log);
95 glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
96 if (status == GL_FALSE) {
97 // Add some line numbers to easier identify compile errors.
98 string src_with_lines = "/* 1 */ ";
100 for (char ch : shader_src) {
101 src_with_lines.push_back(ch);
104 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
105 src_with_lines += buf;
109 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
117 GLuint load_texture(const char *filename, unsigned width, unsigned height)
119 FILE *fp = fopen(filename, "rb");
124 unique_ptr<uint8_t[]> pix(new uint8_t[width * height]);
125 if (fread(pix.get(), width * height, 1, fp) != 1) {
126 fprintf(stderr, "Short read from %s\n", filename);
131 // Convert to bottom-left origin.
132 for (unsigned y = 0; y < height / 2; ++y) {
133 unsigned y2 = height - 1 - y;
134 swap_ranges(&pix[y * width], &pix[y * width + width], &pix[y2 * width]);
138 for (int w = width, h = height; w > 1 || h > 1; ) {
145 glCreateTextures(GL_TEXTURE_2D, 1, &tex);
146 glTextureStorage2D(tex, levels, GL_R8, width, height);
147 glTextureSubImage2D(tex, 0, 0, 0, width, height, GL_RED, GL_UNSIGNED_BYTE, pix.get());
148 glGenerateTextureMipmap(tex);
153 GLuint link_program(GLuint vs_obj, GLuint fs_obj)
155 GLuint program = glCreateProgram();
156 glAttachShader(program, vs_obj);
157 glAttachShader(program, fs_obj);
158 glLinkProgram(program);
160 glGetProgramiv(program, GL_LINK_STATUS, &success);
161 if (success == GL_FALSE) {
162 GLchar error_log[1024] = {0};
163 glGetProgramInfoLog(program, 1024, nullptr, error_log);
164 fprintf(stderr, "Error linking program: %s\n", error_log);
170 GLuint generate_vbo(GLint size, GLsizeiptr data_size, const GLvoid *data)
173 glCreateBuffers(1, &vbo);
174 glBufferData(GL_ARRAY_BUFFER, data_size, data, GL_STATIC_DRAW);
175 glNamedBufferData(vbo, data_size, data, GL_STATIC_DRAW);
179 GLuint fill_vertex_attribute(GLuint vao, GLuint glsl_program_num, const string &attribute_name, GLint size, GLenum type, GLsizeiptr data_size, const GLvoid *data)
181 int attrib = glGetAttribLocation(glsl_program_num, attribute_name.c_str());
186 GLuint vbo = generate_vbo(size, data_size, data);
188 glBindBuffer(GL_ARRAY_BUFFER, vbo);
189 glEnableVertexArrayAttrib(vao, attrib);
190 glVertexAttribPointer(attrib, size, type, GL_FALSE, 0, BUFFER_OFFSET(0));
191 glBindBuffer(GL_ARRAY_BUFFER, 0);
196 void bind_sampler(GLuint program, GLint location, GLuint texture_unit, GLuint tex, GLuint sampler)
198 if (location == -1) {
202 glBindTextureUnit(texture_unit, tex);
203 glBindSampler(texture_unit, sampler);
204 glProgramUniform1i(program, location, texture_unit);
207 // Compute gradients in every point, used for the motion search.
208 // The DIS paper doesn't actually mention how these are computed,
209 // but seemingly, a 3x3 Sobel operator is used here (at least in
210 // later versions of the code), while a [1 -8 0 8 -1] kernel is
211 // used for all the derivatives in the variational refinement part
212 // (which borrows code from DeepFlow). This is inconsistent,
213 // but I guess we're better off with staying with the original
214 // decisions until we actually know having different ones would be better.
218 void exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height);
223 GLuint sobel_program;
226 GLuint uniform_tex, uniform_image_size, uniform_inv_image_size;
231 sobel_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
232 sobel_fs_obj = compile_shader(read_file("sobel.frag"), GL_FRAGMENT_SHADER);
233 sobel_program = link_program(sobel_vs_obj, sobel_fs_obj);
235 // Set up the VAO containing all the required position/texcoord data.
236 glCreateVertexArrays(1, &sobel_vao);
237 glBindVertexArray(sobel_vao);
239 GLint position_attrib = glGetAttribLocation(sobel_program, "position");
240 glEnableVertexArrayAttrib(sobel_vao, position_attrib);
241 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
243 uniform_tex = glGetUniformLocation(sobel_program, "tex");
244 uniform_inv_image_size = glGetUniformLocation(sobel_program, "inv_image_size");
247 void Sobel::exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height)
249 glUseProgram(sobel_program);
250 glBindTextureUnit(0, tex0_view);
251 glBindSampler(0, nearest_sampler);
252 glProgramUniform1i(sobel_program, uniform_tex, 0);
253 glProgramUniform2f(sobel_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
255 GLuint grad0_fbo; // TODO: cleanup
256 glCreateFramebuffers(1, &grad0_fbo);
257 glNamedFramebufferTexture(grad0_fbo, GL_COLOR_ATTACHMENT0, grad0_tex, 0);
259 glViewport(0, 0, level_width, level_height);
260 glBindFramebuffer(GL_FRAMEBUFFER, grad0_fbo);
261 glBindVertexArray(sobel_vao);
262 glUseProgram(sobel_program);
264 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
267 // Motion search to find the initial flow. See motion_search.frag for documentation.
271 void exec(GLuint tex0_view, GLuint tex1_view, GLuint grad0_tex, GLuint flow_tex, GLuint flow_out_tex, int level_width, int level_height, int width_patches, int height_patches);
274 GLuint motion_vs_obj;
275 GLuint motion_fs_obj;
276 GLuint motion_search_program;
277 GLuint motion_search_vao;
279 GLuint uniform_image_size, uniform_inv_image_size;
280 GLuint uniform_image0_tex, uniform_image1_tex, uniform_grad0_tex, uniform_flow_tex;
283 MotionSearch::MotionSearch()
285 motion_vs_obj = compile_shader(read_file("motion_search.vert"), GL_VERTEX_SHADER);
286 motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
287 motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
289 // Set up the VAO containing all the required position/texcoord data.
290 glCreateVertexArrays(1, &motion_search_vao);
291 glBindVertexArray(motion_search_vao);
292 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
294 GLint position_attrib = glGetAttribLocation(motion_search_program, "position");
295 glEnableVertexArrayAttrib(motion_search_vao, position_attrib);
296 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
298 uniform_image_size = glGetUniformLocation(motion_search_program, "image_size");
299 uniform_inv_image_size = glGetUniformLocation(motion_search_program, "inv_image_size");
300 uniform_image0_tex = glGetUniformLocation(motion_search_program, "image0_tex");
301 uniform_image1_tex = glGetUniformLocation(motion_search_program, "image1_tex");
302 uniform_grad0_tex = glGetUniformLocation(motion_search_program, "grad0_tex");
303 uniform_flow_tex = glGetUniformLocation(motion_search_program, "flow_tex");
306 void MotionSearch::exec(GLuint tex0_view, GLuint tex1_view, GLuint grad0_tex, GLuint flow_tex, GLuint flow_out_tex, int level_width, int level_height, int width_patches, int height_patches)
308 glUseProgram(motion_search_program);
310 bind_sampler(motion_search_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
311 bind_sampler(motion_search_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
312 bind_sampler(motion_search_program, uniform_grad0_tex, 2, grad0_tex, nearest_sampler);
313 bind_sampler(motion_search_program, uniform_flow_tex, 3, flow_tex, linear_sampler);
315 glProgramUniform2f(motion_search_program, uniform_image_size, level_width, level_height);
316 glProgramUniform2f(motion_search_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
318 GLuint flow_fbo; // TODO: cleanup
319 glCreateFramebuffers(1, &flow_fbo);
320 glNamedFramebufferTexture(flow_fbo, GL_COLOR_ATTACHMENT0, flow_out_tex, 0);
322 glViewport(0, 0, width_patches, height_patches);
323 glBindFramebuffer(GL_FRAMEBUFFER, flow_fbo);
324 glBindVertexArray(motion_search_vao);
325 glUseProgram(motion_search_program);
326 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
329 // Do “densification”, ie., upsampling of the flow patches to the flow field
330 // (the same size as the image at this level). We draw one quad per patch
331 // over its entire covered area (using instancing in the vertex shader),
332 // and then weight the contributions in the pixel shader by post-warp difference.
333 // This is equation (3) in the paper.
335 // We accumulate the flow vectors in the R/G channels (for u/v) and the total
336 // weight in the B channel. Dividing R and G by B gives the normalized values.
340 void exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint dense_flow_tex, int level_width, int level_height, int width_patches, int height_patches);
343 GLuint densify_vs_obj;
344 GLuint densify_fs_obj;
345 GLuint densify_program;
348 GLuint uniform_width_patches, uniform_patch_size, uniform_patch_spacing;
349 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
354 densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
355 densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
356 densify_program = link_program(densify_vs_obj, densify_fs_obj);
358 // Set up the VAO containing all the required position/texcoord data.
359 glCreateVertexArrays(1, &densify_vao);
360 glBindVertexArray(densify_vao);
361 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
363 GLint position_attrib = glGetAttribLocation(densify_program, "position");
364 glEnableVertexArrayAttrib(densify_vao, position_attrib);
365 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
367 uniform_width_patches = glGetUniformLocation(densify_program, "width_patches");
368 uniform_patch_size = glGetUniformLocation(densify_program, "patch_size");
369 uniform_patch_spacing = glGetUniformLocation(densify_program, "patch_spacing");
370 uniform_image0_tex = glGetUniformLocation(densify_program, "image0_tex");
371 uniform_image1_tex = glGetUniformLocation(densify_program, "image1_tex");
372 uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
375 void Densify::exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint dense_flow_tex, int level_width, int level_height, int width_patches, int height_patches)
377 glUseProgram(densify_program);
379 bind_sampler(densify_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
380 bind_sampler(densify_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
381 bind_sampler(densify_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
383 glProgramUniform1i(densify_program, uniform_width_patches, width_patches);
384 glProgramUniform2f(densify_program, uniform_patch_size,
385 float(patch_size_pixels) / level_width,
386 float(patch_size_pixels) / level_height);
388 float patch_spacing_x = float(level_width - patch_size_pixels) / (width_patches - 1);
389 float patch_spacing_y = float(level_height - patch_size_pixels) / (height_patches - 1);
390 glProgramUniform2f(densify_program, uniform_patch_spacing,
391 patch_spacing_x / level_width,
392 patch_spacing_y / level_height);
394 GLuint dense_flow_fbo; // TODO: cleanup
395 glCreateFramebuffers(1, &dense_flow_fbo);
396 glNamedFramebufferTexture(dense_flow_fbo, GL_COLOR_ATTACHMENT0, dense_flow_tex, 0);
398 glViewport(0, 0, level_width, level_height);
400 glBlendFunc(GL_ONE, GL_ONE);
401 glBindVertexArray(densify_vao);
402 glBindFramebuffer(GL_FRAMEBUFFER, dense_flow_fbo);
403 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches);
408 if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
409 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
412 SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
413 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
414 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
415 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
417 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
418 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
419 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
420 // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
421 SDL_Window *window = SDL_CreateWindow("OpenGL window",
422 SDL_WINDOWPOS_UNDEFINED,
423 SDL_WINDOWPOS_UNDEFINED,
426 SDL_GLContext context = SDL_GL_CreateContext(window);
427 assert(context != nullptr);
430 GLuint tex0 = load_texture("test1499.pgm", WIDTH, HEIGHT);
431 GLuint tex1 = load_texture("test1500.pgm", WIDTH, HEIGHT);
433 // Make some samplers.
434 glCreateSamplers(1, &nearest_sampler);
435 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
436 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
437 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
438 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
440 glCreateSamplers(1, &linear_sampler);
441 glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
442 glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
443 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
444 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
446 glCreateSamplers(1, &mipmap_sampler);
447 glSamplerParameteri(mipmap_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
448 glSamplerParameteri(mipmap_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
449 glSamplerParameteri(mipmap_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
450 glSamplerParameteri(mipmap_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
458 glCreateBuffers(1, &vertex_vbo);
459 glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
460 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
462 // Initial flow is zero, 1x1.
463 GLuint initial_flow_tex;
464 glCreateTextures(GL_TEXTURE_2D, 1, &initial_flow_tex);
465 glTextureStorage2D(initial_flow_tex, 1, GL_RGB32F, 1, 1);
467 GLuint prev_level_flow_tex = initial_flow_tex;
470 MotionSearch motion_search;
474 glGenQueries(1, &query);
475 glBeginQuery(GL_TIME_ELAPSED, query);
477 for (int level = coarsest_level; level >= int(finest_level); --level) {
478 int level_width = WIDTH >> level;
479 int level_height = HEIGHT >> level;
480 float patch_spacing_pixels = patch_size_pixels * (1.0f - patch_overlap_ratio);
481 int width_patches = 1 + lrintf((level_width - patch_size_pixels) / patch_spacing_pixels);
482 int height_patches = 1 + lrintf((level_height - patch_size_pixels) / patch_spacing_pixels);
484 // Make sure we always read from the correct level; the chosen
485 // mipmapping could otherwise be rather unpredictable, especially
486 // during motion search.
487 // TODO: create these beforehand, and stop leaking them.
488 GLuint tex0_view, tex1_view;
489 glGenTextures(1, &tex0_view);
490 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_R8, level, 1, 0, 1);
491 glGenTextures(1, &tex1_view);
492 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_R8, level, 1, 0, 1);
494 // Create a new texture; we could be fancy and render use a multi-level
497 glCreateTextures(GL_TEXTURE_2D, 1, &grad0_tex);
498 glTextureStorage2D(grad0_tex, 1, GL_RG16F, level_width, level_height);
500 // Find the derivative.
501 sobel.exec(tex0_view, grad0_tex, level_width, level_height);
503 // Motion search to find the initial flow. We use the flow from the previous
504 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
506 // Create an output flow texture.
508 glCreateTextures(GL_TEXTURE_2D, 1, &flow_out_tex);
509 glTextureStorage2D(flow_out_tex, 1, GL_RG16F, width_patches, height_patches);
512 motion_search.exec(tex0_view, tex1_view, grad0_tex, prev_level_flow_tex, flow_out_tex, level_width, level_height, width_patches, height_patches);
516 // Set up an output texture (initially zero).
517 GLuint dense_flow_tex;
518 glCreateTextures(GL_TEXTURE_2D, 1, &dense_flow_tex);
519 glTextureStorage2D(dense_flow_tex, 1, GL_RGB16F, level_width, level_height);
522 densify.exec(tex0_view, tex1_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches);
524 // TODO: Variational refinement.
526 prev_level_flow_tex = dense_flow_tex;
528 glEndQuery(GL_TIME_ELAPSED);
532 glGetQueryObjectiv(query, GL_QUERY_RESULT_AVAILABLE, &available);
533 } while (!available);
534 GLuint64 time_elapsed;
535 glGetQueryObjectui64v(query, GL_QUERY_RESULT, &time_elapsed);
536 fprintf(stderr, "GPU time used = %.1f ms\n", time_elapsed / 1e6);
538 int level_width = WIDTH >> finest_level;
539 int level_height = HEIGHT >> finest_level;
540 unique_ptr<float[]> dense_flow(new float[level_width * level_height * 3]);
541 glGetTextureImage(prev_level_flow_tex, 0, GL_RGB, GL_FLOAT, level_width * level_height * 3 * sizeof(float), dense_flow.get());
543 FILE *fp = fopen("flow.ppm", "wb");
544 FILE *flowfp = fopen("flow.flo", "wb");
545 fprintf(fp, "P6\n%d %d\n255\n", level_width, level_height);
546 fprintf(flowfp, "FEIH");
547 fwrite(&level_width, 4, 1, flowfp);
548 fwrite(&level_height, 4, 1, flowfp);
549 for (unsigned y = 0; y < unsigned(level_height); ++y) {
550 int yy = level_height - y - 1;
551 for (unsigned x = 0; x < unsigned(level_width); ++x) {
552 float du = dense_flow[(yy * level_width + x) * 3 + 0];
553 float dv = dense_flow[(yy * level_width + x) * 3 + 1];
554 float w = dense_flow[(yy * level_width + x) * 3 + 2];
556 du = (du / w) * level_width;
557 dv = (-dv / w) * level_height;
559 fwrite(&du, 4, 1, flowfp);
560 fwrite(&dv, 4, 1, flowfp);
563 flow2rgb(du, dv, &r, &g, &b);
572 fprintf(stderr, "err = %d\n", glGetError());