]> git.sesse.net Git - movit/blob - effect_chain.cpp
Yet another use-NULL-instead-of-giving-in-empty-stuff cleanup.
[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         glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
267         check_error();
268         
269         glGenTextures(1, &source_image_num);
270         check_error();
271         glBindTexture(GL_TEXTURE_2D, source_image_num);
272         check_error();
273         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
274         check_error();
275         glTexImage2D(GL_TEXTURE_2D, 0, internal_format, width, height, 0, format, GL_UNSIGNED_BYTE, NULL);
276         check_error();
277
278         finalized = true;
279 }
280
281 void EffectChain::render_to_screen(unsigned char *src)
282 {
283         assert(finalized);
284
285         // Copy the pixel data into the PBO.
286         glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 2);
287         check_error();
288         void *mapped_pbo = glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_WRITE_ONLY);
289         memcpy(mapped_pbo, src, width * height * bytes_per_pixel);
290         glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB);
291         check_error();
292
293         // Re-upload the texture from the PBO.
294         glActiveTexture(GL_TEXTURE0);
295         check_error();
296         glBindTexture(GL_TEXTURE_2D, source_image_num);
297         check_error();
298         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0));
299         check_error();
300         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
301         check_error();
302         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
303         check_error();
304
305         // Intel/Mesa seems to have a broken glGenerateMipmap() for non-FBO textures, so do it here.
306         glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, phases[0].input_needs_mipmaps ? GL_TRUE : GL_FALSE);
307         check_error();
308
309         glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
310         check_error();
311
312         // Basic state.
313         glDisable(GL_BLEND);
314         check_error();
315         glDisable(GL_DEPTH_TEST);
316         check_error();
317         glDepthMask(GL_FALSE);
318         check_error();
319
320         glMatrixMode(GL_PROJECTION);
321         glLoadIdentity();
322         glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
323
324         glMatrixMode(GL_MODELVIEW);
325         glLoadIdentity();
326
327         if (phases.size() > 1) {
328                 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
329                 check_error();
330         }
331
332         for (unsigned phase = 0; phase < phases.size(); ++phase) {
333                 // Set up inputs and outputs for this phase.
334                 glActiveTexture(GL_TEXTURE0);
335                 if (phase == 0) {
336                         // First phase reads from the input texture (which is already bound).
337                 } else {
338                         glBindTexture(GL_TEXTURE_2D, temp_textures[(phase + 1) % 2]);
339                         check_error();
340                 }
341                 if (phases[phase].input_needs_mipmaps) {
342                         if (phase != 0) {
343                                 // For phase 0, it's done further up.
344                                 glGenerateMipmap(GL_TEXTURE_2D);
345                                 check_error();
346                         }
347                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
348                         check_error();
349                 } else {
350                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
351                         check_error();
352                 }
353
354                 if (phase == phases.size() - 1) {
355                         // Last phase goes directly to the screen.
356                         glBindFramebuffer(GL_FRAMEBUFFER, 0);
357                         check_error();
358                 } else {
359                         glFramebufferTexture2D(
360                                 GL_FRAMEBUFFER,
361                                 GL_COLOR_ATTACHMENT0,
362                                 GL_TEXTURE_2D,
363                                 temp_textures[phase % 2],
364                                 0);
365                         check_error();
366                 }
367
368                 // We have baked an upside-down transform into the quad coordinates,
369                 // since the typical graphics program will have the origin at the upper-left,
370                 // while OpenGL uses lower-left. In the next ones, however, the origin
371                 // is all right, and we need to reverse that.
372                 if (phase == 1) {
373                         glTranslatef(0.0f, 1.0f, 0.0f);
374                         glScalef(1.0f, -1.0f, 1.0f);
375                 }
376
377                 // Give the required parameters to all the effects.
378                 glUseProgram(phases[phase].glsl_program_num);
379                 check_error();
380
381                 glUniform1i(glGetUniformLocation(phases[phase].glsl_program_num, "input_tex"), 0);
382                 check_error();
383
384                 unsigned sampler_num = 1;
385                 for (unsigned i = phases[phase].start; i < phases[phase].end; ++i) {
386                         char effect_id[256];
387                         sprintf(effect_id, "eff%d", i);
388                         effects[i]->set_uniforms(phases[phase].glsl_program_num, effect_id, &sampler_num);
389                 }
390
391                 // Now draw!
392                 glBegin(GL_QUADS);
393
394                 glTexCoord2f(0.0f, 1.0f);
395                 glVertex2f(0.0f, 0.0f);
396
397                 glTexCoord2f(1.0f, 1.0f);
398                 glVertex2f(1.0f, 0.0f);
399
400                 glTexCoord2f(1.0f, 0.0f);
401                 glVertex2f(1.0f, 1.0f);
402
403                 glTexCoord2f(0.0f, 0.0f);
404                 glVertex2f(0.0f, 1.0f);
405
406                 glEnd();
407                 check_error();
408
409                 // HACK
410                 glActiveTexture(GL_TEXTURE0);
411                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
412                 check_error();
413                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1000);
414                 check_error();
415         }
416 }