]> git.sesse.net Git - movit/blob - main.cpp
Move the Effect class out into its own file.
[movit] / main.cpp
1 #define GL_GLEXT_PROTOTYPES 1
2 #define NO_SDL_GLEXT 1
3
4 #define WIDTH 1280
5 #define HEIGHT 720
6 #define BUFFER_OFFSET(i) ((char *)NULL + (i))
7
8 #include <string.h>
9 #include <math.h>
10 #include <time.h>
11 #include <assert.h>
12
13 #include <string>
14 #include <vector>
15 #include <map>
16
17 #include <SDL/SDL.h>
18 #include <SDL/SDL_opengl.h>
19 #include <SDL/SDL_image.h>
20
21 #include <GL/gl.h>
22 #include <GL/glext.h>
23
24 #include "effect.h"
25 #include "util.h"
26 #include "widgets.h"
27 #include "texture_enum.h"
28
29 unsigned char result[WIDTH * HEIGHT * 4];
30
31 float lift_theta = 0.0f, lift_rad = 0.0f, lift_v = 0.0f;
32 float gamma_theta = 0.0f, gamma_rad = 0.0f, gamma_v = 0.5f;
33 float gain_theta = 0.0f, gain_rad = 0.0f, gain_v = 0.25f;
34 float saturation = 1.0f;
35
36 float lift_r = 0.0f, lift_g = 0.0f, lift_b = 0.0f;
37 float gamma_r = 1.0f, gamma_g = 1.0f, gamma_b = 1.0f;
38 float gain_r = 1.0f, gain_g = 1.0f, gain_b = 1.0f;
39
40 enum PixelFormat { FORMAT_RGB, FORMAT_RGBA };
41
42 enum ColorSpace {
43         COLORSPACE_sRGB = 0,
44         COLORSPACE_REC_709 = 0,  // Same as sRGB.
45         COLORSPACE_REC_601_525 = 1,
46         COLORSPACE_REC_601_625 = 2,
47 };
48
49 enum GammaCurve {
50         GAMMA_LINEAR = 0,
51         GAMMA_sRGB = 1,
52         GAMMA_REC_601 = 2,
53         GAMMA_REC_709 = 2,  // Same as Rec. 601.
54 };
55
56 struct ImageFormat {
57         PixelFormat pixel_format;
58         ColorSpace color_space;
59         GammaCurve gamma_curve;
60 };
61
62 enum EffectId {
63         // Mostly for internal use.
64         GAMMA_CONVERSION = 0,
65         RGB_PRIMARIES_CONVERSION,
66
67         // Color.
68         LIFT_GAMMA_GAIN,
69 };
70
71 // Can alias on a float[3].
72 struct RGBTriplet {
73         RGBTriplet(float r, float g, float b)
74                 : r(r), g(g), b(b) {}
75
76         float r, g, b;
77 };
78
79 class GammaExpansionEffect : public Effect {
80 public:
81         GammaExpansionEffect()
82                 : source_curve(GAMMA_LINEAR)
83         {
84                 register_int("source_curve", (int *)&source_curve);
85         }
86
87 private:
88         GammaCurve source_curve;
89 };
90
91 class ColorSpaceConversionEffect : public Effect {
92 public:
93         ColorSpaceConversionEffect()
94                 : source_space(COLORSPACE_sRGB),
95                   destination_space(COLORSPACE_sRGB)
96         {
97                 register_int("source_space", (int *)&source_space);
98                 register_int("destination_space", (int *)&destination_space);
99         }
100
101 private:
102         ColorSpace source_space, destination_space;
103 };
104
105 class ColorSpaceConversionEffect;
106
107 class LiftGammaGainEffect : public Effect {
108 public:
109         LiftGammaGainEffect()
110                 : lift(0.0f, 0.0f, 0.0f),
111                   gamma(1.0f, 1.0f, 1.0f),
112                   gain(1.0f, 1.0f, 1.0f),
113                   saturation(1.0f)
114         {
115                 register_vec3("lift", (float *)&lift);
116                 register_vec3("gamma", (float *)&gamma);
117                 register_vec3("gain", (float *)&gain);
118                 register_float("saturation", &saturation);
119         }
120
121 private:
122         RGBTriplet lift, gamma, gain;
123         float saturation;
124 };
125
126 class EffectChain {
127 public:
128         EffectChain(unsigned width, unsigned height);
129         void add_input(const ImageFormat &format);
130
131         // The pointer is owned by EffectChain.
132         Effect *add_effect(EffectId effect);
133
134         void add_output(const ImageFormat &format);
135
136         void render(unsigned char *src, unsigned char *dst);
137
138 private:
139         unsigned width, height;
140         ImageFormat input_format, output_format;
141         std::vector<Effect *> effects;
142
143         ColorSpace current_color_space;
144         GammaCurve current_gamma_curve; 
145 };
146
147 EffectChain::EffectChain(unsigned width, unsigned height)
148         : width(width), height(height) {}
149
150 void EffectChain::add_input(const ImageFormat &format)
151 {
152         input_format = format;
153         current_color_space = format.color_space;
154         current_gamma_curve = format.gamma_curve;
155 }
156
157 void EffectChain::add_output(const ImageFormat &format)
158 {
159         output_format = format;
160 }
161         
162 Effect *instantiate_effect(EffectId effect)
163 {
164         switch (effect) {
165         case GAMMA_CONVERSION:
166                 return new GammaExpansionEffect();
167         case RGB_PRIMARIES_CONVERSION:
168                 return new GammaExpansionEffect();
169         case LIFT_GAMMA_GAIN:
170                 return new LiftGammaGainEffect();
171         }
172         assert(false);
173 }
174
175 Effect *EffectChain::add_effect(EffectId effect_id)
176 {
177         Effect *effect = instantiate_effect(effect_id);
178
179         if (effect->needs_linear_light() && current_gamma_curve != GAMMA_LINEAR) {
180                 GammaExpansionEffect *gamma_conversion = new GammaExpansionEffect();
181                 gamma_conversion->set_int("source_curve", current_gamma_curve);
182                 effects.push_back(gamma_conversion);
183                 current_gamma_curve = GAMMA_LINEAR;
184         }
185
186         if (effect->needs_srgb_primaries() && current_color_space != COLORSPACE_sRGB) {
187                 assert(current_gamma_curve == GAMMA_LINEAR);
188                 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
189                 colorspace_conversion->set_int("source_space", current_color_space);
190                 colorspace_conversion->set_int("destination_space", COLORSPACE_sRGB);
191                 effects.push_back(colorspace_conversion);
192                 current_color_space = COLORSPACE_sRGB;
193         }
194
195         effects.push_back(effect);
196         return effect;
197 }
198
199 GLhandleARB read_shader(const char* filename, GLenum type)
200 {
201         static char buf[131072];
202         FILE *fp = fopen(filename, "r");
203         if (fp == NULL) {
204                 perror(filename);
205                 exit(1);
206         }
207
208         int len = fread(buf, 1, sizeof(buf), fp);
209         fclose(fp);
210
211         GLhandleARB obj = glCreateShaderObjectARB(type);
212         const GLchar* source[] = { buf };
213         const GLint length[] = { len };
214         glShaderSource(obj, 1, source, length);
215         glCompileShader(obj);
216
217         GLchar info_log[4096];
218         GLsizei log_length = sizeof(info_log) - 1;
219         glGetShaderInfoLog(obj, log_length, &log_length, info_log);
220         info_log[log_length] = 0; 
221         printf("shader compile log: %s\n", info_log);
222
223         GLint status;
224         glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
225         if (status == GL_FALSE) {
226                 exit(1);
227         }
228
229         return obj;
230 }
231
232 void draw_picture_quad(GLint prog, int frame)
233 {
234         glUseProgramObjectARB(prog);
235         check_error();
236
237         glActiveTexture(GL_TEXTURE0);
238         glBindTexture(GL_TEXTURE_2D, SOURCE_IMAGE);
239         glUniform1i(glGetUniformLocation(prog, "tex"), 0);
240
241         glActiveTexture(GL_TEXTURE1);
242         glBindTexture(GL_TEXTURE_1D, SRGB_LUT);
243         glUniform1i(glGetUniformLocation(prog, "srgb_tex"), 1);
244
245         glActiveTexture(GL_TEXTURE2);
246         glBindTexture(GL_TEXTURE_1D, SRGB_REVERSE_LUT);
247         glUniform1i(glGetUniformLocation(prog, "srgb_reverse_tex"), 2);
248
249         glUniform3f(glGetUniformLocation(prog, "lift"), lift_r, lift_g, lift_b);
250         //glUniform3f(glGetUniformLocation(prog, "gamma"), gamma_r, gamma_g, gamma_b);
251         glUniform3f(glGetUniformLocation(prog, "inv_gamma_22"),
252                     2.2f / gamma_r,
253                     2.2f / gamma_g,
254                     2.2f / gamma_b);
255         glUniform3f(glGetUniformLocation(prog, "gain_pow_inv_gamma"),
256                     pow(gain_r, 1.0f / gamma_r),
257                     pow(gain_g, 1.0f / gamma_g),
258                     pow(gain_b, 1.0f / gamma_b));
259         glUniform1f(glGetUniformLocation(prog, "saturation"), saturation);
260
261         glDisable(GL_BLEND);
262         check_error();
263         glDisable(GL_DEPTH_TEST);
264         check_error();
265         glDepthMask(GL_FALSE);
266         check_error();
267
268         glMatrixMode(GL_PROJECTION);
269         glLoadIdentity();
270         glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
271
272         glMatrixMode(GL_MODELVIEW);
273         glLoadIdentity();
274
275         glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
276 //      glClear(GL_COLOR_BUFFER_BIT);
277         check_error();
278
279         glBegin(GL_QUADS);
280
281         glTexCoord2f(0.0f, 1.0f);
282         glVertex2f(0.0f, 0.0f);
283
284         glTexCoord2f(1.0f, 1.0f);
285         glVertex2f(1.0f, 0.0f);
286
287         glTexCoord2f(1.0f, 0.0f);
288         glVertex2f(1.0f, 1.0f);
289
290         glTexCoord2f(0.0f, 0.0f);
291         glVertex2f(0.0f, 1.0f);
292
293         glEnd();
294         check_error();
295 }
296
297 void update_hsv()
298 {
299         hsv2rgb(lift_theta, lift_rad, lift_v, &lift_r, &lift_g, &lift_b);
300         hsv2rgb(gamma_theta, gamma_rad, gamma_v * 2.0f, &gamma_r, &gamma_g, &gamma_b);
301         hsv2rgb(gain_theta, gain_rad, gain_v * 4.0f, &gain_r, &gain_g, &gain_b);
302
303         if (saturation < 0.0) {
304                 saturation = 0.0;
305         }
306
307         printf("lift: %f %f %f\n", lift_r, lift_g, lift_b);
308         printf("gamma: %f %f %f\n", gamma_r, gamma_g, gamma_b);
309         printf("gain: %f %f %f\n", gain_r, gain_g, gain_b);
310         printf("saturation: %f\n", saturation);
311         printf("\n");
312 }
313
314 void mouse(int x, int y)
315 {
316         float xf = (x / (float)WIDTH) * 16.0f / 9.0f;
317         float yf = (HEIGHT - y) / (float)HEIGHT;
318
319         if (yf < 0.2f) {
320                 read_colorwheel(xf, yf, &lift_rad, &lift_theta, &lift_v);
321         } else if (yf >= 0.2f && yf < 0.4f) {
322                 read_colorwheel(xf, yf - 0.2f, &gamma_rad, &gamma_theta, &gamma_v);
323         } else if (yf >= 0.4f && yf < 0.6f) {
324                 read_colorwheel(xf, yf - 0.4f, &gain_rad, &gain_theta, &gain_v);
325         } else if (yf >= 0.6f && yf < 0.62f && xf < 0.2f) {
326                 saturation = (xf / 0.2f) * 4.0f;
327         }
328
329         update_hsv();
330 }
331
332 void load_texture(const char *filename)
333 {
334         SDL_Surface *img = IMG_Load(filename);
335         if (img == NULL) {
336                 fprintf(stderr, "Load of '%s' failed\n", filename);
337                 exit(1);
338         }
339
340         // Convert to RGB.
341         SDL_PixelFormat *fmt = img->format;
342         SDL_LockSurface(img);
343         unsigned char *src_pixels = (unsigned char *)img->pixels;
344         unsigned char *dst_pixels = (unsigned char *)malloc(img->w * img->h * 3);
345         for (unsigned i = 0; i < img->w * img->h; ++i) {
346                 unsigned char r, g, b;
347                 unsigned int temp;
348                 unsigned int pixel = *(unsigned int *)(src_pixels + i * fmt->BytesPerPixel);
349
350                 temp = pixel & fmt->Rmask;
351                 temp = temp >> fmt->Rshift;
352                 temp = temp << fmt->Rloss;
353                 r = temp;
354
355                 temp = pixel & fmt->Gmask;
356                 temp = temp >> fmt->Gshift;
357                 temp = temp << fmt->Gloss;
358                 g = temp;
359
360                 temp = pixel & fmt->Bmask;
361                 temp = temp >> fmt->Bshift;
362                 temp = temp << fmt->Bloss;
363                 b = temp;
364
365                 dst_pixels[i * 3 + 0] = r;
366                 dst_pixels[i * 3 + 1] = g;
367                 dst_pixels[i * 3 + 2] = b;
368         }
369         SDL_UnlockSurface(img);
370
371 #if 1
372         // we will convert to sRGB in the shader
373         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, img->w, img->h, 0, GL_RGB, GL_UNSIGNED_BYTE, dst_pixels);
374         check_error();
375 #else
376         // implicit sRGB conversion in hardware
377         glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8, img->w, img->h, 0, GL_RGB, GL_UNSIGNED_BYTE, dst_pixels);
378         check_error();
379 #endif
380         free(dst_pixels);
381         SDL_FreeSurface(img);
382 }
383
384 void write_ppm(const char *filename, unsigned char *screenbuf)
385 {
386         FILE *fp = fopen(filename, "w");
387         fprintf(fp, "P6\n%d %d\n255\n", WIDTH, HEIGHT);
388         for (unsigned y = 0; y < HEIGHT; ++y) {
389                 unsigned char *srcptr = screenbuf + ((HEIGHT - y - 1) * WIDTH) * 4;
390                 for (unsigned x = 0; x < WIDTH; ++x) {
391                         fputc(srcptr[x * 4 + 2], fp);
392                         fputc(srcptr[x * 4 + 1], fp);
393                         fputc(srcptr[x * 4 + 0], fp);
394                 }
395         }
396         fclose(fp);
397 }
398
399 int main(int argc, char **argv)
400 {
401         int quit = 0;
402
403         SDL_Init(SDL_INIT_EVERYTHING);
404         SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
405         SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
406         SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
407         SDL_SetVideoMode(WIDTH, HEIGHT, 0, SDL_OPENGL);
408         SDL_WM_SetCaption("OpenGL window", NULL);
409         
410         // geez 
411         glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
412         glPixelStorei(GL_PACK_ALIGNMENT, 1);
413
414         glBindTexture(GL_TEXTURE_2D, SOURCE_IMAGE);
415         check_error();
416         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
417         check_error();
418
419         load_texture("blg_wheels_woman_1.jpg");
420         //glGenerateMipmap(GL_TEXTURE_2D);
421         //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 4);
422         //check_error();
423
424         //load_texture("maserati_gts_wallpaper_1280x720_01.jpg");
425         //load_texture("90630d1295075297-console-games-wallpapers-wallpaper_need_for_speed_prostreet_09_1920x1080.jpg");
426         //load_texture("glacier-lake-1280-720-4087.jpg");
427
428 #if 0
429         // sRGB reverse LUT
430         glBindTexture(GL_TEXTURE_1D, SRGB_REVERSE_LUT);
431         check_error();
432         glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
433         glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
434         check_error();
435         float srgb_reverse_tex[4096];
436         for (unsigned i = 0; i < 4096; ++i) {
437                 float x = i / 4095.0;
438                 if (x < 0.0031308f) {
439                         srgb_reverse_tex[i] = 12.92f * x;
440                 } else {
441                         srgb_reverse_tex[i] = 1.055f * pow(x, 1.0f / 2.4f) - 0.055f;
442                 }
443         }
444         glTexImage1D(GL_TEXTURE_1D, 0, GL_LUMINANCE16F_ARB, 4096, 0, GL_LUMINANCE, GL_FLOAT, srgb_reverse_tex);
445         check_error();
446
447         // sRGB LUT
448         glBindTexture(GL_TEXTURE_1D, SRGB_LUT);
449         check_error();
450         glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
451         glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
452         check_error();
453         float srgb_tex[256];
454         for (unsigned i = 0; i < 256; ++i) {
455                 float x = i / 255.0;
456                 if (x < 0.04045f) {
457                         srgb_tex[i] = x * (1.0f / 12.92f);
458                 } else {
459                         srgb_tex[i] = pow((x + 0.055) * (1.0 / 1.055f), 2.4);
460                 }
461         }
462         glTexImage1D(GL_TEXTURE_1D, 0, GL_LUMINANCE16F_ARB, 256, 0, GL_LUMINANCE, GL_FLOAT, srgb_tex);
463         check_error();
464 #endif
465
466         // generate a PDO to hold the data we read back with glReadPixels()
467         // (Intel/DRI goes into a slow path if we don't read to PDO)
468         glBindBuffer(GL_PIXEL_PACK_BUFFER_ARB, 1);
469         glBufferData(GL_PIXEL_PACK_BUFFER_ARB, WIDTH * HEIGHT * 4, NULL, GL_STREAM_READ);
470
471         make_hsv_wheel_texture();
472         update_hsv();
473
474         int prog = glCreateProgram();
475         GLhandleARB vs_obj = read_shader("vs.glsl", GL_VERTEX_SHADER);
476         GLhandleARB fs_obj = read_shader("fs.glsl", GL_FRAGMENT_SHADER);
477         glAttachObjectARB(prog, vs_obj);
478         check_error();
479         glAttachObjectARB(prog, fs_obj);
480         check_error();
481         glLinkProgram(prog);
482         check_error();
483
484         GLchar info_log[4096];
485         GLsizei log_length = sizeof(info_log) - 1;
486         log_length = sizeof(info_log) - 1;
487         glGetProgramInfoLog(prog, log_length, &log_length, info_log);
488         info_log[log_length] = 0; 
489         printf("link: %s\n", info_log);
490
491         struct timespec start, now;
492         int frame = 0, screenshot = 0;
493         clock_gettime(CLOCK_MONOTONIC, &start);
494
495         while (!quit) {
496                 SDL_Event event;
497                 while (SDL_PollEvent(&event)) {
498                         if (event.type == SDL_QUIT) {
499                                 quit = 1;
500                         } else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE) {
501                                 quit = 1;
502                         } else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_F1) {
503                                 screenshot = 1;
504                         } else if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT) {
505                                 mouse(event.button.x, event.button.y);
506                         } else if (event.type == SDL_MOUSEMOTION && (event.motion.state & SDL_BUTTON(1))) {
507                                 mouse(event.motion.x, event.motion.y);
508                         }
509                 }
510
511                 ++frame;
512
513                 draw_picture_quad(prog, frame);
514                 
515                 glReadPixels(0, 0, WIDTH, HEIGHT, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, BUFFER_OFFSET(0));
516                 check_error();
517
518                 draw_hsv_wheel(0.0f, lift_rad, lift_theta, lift_v);
519                 draw_hsv_wheel(0.2f, gamma_rad, gamma_theta, gamma_v);
520                 draw_hsv_wheel(0.4f, gain_rad, gain_theta, gain_v);
521                 draw_saturation_bar(0.6f, saturation);
522
523                 SDL_GL_SwapBuffers();
524                 check_error();
525
526                 unsigned char *screenbuf = (unsigned char *)glMapBuffer(GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY);
527                 check_error();
528                 if (screenshot) {
529                         char filename[256];
530                         sprintf(filename, "frame%05d.ppm", frame);
531                         write_ppm(filename, screenbuf);
532                         printf("Screenshot: %s\n", filename);
533                         screenshot = 0;
534                 }
535                 glUnmapBuffer(GL_PIXEL_PACK_BUFFER_ARB);
536                 check_error();
537
538 #if 1
539                 clock_gettime(CLOCK_MONOTONIC, &now);
540                 double elapsed = now.tv_sec - start.tv_sec +
541                         1e-9 * (now.tv_nsec - start.tv_nsec);
542                 printf("%d frames in %.3f seconds = %.1f fps (%.1f ms/frame)\n",
543                         frame, elapsed, frame / elapsed,
544                         1e3 * elapsed / frame);
545 #endif
546         }
547         return 0; 
548 }