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