]> git.sesse.net Git - movit/blob - effect_chain.cpp
Let SDL convert the pixels instead of doing it ourselves.
[movit] / effect_chain.cpp
1 #define GL_GLEXT_PROTOTYPES 1
2
3 #include <stdio.h>
4 #include <string.h>
5 #include <assert.h>
6
7 #include <GL/gl.h>
8 #include <GL/glext.h>
9
10 #include "util.h"
11 #include "effect_chain.h"
12 #include "gamma_expansion_effect.h"
13 #include "gamma_compression_effect.h"
14 #include "lift_gamma_gain_effect.h"
15 #include "colorspace_conversion_effect.h"
16 #include "sandbox_effect.h"
17 #include "saturation_effect.h"
18 #include "mirror_effect.h"
19 #include "vignette_effect.h"
20 #include "blur_effect.h"
21
22 EffectChain::EffectChain(unsigned width, unsigned height)
23         : width(width), height(height), use_srgb_texture_format(false), finalized(false) {}
24
25 void EffectChain::add_input(const ImageFormat &format)
26 {
27         input_format = format;
28         current_color_space = format.color_space;
29         current_gamma_curve = format.gamma_curve;
30 }
31
32 void EffectChain::add_output(const ImageFormat &format)
33 {
34         output_format = format;
35 }
36         
37 Effect *instantiate_effect(EffectId effect)
38 {
39         switch (effect) {
40         case EFFECT_GAMMA_EXPANSION:
41                 return new GammaExpansionEffect();
42         case EFFECT_GAMMA_COMPRESSION:
43                 return new GammaCompressionEffect();
44         case EFFECT_COLOR_SPACE_CONVERSION:
45                 return new ColorSpaceConversionEffect();
46         case EFFECT_SANDBOX:
47                 return new SandboxEffect();
48         case EFFECT_LIFT_GAMMA_GAIN:
49                 return new LiftGammaGainEffect();
50         case EFFECT_SATURATION:
51                 return new SaturationEffect();
52         case EFFECT_MIRROR:
53                 return new MirrorEffect();
54         case EFFECT_VIGNETTE:
55                 return new VignetteEffect();
56         case EFFECT_BLUR:
57                 return new BlurEffect();
58         }
59         assert(false);
60 }
61
62 void EffectChain::normalize_to_linear_gamma()
63 {
64         if (current_gamma_curve == GAMMA_sRGB) {
65                 // TODO: check if the extension exists
66                 use_srgb_texture_format = true;
67         } else {
68                 GammaExpansionEffect *gamma_conversion = new GammaExpansionEffect();
69                 gamma_conversion->set_int("source_curve", current_gamma_curve);
70                 gamma_conversion->add_self_to_effect_chain(&effects);
71         }
72         current_gamma_curve = GAMMA_LINEAR;
73 }
74
75 void EffectChain::normalize_to_srgb()
76 {
77         assert(current_gamma_curve == GAMMA_LINEAR);
78         ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
79         colorspace_conversion->set_int("source_space", current_color_space);
80         colorspace_conversion->set_int("destination_space", COLORSPACE_sRGB);
81         colorspace_conversion->add_self_to_effect_chain(&effects);
82         current_color_space = COLORSPACE_sRGB;
83 }
84
85 Effect *EffectChain::add_effect(EffectId effect_id)
86 {
87         Effect *effect = instantiate_effect(effect_id);
88
89         if (effect->needs_linear_light() && current_gamma_curve != GAMMA_LINEAR) {
90                 normalize_to_linear_gamma();
91         }
92
93         if (effect->needs_srgb_primaries() && current_color_space != COLORSPACE_sRGB) {
94                 normalize_to_srgb();
95         }
96
97         effect->add_self_to_effect_chain(&effects);
98         return effect;
99 }
100
101 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
102 std::string replace_prefix(const std::string &text, const std::string &prefix)
103 {
104         std::string output;
105         size_t start = 0;
106
107         while (start < text.size()) {
108                 size_t pos = text.find("PREFIX(", start);
109                 if (pos == std::string::npos) {
110                         output.append(text.substr(start, std::string::npos));
111                         break;
112                 }
113
114                 output.append(text.substr(start, pos - start));
115                 output.append(prefix);
116                 output.append("_");
117
118                 pos += strlen("PREFIX(");
119         
120                 // Output stuff until we find the matching ), which we then eat.
121                 int depth = 1;
122                 size_t end_arg_pos = pos;
123                 while (end_arg_pos < text.size()) {
124                         if (text[end_arg_pos] == '(') {
125                                 ++depth;
126                         } else if (text[end_arg_pos] == ')') {
127                                 --depth;
128                                 if (depth == 0) {
129                                         break;
130                                 }
131                         }
132                         ++end_arg_pos;
133                 }
134                 output.append(text.substr(pos, end_arg_pos - pos));
135                 ++end_arg_pos;
136                 assert(depth == 0);
137                 start = end_arg_pos;
138         }
139         return output;
140 }
141
142 EffectChain::Phase EffectChain::compile_glsl_program(unsigned start_index, unsigned end_index)
143 {
144         bool input_needs_mipmaps = false;
145         std::string frag_shader = read_file("header.frag");
146         for (unsigned i = start_index; i < end_index; ++i) {
147                 char effect_id[256];
148                 sprintf(effect_id, "eff%d", i);
149         
150                 frag_shader += "\n";
151                 frag_shader += std::string("#define FUNCNAME ") + effect_id + "\n";
152                 frag_shader += replace_prefix(effects[i]->output_convenience_uniforms(), effect_id);
153                 frag_shader += replace_prefix(effects[i]->output_fragment_shader(), effect_id);
154                 frag_shader += "#undef PREFIX\n";
155                 frag_shader += "#undef FUNCNAME\n";
156                 frag_shader += "#undef LAST_INPUT\n";
157                 frag_shader += std::string("#define LAST_INPUT ") + effect_id + "\n";
158                 frag_shader += "\n";
159
160                 input_needs_mipmaps |= effects[i]->needs_mipmaps();
161         }
162         frag_shader.append(read_file("footer.frag"));
163         printf("%s\n", frag_shader.c_str());
164         
165         GLuint glsl_program_num = glCreateProgram();
166         GLuint vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
167         GLuint fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
168         glAttachShader(glsl_program_num, vs_obj);
169         check_error();
170         glAttachShader(glsl_program_num, fs_obj);
171         check_error();
172         glLinkProgram(glsl_program_num);
173         check_error();
174
175         Phase phase;
176         phase.glsl_program_num = glsl_program_num;
177         phase.input_needs_mipmaps = input_needs_mipmaps;
178         phase.start = start_index;
179         phase.end = end_index;
180
181         return phase;
182 }
183
184 void EffectChain::finalize()
185 {
186         // Add normalizers to get the output format right.
187         if (current_color_space != output_format.color_space) {
188                 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
189                 colorspace_conversion->set_int("source_space", current_color_space);
190                 colorspace_conversion->set_int("destination_space", output_format.color_space);
191                 effects.push_back(colorspace_conversion);
192                 current_color_space = output_format.color_space;
193         }
194         if (current_gamma_curve != output_format.gamma_curve) {
195                 if (current_gamma_curve != GAMMA_LINEAR) {
196                         normalize_to_linear_gamma();
197                 }
198                 assert(current_gamma_curve == GAMMA_LINEAR);
199                 GammaCompressionEffect *gamma_conversion = new GammaCompressionEffect();
200                 gamma_conversion->set_int("destination_curve", output_format.gamma_curve);
201                 effects.push_back(gamma_conversion);
202                 current_gamma_curve = output_format.gamma_curve;
203         }
204
205         // Construct the GLSL programs. We end a program every time we come
206         // to an effect marked as "needs many samples" (ie. "please let me
207         // sample directly from a texture, with no arithmetic in-between"),
208         // and of course at the end.
209         unsigned start = 0;
210         for (unsigned i = 0; i < effects.size(); ++i) {
211                 if (effects[i]->needs_many_samples() && i != start) {
212                         phases.push_back(compile_glsl_program(start, i));
213                         start = i;
214                 }
215         }
216         phases.push_back(compile_glsl_program(start, effects.size()));
217
218         // If we have more than one phase, we need intermediate render-to-texture.
219         // Construct an FBO, and then as many textures as we need.
220         if (phases.size() > 1) {
221                 glGenFramebuffers(1, &fbo);
222
223                 unsigned num_textures = std::max<int>(phases.size() - 1, 2);
224                 glGenTextures(num_textures, temp_textures);
225
226                 for (unsigned i = 0; i < num_textures; ++i) {
227                         glBindTexture(GL_TEXTURE_2D, temp_textures[i]);
228                         check_error();
229                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
230                         check_error();
231                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
232                         check_error();
233                         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
234                         check_error();
235                 }
236         }
237         
238         // Translate the input format to OpenGL's enums.
239         GLenum internal_format;
240         if (use_srgb_texture_format) {
241                 internal_format = GL_SRGB8;
242         } else {
243                 internal_format = GL_RGBA8;
244         }
245         if (input_format.pixel_format == FORMAT_RGB) {
246                 format = GL_RGB;
247                 bytes_per_pixel = 3;
248         } else if (input_format.pixel_format == FORMAT_RGBA) {
249                 format = GL_RGBA;
250                 bytes_per_pixel = 4;
251         } else if (input_format.pixel_format == FORMAT_BGR) {
252                 format = GL_BGR;
253                 bytes_per_pixel = 3;
254         } else if (input_format.pixel_format == FORMAT_BGRA) {
255                 format = GL_BGRA;
256                 bytes_per_pixel = 4;
257         } else {
258                 assert(false);
259         }
260
261         // Create PBO to hold the texture holding the input image, and then the texture itself.
262         glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 2);
263         check_error();
264         glBufferData(GL_PIXEL_UNPACK_BUFFER_ARB, width * height * bytes_per_pixel, NULL, GL_STREAM_DRAW);
265         check_error();
266
267         void *mapped_pbo = glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_WRITE_ONLY);
268         memset(mapped_pbo, 0, width * height * bytes_per_pixel);
269         glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB);
270         check_error();
271         
272         glGenTextures(1, &source_image_num);
273         check_error();
274         glBindTexture(GL_TEXTURE_2D, source_image_num);
275         check_error();
276         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
277         check_error();
278         glTexImage2D(GL_TEXTURE_2D, 0, internal_format, width, height, 0, format, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0));
279         check_error();
280         glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
281         check_error();
282
283         finalized = true;
284 }
285
286 void EffectChain::render_to_screen(unsigned char *src)
287 {
288         assert(finalized);
289
290         // Copy the pixel data into the PBO.
291         glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 2);
292         check_error();
293         void *mapped_pbo = glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_WRITE_ONLY);
294         memcpy(mapped_pbo, src, width * height * bytes_per_pixel);
295         glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB);
296         check_error();
297
298         // Re-upload the texture from the PBO.
299         glActiveTexture(GL_TEXTURE0);
300         check_error();
301         glBindTexture(GL_TEXTURE_2D, source_image_num);
302         check_error();
303         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0));
304         check_error();
305         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
306         check_error();
307         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
308         check_error();
309
310         // Intel/Mesa seems to have a broken glGenerateMipmap() for non-FBO textures, so do it here.
311         glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, phases[0].input_needs_mipmaps ? GL_TRUE : GL_FALSE);
312         check_error();
313
314         glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
315         check_error();
316
317         // Basic state.
318         glDisable(GL_BLEND);
319         check_error();
320         glDisable(GL_DEPTH_TEST);
321         check_error();
322         glDepthMask(GL_FALSE);
323         check_error();
324
325         glMatrixMode(GL_PROJECTION);
326         glLoadIdentity();
327         glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
328
329         glMatrixMode(GL_MODELVIEW);
330         glLoadIdentity();
331
332         if (phases.size() > 1) {
333                 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
334                 check_error();
335         }
336
337         for (unsigned phase = 0; phase < phases.size(); ++phase) {
338                 // Set up inputs and outputs for this phase.
339                 glActiveTexture(GL_TEXTURE0);
340                 if (phase == 0) {
341                         // First phase reads from the input texture (which is already bound).
342                 } else {
343                         glBindTexture(GL_TEXTURE_2D, temp_textures[(phase + 1) % 2]);
344                         check_error();
345                 }
346                 if (phases[phase].input_needs_mipmaps) {
347                         if (phase != 0) {
348                                 // For phase 0, it's done further up.
349                                 glGenerateMipmap(GL_TEXTURE_2D);
350                                 check_error();
351                         }
352                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
353                         check_error();
354                 } else {
355                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
356                         check_error();
357                 }
358
359                 if (phase == phases.size() - 1) {
360                         // Last phase goes directly to the screen.
361                         glBindFramebuffer(GL_FRAMEBUFFER, 0);
362                         check_error();
363                 } else {
364                         glFramebufferTexture2D(
365                                 GL_FRAMEBUFFER,
366                                 GL_COLOR_ATTACHMENT0,
367                                 GL_TEXTURE_2D,
368                                 temp_textures[phase % 2],
369                                 0);
370                         check_error();
371                 }
372
373                 // We have baked an upside-down transform into the quad coordinates,
374                 // since the typical graphics program will have the origin at the upper-left,
375                 // while OpenGL uses lower-left. In the next ones, however, the origin
376                 // is all right, and we need to reverse that.
377                 if (phase == 1) {
378                         glTranslatef(0.0f, 1.0f, 0.0f);
379                         glScalef(1.0f, -1.0f, 1.0f);
380                 }
381
382                 // Give the required parameters to all the effects.
383                 glUseProgram(phases[phase].glsl_program_num);
384                 check_error();
385
386                 glUniform1i(glGetUniformLocation(phases[phase].glsl_program_num, "input_tex"), 0);
387                 check_error();
388
389                 unsigned sampler_num = 1;
390                 for (unsigned i = phases[phase].start; i < phases[phase].end; ++i) {
391                         char effect_id[256];
392                         sprintf(effect_id, "eff%d", i);
393                         effects[i]->set_uniforms(phases[phase].glsl_program_num, effect_id, &sampler_num);
394                 }
395
396                 // Now draw!
397                 glBegin(GL_QUADS);
398
399                 glTexCoord2f(0.0f, 1.0f);
400                 glVertex2f(0.0f, 0.0f);
401
402                 glTexCoord2f(1.0f, 1.0f);
403                 glVertex2f(1.0f, 0.0f);
404
405                 glTexCoord2f(1.0f, 0.0f);
406                 glVertex2f(1.0f, 1.0f);
407
408                 glTexCoord2f(0.0f, 0.0f);
409                 glVertex2f(0.0f, 1.0f);
410
411                 glEnd();
412                 check_error();
413
414                 // HACK
415                 glActiveTexture(GL_TEXTURE0);
416                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
417                 check_error();
418                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1000);
419                 check_error();
420         }
421 }