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