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