Fix an issue where a (cached) shader program could be used from multiple
[movit] / resource_pool.cpp
1 #include <assert.h>
2 #include <pthread.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <algorithm>
6 #include <map>
7 #include <string>
8 #include <utility>
9 #include <epoxy/gl.h>
10
11 #include "init.h"
12 #include "resource_pool.h"
13 #include "util.h"
14
15 using namespace std;
16
17 namespace movit {
18
19 ResourcePool::ResourcePool(size_t program_freelist_max_length,
20                            size_t texture_freelist_max_bytes,
21                            size_t fbo_freelist_max_length)
22         : program_freelist_max_length(program_freelist_max_length),
23           texture_freelist_max_bytes(texture_freelist_max_bytes),
24           fbo_freelist_max_length(fbo_freelist_max_length),
25           texture_freelist_bytes(0)
26 {
27         pthread_mutex_init(&lock, NULL);
28 }
29
30 ResourcePool::~ResourcePool()
31 {
32         assert(program_refcount.empty());
33
34         for (list<GLuint>::const_iterator freelist_it = program_freelist.begin();
35              freelist_it != program_freelist.end();
36              ++freelist_it) {
37                 delete_program(*freelist_it);
38         }
39         assert(programs.empty());
40         assert(program_shaders.empty());
41
42         for (list<GLuint>::const_iterator freelist_it = texture_freelist.begin();
43              freelist_it != texture_freelist.end();
44              ++freelist_it) {
45                 GLuint free_texture_num = *freelist_it;
46                 assert(texture_formats.count(free_texture_num) != 0);
47                 texture_freelist_bytes -= estimate_texture_size(texture_formats[free_texture_num]);
48                 texture_formats.erase(free_texture_num);
49                 glDeleteTextures(1, &free_texture_num);
50                 check_error();
51         }
52         assert(texture_formats.empty());
53         assert(texture_freelist_bytes == 0);
54
55         void *context = get_gl_context_identifier();
56         cleanup_unlinked_fbos(context);
57
58         for (map<void *, std::list<FBOFormatIterator> >::iterator context_it = fbo_freelist.begin();
59              context_it != fbo_freelist.end();
60              ++context_it) {
61                 if (context_it->first != context) {
62                         // If this does not hold, the client should have called clean_context() earlier.
63                         assert(context_it->second.empty());
64                         continue;
65                 }
66                 for (list<FBOFormatIterator>::const_iterator freelist_it = context_it->second.begin();
67                      freelist_it != context_it->second.end();
68                      ++freelist_it) {
69                         FBOFormatIterator fbo_it = *freelist_it;
70                         glDeleteFramebuffers(1, &fbo_it->second.fbo_num);
71                         check_error();
72                         fbo_formats.erase(fbo_it);
73                 }
74         }
75
76         assert(fbo_formats.empty());
77 }
78
79 void ResourcePool::delete_program(GLuint glsl_program_num)
80 {
81         bool found_program = false;
82         for (map<pair<string, string>, GLuint>::iterator program_it = programs.begin();
83              program_it != programs.end();
84              ++program_it) {
85                 if (program_it->second == glsl_program_num) {
86                         programs.erase(program_it);
87                         found_program = true;
88                         break;
89                 }
90         }
91         assert(found_program);
92
93         map<GLuint, stack<GLuint> >::iterator instance_list_it = program_instances.find(glsl_program_num);
94         assert(instance_list_it != program_instances.end());
95
96         while (!instance_list_it->second.empty()) {
97                 GLuint instance_program_num = instance_list_it->second.top();
98                 instance_list_it->second.pop();
99                 glDeleteProgram(instance_program_num);
100                 program_masters.erase(instance_program_num);
101         }
102         program_instances.erase(instance_list_it);
103
104         map<GLuint, ShaderSpec>::iterator shader_it =
105                 program_shaders.find(glsl_program_num);
106         assert(shader_it != program_shaders.end());
107
108         glDeleteShader(shader_it->second.vs_obj);
109         glDeleteShader(shader_it->second.fs_obj);
110         program_shaders.erase(shader_it);
111 }
112
113 GLuint ResourcePool::compile_glsl_program(const string& vertex_shader,
114                                           const string& fragment_shader,
115                                           const vector<string>& fragment_shader_outputs)
116 {
117         GLuint glsl_program_num;
118         pthread_mutex_lock(&lock);
119
120         // Augment the fragment shader program text with the outputs, so that they become
121         // part of the key. Also potentially useful for debugging.
122         string fragment_shader_processed = fragment_shader;
123         for (unsigned output_index = 0; output_index < fragment_shader_outputs.size(); ++output_index) {
124                 char buf[256];
125                 snprintf(buf, sizeof(buf), "// Bound output: %s\n", fragment_shader_outputs[output_index].c_str());
126                 fragment_shader_processed += buf;
127         }
128
129         const pair<string, string> key(vertex_shader, fragment_shader_processed);
130         if (programs.count(key)) {
131                 // Already in the cache. Increment the refcount, or take it off the freelist
132                 // if it's zero.
133                 glsl_program_num = programs[key];
134                 map<GLuint, int>::iterator refcount_it = program_refcount.find(glsl_program_num);
135                 if (refcount_it != program_refcount.end()) {
136                         ++refcount_it->second;
137                 } else {
138                         list<GLuint>::iterator freelist_it =
139                                 find(program_freelist.begin(), program_freelist.end(), glsl_program_num);
140                         assert(freelist_it != program_freelist.end());
141                         program_freelist.erase(freelist_it);
142                         program_refcount.insert(make_pair(glsl_program_num, 1));
143                 }
144         } else {
145                 // Not in the cache. Compile the shaders.
146                 GLuint vs_obj = compile_shader(vertex_shader, GL_VERTEX_SHADER);
147                 check_error();
148                 GLuint fs_obj = compile_shader(fragment_shader_processed, GL_FRAGMENT_SHADER);
149                 check_error();
150                 glsl_program_num = link_program(vs_obj, fs_obj, fragment_shader_outputs);
151
152                 if (movit_debug_level == MOVIT_DEBUG_ON) {
153                         // Output shader to a temporary file, for easier debugging.
154                         static int compiled_shader_num = 0;
155                         char filename[256];
156                         sprintf(filename, "chain-%03d.frag", compiled_shader_num++);
157                         FILE *fp = fopen(filename, "w");
158                         if (fp == NULL) {
159                                 perror(filename);
160                                 exit(1);
161                         }
162                         fprintf(fp, "%s\n", fragment_shader_processed.c_str());
163                         fclose(fp);
164                 }
165
166                 programs.insert(make_pair(key, glsl_program_num));
167                 program_refcount.insert(make_pair(glsl_program_num, 1));
168                 ShaderSpec spec;
169                 spec.vs_obj = vs_obj;
170                 spec.fs_obj = fs_obj;
171                 spec.fragment_shader_outputs = fragment_shader_outputs;
172                 program_shaders.insert(make_pair(glsl_program_num, spec));
173                 stack<GLuint> instances;
174                 instances.push(glsl_program_num);
175                 program_instances.insert(make_pair(glsl_program_num, instances));
176                 program_masters.insert(make_pair(glsl_program_num, glsl_program_num));
177         }
178         pthread_mutex_unlock(&lock);
179         return glsl_program_num;
180 }
181
182 GLuint ResourcePool::link_program(GLuint vs_obj,
183                                   GLuint fs_obj,
184                                   const vector<string>& fragment_shader_outputs)
185 {
186         GLuint glsl_program_num = glCreateProgram();
187         check_error();
188         glAttachShader(glsl_program_num, vs_obj);
189         check_error();
190         glAttachShader(glsl_program_num, fs_obj);
191         check_error();
192
193         // Bind the outputs, if we have multiple ones.
194         if (fragment_shader_outputs.size() > 1) {
195                 for (unsigned output_index = 0; output_index < fragment_shader_outputs.size(); ++output_index) {
196                         glBindFragDataLocation(glsl_program_num, output_index,
197                                                fragment_shader_outputs[output_index].c_str());
198                 }
199         }
200
201         glLinkProgram(glsl_program_num);
202         check_error();
203
204         GLint success;
205         glGetProgramiv(glsl_program_num, GL_LINK_STATUS, &success);
206         if (success == GL_FALSE) {
207                 GLchar error_log[1024] = {0};
208                 glGetProgramInfoLog(glsl_program_num, 1024, NULL, error_log);
209                 fprintf(stderr, "Error linking program: %s\n", error_log);
210                 exit(1);
211         }
212
213         return glsl_program_num;
214 }
215
216 void ResourcePool::release_glsl_program(GLuint glsl_program_num)
217 {
218         pthread_mutex_lock(&lock);
219         map<GLuint, int>::iterator refcount_it = program_refcount.find(glsl_program_num);
220         assert(refcount_it != program_refcount.end());
221
222         if (--refcount_it->second == 0) {
223                 program_refcount.erase(refcount_it);
224                 assert(find(program_freelist.begin(), program_freelist.end(), glsl_program_num)
225                         == program_freelist.end());
226                 program_freelist.push_front(glsl_program_num);
227                 if (program_freelist.size() > program_freelist_max_length) {
228                         delete_program(program_freelist.back());
229                         program_freelist.pop_back();
230                 }
231         }
232
233         pthread_mutex_unlock(&lock);
234 }
235
236 GLuint ResourcePool::use_glsl_program(GLuint glsl_program_num)
237 {
238         pthread_mutex_lock(&lock);
239         assert(program_instances.count(glsl_program_num));
240         stack<GLuint> &instances = program_instances[glsl_program_num];
241
242         GLuint instance_program_num;
243         if (!instances.empty()) {
244                 // There's an unused instance of this program; just return it.
245                 instance_program_num = instances.top();
246                 instances.pop();
247         } else {
248                 // We need to clone this program. (unuse_glsl_program()
249                 // will later put it onto the list.)
250                 map<GLuint, ShaderSpec>::iterator shader_it =
251                         program_shaders.find(glsl_program_num);
252                 assert(shader_it != program_shaders.end());
253
254                 instance_program_num = link_program(
255                         shader_it->second.vs_obj,
256                         shader_it->second.fs_obj,
257                         shader_it->second.fragment_shader_outputs);
258                 program_masters.insert(make_pair(instance_program_num, glsl_program_num));
259         }
260         pthread_mutex_unlock(&lock);
261
262         glUseProgram(instance_program_num);
263         return instance_program_num;
264 }
265
266 void ResourcePool::unuse_glsl_program(GLuint instance_program_num)
267 {
268         pthread_mutex_lock(&lock);
269
270         map<GLuint, GLuint>::const_iterator master_it = program_masters.find(instance_program_num);
271         assert(master_it != program_masters.end());
272
273         assert(program_instances.count(master_it->second));
274         stack<GLuint> &instances = program_instances[master_it->second];
275
276         instances.push(instance_program_num);
277
278         pthread_mutex_unlock(&lock);
279 }
280
281 GLuint ResourcePool::create_2d_texture(GLint internal_format, GLsizei width, GLsizei height)
282 {
283         assert(width > 0);
284         assert(height > 0);
285
286         pthread_mutex_lock(&lock);
287         // See if there's a texture on the freelist we can use.
288         for (list<GLuint>::iterator freelist_it = texture_freelist.begin();
289              freelist_it != texture_freelist.end();
290              ++freelist_it) {
291                 GLuint texture_num = *freelist_it;
292                 map<GLuint, Texture2D>::const_iterator format_it = texture_formats.find(texture_num);
293                 assert(format_it != texture_formats.end());
294                 if (format_it->second.internal_format == internal_format &&
295                     format_it->second.width == width &&
296                     format_it->second.height == height) {
297                         texture_freelist_bytes -= estimate_texture_size(format_it->second);
298                         texture_freelist.erase(freelist_it);
299                         pthread_mutex_unlock(&lock);
300                         return texture_num;
301                 }
302         }
303
304         // Find any reasonable format given the internal format; OpenGL validates it
305         // even though we give NULL as pointer.
306         GLenum format;
307         switch (internal_format) {
308         case GL_RGBA32F_ARB:
309         case GL_RGBA16F_ARB:
310         case GL_RGBA8:
311         case GL_RGB10_A2:
312         case GL_SRGB8_ALPHA8:
313                 format = GL_RGBA;
314                 break;
315         case GL_RGB32F:
316         case GL_RGB16F:
317         case GL_R11F_G11F_B10F:
318         case GL_RGB8:
319         case GL_RGB10:
320         case GL_SRGB8:
321         case GL_RGB565:
322         case GL_RGB9_E5:
323                 format = GL_RGB;
324                 break;
325         case GL_RG32F:
326         case GL_RG16F:
327         case GL_RG8:
328                 format = GL_RG;
329                 break;
330         case GL_R32F:
331         case GL_R16F:
332         case GL_R8:
333                 format = GL_RED;
334                 break;
335         default:
336                 // TODO: Add more here as needed.
337                 assert(false);
338         }
339
340         // Same with type; GLES is stricter than desktop OpenGL here.
341         GLenum type;
342         switch (internal_format) {
343         case GL_RGBA32F_ARB:
344         case GL_RGBA16F_ARB:
345         case GL_RGB32F:
346         case GL_RGB16F:
347         case GL_R11F_G11F_B10F:
348         case GL_RGB9_E5:
349         case GL_RG32F:
350         case GL_RG16F:
351         case GL_R32F:
352         case GL_R16F:
353                 type = GL_FLOAT;
354                 break;
355         case GL_SRGB8_ALPHA8:
356         case GL_SRGB8:
357         case GL_RGBA8:
358         case GL_RGB8:
359         case GL_RGB10_A2:
360         case GL_RGB10:
361         case GL_RG8:
362         case GL_R8:
363                 type = GL_UNSIGNED_BYTE;
364                 break;
365         case GL_RGB565:
366                 type = GL_UNSIGNED_SHORT_5_6_5;
367                 break;
368         default:
369                 // TODO: Add more here as needed.
370                 assert(false);
371         }
372
373
374         GLuint texture_num;
375         glGenTextures(1, &texture_num);
376         check_error();
377         glBindTexture(GL_TEXTURE_2D, texture_num);
378         check_error();
379         glTexImage2D(GL_TEXTURE_2D, 0, internal_format, width, height, 0, format, type, NULL);
380         check_error();
381         glBindTexture(GL_TEXTURE_2D, 0);
382         check_error();
383
384         Texture2D texture_format;
385         texture_format.internal_format = internal_format;
386         texture_format.width = width;
387         texture_format.height = height;
388         assert(texture_formats.count(texture_num) == 0);
389         texture_formats.insert(make_pair(texture_num, texture_format));
390
391         pthread_mutex_unlock(&lock);
392         return texture_num;
393 }
394
395 void ResourcePool::release_2d_texture(GLuint texture_num)
396 {
397         pthread_mutex_lock(&lock);
398         texture_freelist.push_front(texture_num);
399         assert(texture_formats.count(texture_num) != 0);
400         texture_freelist_bytes += estimate_texture_size(texture_formats[texture_num]);
401
402         while (texture_freelist_bytes > texture_freelist_max_bytes) {
403                 GLuint free_texture_num = texture_freelist.back();
404                 texture_freelist.pop_back();
405                 assert(texture_formats.count(free_texture_num) != 0);
406                 texture_freelist_bytes -= estimate_texture_size(texture_formats[free_texture_num]);
407                 texture_formats.erase(free_texture_num);
408                 glDeleteTextures(1, &free_texture_num);
409                 check_error();
410
411                 // Unlink any lingering FBO related to this texture. We might
412                 // not be in the right context, so don't delete it right away;
413                 // the cleanup in release_fbo() (which calls cleanup_unlinked_fbos())
414                 // will take care of actually doing that later.
415                 for (map<pair<void *, GLuint>, FBO>::iterator format_it = fbo_formats.begin();
416                      format_it != fbo_formats.end();
417                      ++format_it) {
418                         for (unsigned i = 0; i < num_fbo_attachments; ++i) {
419                                 if (format_it->second.texture_num[i] == free_texture_num) {
420                                         format_it->second.texture_num[i] = GL_INVALID_INDEX;
421                                 }
422                         }
423                 }
424         }
425         pthread_mutex_unlock(&lock);
426 }
427
428 GLuint ResourcePool::create_fbo(GLuint texture0_num, GLuint texture1_num, GLuint texture2_num, GLuint texture3_num)
429 {
430         void *context = get_gl_context_identifier();
431
432         // Make sure we are filled from the bottom.
433         assert(texture0_num != 0);
434         if (texture1_num == 0) {
435                 assert(texture2_num == 0);
436         }
437         if (texture2_num == 0) {
438                 assert(texture3_num == 0);
439         }
440
441         pthread_mutex_lock(&lock);
442         if (fbo_freelist.count(context) != 0) {
443                 // See if there's an FBO on the freelist we can use.
444                 list<FBOFormatIterator>::iterator end = fbo_freelist[context].end();
445                 for (list<FBOFormatIterator>::iterator freelist_it = fbo_freelist[context].begin();
446                      freelist_it != end; ++freelist_it) {
447                         FBOFormatIterator fbo_it = *freelist_it;
448                         if (fbo_it->second.texture_num[0] == texture0_num &&
449                             fbo_it->second.texture_num[1] == texture1_num &&
450                             fbo_it->second.texture_num[2] == texture2_num &&
451                             fbo_it->second.texture_num[3] == texture3_num) {
452                                 fbo_freelist[context].erase(freelist_it);
453                                 pthread_mutex_unlock(&lock);
454                                 return fbo_it->second.fbo_num;
455                         }
456                 }
457         }
458
459         // Create a new one.
460         FBO fbo_format;
461         fbo_format.texture_num[0] = texture0_num;
462         fbo_format.texture_num[1] = texture1_num;
463         fbo_format.texture_num[2] = texture2_num;
464         fbo_format.texture_num[3] = texture3_num;
465
466         glGenFramebuffers(1, &fbo_format.fbo_num);
467         check_error();
468         glBindFramebuffer(GL_FRAMEBUFFER, fbo_format.fbo_num);
469         check_error();
470
471         GLenum bufs[num_fbo_attachments];
472         unsigned num_active_attachments = 0;
473         for (unsigned i = 0; i < num_fbo_attachments; ++i, ++num_active_attachments) {
474                 if (fbo_format.texture_num[i] == 0) {
475                         break;
476                 }
477                 glFramebufferTexture2D(
478                         GL_FRAMEBUFFER,
479                         GL_COLOR_ATTACHMENT0 + i,
480                         GL_TEXTURE_2D,
481                         fbo_format.texture_num[i],
482                         0);
483                 check_error();
484                 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
485         }
486
487         glDrawBuffers(num_active_attachments, bufs);
488         check_error();
489
490         GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
491         assert(status == GL_FRAMEBUFFER_COMPLETE);
492         glBindFramebuffer(GL_FRAMEBUFFER, 0);
493         check_error();
494
495         pair<void *, GLuint> key(context, fbo_format.fbo_num);
496         assert(fbo_formats.count(key) == 0);
497         fbo_formats.insert(make_pair(key, fbo_format));
498
499         pthread_mutex_unlock(&lock);
500         return fbo_format.fbo_num;
501 }
502
503 void ResourcePool::release_fbo(GLuint fbo_num)
504 {
505         void *context = get_gl_context_identifier();
506
507         pthread_mutex_lock(&lock);
508         FBOFormatIterator fbo_it = fbo_formats.find(make_pair(context, fbo_num));
509         assert(fbo_it != fbo_formats.end());
510         fbo_freelist[context].push_front(fbo_it);
511
512         // Now that we're in this context, free up any FBOs that are connected
513         // to deleted textures (in release_2d_texture).
514         cleanup_unlinked_fbos(context);
515
516         shrink_fbo_freelist(context, fbo_freelist_max_length);
517         pthread_mutex_unlock(&lock);
518 }
519
520 void ResourcePool::clean_context()
521 {
522         void *context = get_gl_context_identifier();
523
524         // Currently, we only need to worry about FBOs, as they are the only
525         // non-shareable resource we hold.
526         shrink_fbo_freelist(context, 0);
527         fbo_freelist.erase(context);
528 }
529
530 void ResourcePool::cleanup_unlinked_fbos(void *context)
531 {
532         list<FBOFormatIterator>::iterator end = fbo_freelist[context].end();
533         for (list<FBOFormatIterator>::iterator freelist_it = fbo_freelist[context].begin(); freelist_it != end; ) {
534                 FBOFormatIterator fbo_it = *freelist_it;
535
536                 bool all_unlinked = true;
537                 for (unsigned i = 0; i < num_fbo_attachments; ++i) {
538                         if (fbo_it->second.texture_num[i] != 0 &&
539                             fbo_it->second.texture_num[i] != GL_INVALID_INDEX) {
540                                 all_unlinked = false;
541                                 break;
542                         }
543                 }
544                 if (all_unlinked) {
545                         glDeleteFramebuffers(1, &fbo_it->second.fbo_num);
546                         check_error();
547                         fbo_formats.erase(fbo_it);
548                         fbo_freelist[context].erase(freelist_it++);
549                 } else {
550                         freelist_it++;
551                 }
552         }
553 }
554
555 void ResourcePool::shrink_fbo_freelist(void *context, size_t max_length)
556 {
557         list<FBOFormatIterator> &freelist = fbo_freelist[context];
558         while (freelist.size() > max_length) {
559                 FBOFormatIterator free_fbo_it = freelist.back();
560                 glDeleteFramebuffers(1, &free_fbo_it->second.fbo_num);
561                 check_error();
562                 fbo_formats.erase(free_fbo_it);
563                 freelist.pop_back();
564         }
565 }
566
567 size_t ResourcePool::estimate_texture_size(const Texture2D &texture_format)
568 {
569         size_t bytes_per_pixel;
570
571         switch (texture_format.internal_format) {
572         case GL_RGBA32F_ARB:
573                 bytes_per_pixel = 16;
574                 break;
575         case GL_RGBA16F_ARB:
576                 bytes_per_pixel = 8;
577                 break;
578         case GL_RGB32F_ARB:
579                 bytes_per_pixel = 12;
580                 break;
581         case GL_RGB16F_ARB:
582                 bytes_per_pixel = 6;
583                 break;
584         case GL_R11F_G11F_B10F:
585                 bytes_per_pixel = 4;
586                 break;
587         case GL_RGB9_E5:
588                 bytes_per_pixel = 4;
589                 break;
590         case GL_RGBA8:
591         case GL_SRGB8_ALPHA8:
592         case GL_RGB10_A2:
593         case GL_RGB10:
594                 bytes_per_pixel = 4;
595                 break;
596         case GL_RGB8:
597         case GL_SRGB8:
598                 bytes_per_pixel = 3;
599                 break;
600         case GL_RG32F:
601                 bytes_per_pixel = 8;
602                 break;
603         case GL_RG16F:
604                 bytes_per_pixel = 4;
605                 break;
606         case GL_R32F:
607                 bytes_per_pixel = 4;
608                 break;
609         case GL_R16F:
610                 bytes_per_pixel = 2;
611                 break;
612         case GL_RG8:
613                 bytes_per_pixel = 2;
614                 break;
615         case GL_R8:
616                 bytes_per_pixel = 1;
617                 break;
618         case GL_RGB565:
619                 bytes_per_pixel = 2;
620                 break;
621         default:
622                 // TODO: Add more here as needed.
623                 assert(false);
624         }
625
626         return texture_format.width * texture_format.height * bytes_per_pixel;
627 }
628
629 }  // namespace movit