]> git.sesse.net Git - movit/blob - resource_pool.cpp
Use ryg's much faster fp16 conversion code.
[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         glDeleteProgram(glsl_program_num);
93
94         map<GLuint, pair<GLuint, GLuint> >::iterator shader_it =
95                 program_shaders.find(glsl_program_num);
96         assert(shader_it != program_shaders.end());
97
98         glDeleteShader(shader_it->second.first);
99         glDeleteShader(shader_it->second.second);
100         program_shaders.erase(shader_it);
101 }
102
103 GLuint ResourcePool::compile_glsl_program(const string& vertex_shader,
104                                           const string& fragment_shader,
105                                           const vector<string>& fragment_shader_outputs)
106 {
107         GLuint glsl_program_num;
108         pthread_mutex_lock(&lock);
109
110         // Augment the fragment shader program text with the outputs, so that they become
111         // part of the key. Also potentially useful for debugging.
112         string fragment_shader_processed = fragment_shader;
113         for (unsigned output_index = 0; output_index < fragment_shader_outputs.size(); ++output_index) {
114                 char buf[256];
115                 snprintf(buf, sizeof(buf), "// Bound output: %s\n", fragment_shader_outputs[output_index].c_str());
116                 fragment_shader_processed += buf;
117         }
118
119         const pair<string, string> key(vertex_shader, fragment_shader_processed);
120         if (programs.count(key)) {
121                 // Already in the cache. Increment the refcount, or take it off the freelist
122                 // if it's zero.
123                 glsl_program_num = programs[key];
124                 map<GLuint, int>::iterator refcount_it = program_refcount.find(glsl_program_num);
125                 if (refcount_it != program_refcount.end()) {
126                         ++refcount_it->second;
127                 } else {
128                         list<GLuint>::iterator freelist_it =
129                                 find(program_freelist.begin(), program_freelist.end(), glsl_program_num);
130                         assert(freelist_it != program_freelist.end());
131                         program_freelist.erase(freelist_it);
132                         program_refcount.insert(make_pair(glsl_program_num, 1));
133                 }
134         } else {
135                 // Not in the cache. Compile the shaders.
136                 glsl_program_num = glCreateProgram();
137                 check_error();
138                 GLuint vs_obj = compile_shader(vertex_shader, GL_VERTEX_SHADER);
139                 check_error();
140                 GLuint fs_obj = compile_shader(fragment_shader_processed, GL_FRAGMENT_SHADER);
141                 check_error();
142                 glAttachShader(glsl_program_num, vs_obj);
143                 check_error();
144                 glAttachShader(glsl_program_num, fs_obj);
145                 check_error();
146
147                 // Bind the outputs, if we have multiple ones.
148                 if (fragment_shader_outputs.size() > 1) {
149                         for (unsigned output_index = 0; output_index < fragment_shader_outputs.size(); ++output_index) {
150                                 glBindFragDataLocation(glsl_program_num, output_index,
151                                                        fragment_shader_outputs[output_index].c_str());
152                         }
153                 }
154
155                 glLinkProgram(glsl_program_num);
156                 check_error();
157
158                 GLint success;
159                 glGetProgramiv(glsl_program_num, GL_LINK_STATUS, &success);
160                 if (success == GL_FALSE) {
161                         GLchar error_log[1024] = {0};
162                         glGetProgramInfoLog(glsl_program_num, 1024, NULL, error_log);
163                         fprintf(stderr, "Error linking program: %s\n", error_log);
164                         exit(1);
165                 }
166
167                 if (movit_debug_level == MOVIT_DEBUG_ON) {
168                         // Output shader to a temporary file, for easier debugging.
169                         static int compiled_shader_num = 0;
170                         char filename[256];
171                         sprintf(filename, "chain-%03d.frag", compiled_shader_num++);
172                         FILE *fp = fopen(filename, "w");
173                         if (fp == NULL) {
174                                 perror(filename);
175                                 exit(1);
176                         }
177                         fprintf(fp, "%s\n", fragment_shader_processed.c_str());
178                         fclose(fp);
179                 }
180
181                 programs.insert(make_pair(key, glsl_program_num));
182                 program_refcount.insert(make_pair(glsl_program_num, 1));
183                 program_shaders.insert(make_pair(glsl_program_num, make_pair(vs_obj, fs_obj)));
184         }
185         pthread_mutex_unlock(&lock);
186         return glsl_program_num;
187 }
188
189 void ResourcePool::release_glsl_program(GLuint glsl_program_num)
190 {
191         pthread_mutex_lock(&lock);
192         map<GLuint, int>::iterator refcount_it = program_refcount.find(glsl_program_num);
193         assert(refcount_it != program_refcount.end());
194
195         if (--refcount_it->second == 0) {
196                 program_refcount.erase(refcount_it);
197                 assert(find(program_freelist.begin(), program_freelist.end(), glsl_program_num)
198                         == program_freelist.end());
199                 program_freelist.push_front(glsl_program_num);
200                 if (program_freelist.size() > program_freelist_max_length) {
201                         delete_program(program_freelist.back());
202                         program_freelist.pop_back();
203                 }
204         }
205
206         pthread_mutex_unlock(&lock);
207 }
208
209 GLuint ResourcePool::create_2d_texture(GLint internal_format, GLsizei width, GLsizei height)
210 {
211         assert(width > 0);
212         assert(height > 0);
213
214         pthread_mutex_lock(&lock);
215         // See if there's a texture on the freelist we can use.
216         for (list<GLuint>::iterator freelist_it = texture_freelist.begin();
217              freelist_it != texture_freelist.end();
218              ++freelist_it) {
219                 GLuint texture_num = *freelist_it;
220                 map<GLuint, Texture2D>::const_iterator format_it = texture_formats.find(texture_num);
221                 assert(format_it != texture_formats.end());
222                 if (format_it->second.internal_format == internal_format &&
223                     format_it->second.width == width &&
224                     format_it->second.height == height) {
225                         texture_freelist_bytes -= estimate_texture_size(format_it->second);
226                         texture_freelist.erase(freelist_it);
227                         pthread_mutex_unlock(&lock);
228                         return texture_num;
229                 }
230         }
231
232         // Find any reasonable format given the internal format; OpenGL validates it
233         // even though we give NULL as pointer.
234         GLenum format;
235         switch (internal_format) {
236         case GL_RGBA32F_ARB:
237         case GL_RGBA16F_ARB:
238         case GL_RGBA8:
239         case GL_SRGB8_ALPHA8:
240                 format = GL_RGBA;
241                 break;
242         case GL_RGB32F:
243         case GL_RGB16F:
244         case GL_RGB8:
245         case GL_SRGB8:
246         case GL_RGB565:
247                 format = GL_RGB;
248                 break;
249         case GL_RG32F:
250         case GL_RG16F:
251         case GL_RG8:
252                 format = GL_RG;
253                 break;
254         case GL_R32F:
255         case GL_R16F:
256         case GL_R8:
257                 format = GL_RED;
258                 break;
259         default:
260                 // TODO: Add more here as needed.
261                 assert(false);
262         }
263
264         // Same with type; GLES is stricter than desktop OpenGL here.
265         GLenum type;
266         switch (internal_format) {
267         case GL_RGBA32F_ARB:
268         case GL_RGBA16F_ARB:
269         case GL_RGB32F:
270         case GL_RGB16F:
271         case GL_RG32F:
272         case GL_RG16F:
273         case GL_R32F:
274         case GL_R16F:
275                 type = GL_FLOAT;
276                 break;
277         case GL_SRGB8_ALPHA8:
278         case GL_SRGB8:
279         case GL_RGBA8:
280         case GL_RGB8:
281         case GL_RG8:
282         case GL_R8:
283                 type = GL_UNSIGNED_BYTE;
284                 break;
285         case GL_RGB565:
286                 type = GL_UNSIGNED_SHORT_5_6_5;
287                 break;
288         default:
289                 // TODO: Add more here as needed.
290                 assert(false);
291         }
292
293
294         GLuint texture_num;
295         glGenTextures(1, &texture_num);
296         check_error();
297         glBindTexture(GL_TEXTURE_2D, texture_num);
298         check_error();
299         glTexImage2D(GL_TEXTURE_2D, 0, internal_format, width, height, 0, format, type, NULL);
300         check_error();
301         glBindTexture(GL_TEXTURE_2D, 0);
302         check_error();
303
304         Texture2D texture_format;
305         texture_format.internal_format = internal_format;
306         texture_format.width = width;
307         texture_format.height = height;
308         assert(texture_formats.count(texture_num) == 0);
309         texture_formats.insert(make_pair(texture_num, texture_format));
310
311         pthread_mutex_unlock(&lock);
312         return texture_num;
313 }
314
315 void ResourcePool::release_2d_texture(GLuint texture_num)
316 {
317         pthread_mutex_lock(&lock);
318         texture_freelist.push_front(texture_num);
319         assert(texture_formats.count(texture_num) != 0);
320         texture_freelist_bytes += estimate_texture_size(texture_formats[texture_num]);
321
322         while (texture_freelist_bytes > texture_freelist_max_bytes) {
323                 GLuint free_texture_num = texture_freelist.back();
324                 texture_freelist.pop_back();
325                 assert(texture_formats.count(free_texture_num) != 0);
326                 texture_freelist_bytes -= estimate_texture_size(texture_formats[free_texture_num]);
327                 texture_formats.erase(free_texture_num);
328                 glDeleteTextures(1, &free_texture_num);
329                 check_error();
330
331                 // Unlink any lingering FBO related to this texture. We might
332                 // not be in the right context, so don't delete it right away;
333                 // the cleanup in release_fbo() (which calls cleanup_unlinked_fbos())
334                 // will take care of actually doing that later.
335                 for (map<pair<void *, GLuint>, FBO>::iterator format_it = fbo_formats.begin();
336                      format_it != fbo_formats.end();
337                      ++format_it) {
338                         for (unsigned i = 0; i < num_fbo_attachments; ++i) {
339                                 if (format_it->second.texture_num[i] == free_texture_num) {
340                                         format_it->second.texture_num[i] = GL_INVALID_INDEX;
341                                 }
342                         }
343                 }
344         }
345         pthread_mutex_unlock(&lock);
346 }
347
348 GLuint ResourcePool::create_fbo(GLuint texture0_num, GLuint texture1_num, GLuint texture2_num, GLuint texture3_num)
349 {
350         void *context = get_gl_context_identifier();
351
352         // Make sure we are filled from the bottom.
353         assert(texture0_num != 0);
354         if (texture1_num == 0) {
355                 assert(texture2_num == 0);
356         }
357         if (texture2_num == 0) {
358                 assert(texture3_num == 0);
359         }
360
361         pthread_mutex_lock(&lock);
362         if (fbo_freelist.count(context) != 0) {
363                 // See if there's an FBO on the freelist we can use.
364                 list<FBOFormatIterator>::iterator end = fbo_freelist[context].end();
365                 for (list<FBOFormatIterator>::iterator freelist_it = fbo_freelist[context].begin();
366                      freelist_it != end; ++freelist_it) {
367                         FBOFormatIterator fbo_it = *freelist_it;
368                         if (fbo_it->second.texture_num[0] == texture0_num &&
369                             fbo_it->second.texture_num[1] == texture1_num &&
370                             fbo_it->second.texture_num[2] == texture2_num &&
371                             fbo_it->second.texture_num[3] == texture3_num) {
372                                 fbo_freelist[context].erase(freelist_it);
373                                 pthread_mutex_unlock(&lock);
374                                 return fbo_it->second.fbo_num;
375                         }
376                 }
377         }
378
379         // Create a new one.
380         FBO fbo_format;
381         fbo_format.texture_num[0] = texture0_num;
382         fbo_format.texture_num[1] = texture1_num;
383         fbo_format.texture_num[2] = texture2_num;
384         fbo_format.texture_num[3] = texture3_num;
385
386         glGenFramebuffers(1, &fbo_format.fbo_num);
387         check_error();
388         glBindFramebuffer(GL_FRAMEBUFFER, fbo_format.fbo_num);
389         check_error();
390
391         GLenum bufs[num_fbo_attachments];
392         unsigned num_active_attachments = 0;
393         for (unsigned i = 0; i < num_fbo_attachments; ++i, ++num_active_attachments) {
394                 if (fbo_format.texture_num[i] == 0) {
395                         break;
396                 }
397                 glFramebufferTexture2D(
398                         GL_FRAMEBUFFER,
399                         GL_COLOR_ATTACHMENT0 + i,
400                         GL_TEXTURE_2D,
401                         fbo_format.texture_num[i],
402                         0);
403                 check_error();
404                 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
405         }
406
407         glDrawBuffers(num_active_attachments, bufs);
408         check_error();
409
410         GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
411         assert(status == GL_FRAMEBUFFER_COMPLETE);
412         glBindFramebuffer(GL_FRAMEBUFFER, 0);
413         check_error();
414
415         pair<void *, GLuint> key(context, fbo_format.fbo_num);
416         assert(fbo_formats.count(key) == 0);
417         fbo_formats.insert(make_pair(key, fbo_format));
418
419         pthread_mutex_unlock(&lock);
420         return fbo_format.fbo_num;
421 }
422
423 void ResourcePool::release_fbo(GLuint fbo_num)
424 {
425         void *context = get_gl_context_identifier();
426
427         pthread_mutex_lock(&lock);
428         FBOFormatIterator fbo_it = fbo_formats.find(make_pair(context, fbo_num));
429         assert(fbo_it != fbo_formats.end());
430         fbo_freelist[context].push_front(fbo_it);
431
432         // Now that we're in this context, free up any FBOs that are connected
433         // to deleted textures (in release_2d_texture).
434         cleanup_unlinked_fbos(context);
435
436         shrink_fbo_freelist(context, fbo_freelist_max_length);
437         pthread_mutex_unlock(&lock);
438 }
439
440 void ResourcePool::clean_context()
441 {
442         void *context = get_gl_context_identifier();
443
444         // Currently, we only need to worry about FBOs, as they are the only
445         // non-shareable resource we hold.
446         shrink_fbo_freelist(context, 0);
447         fbo_freelist.erase(context);
448 }
449
450 void ResourcePool::cleanup_unlinked_fbos(void *context)
451 {
452         list<FBOFormatIterator>::iterator end = fbo_freelist[context].end();
453         for (list<FBOFormatIterator>::iterator freelist_it = fbo_freelist[context].begin(); freelist_it != end; ) {
454                 FBOFormatIterator fbo_it = *freelist_it;
455
456                 bool all_unlinked = true;
457                 for (unsigned i = 0; i < num_fbo_attachments; ++i) {
458                         if (fbo_it->second.texture_num[i] != 0 &&
459                             fbo_it->second.texture_num[i] != GL_INVALID_INDEX) {
460                                 all_unlinked = false;
461                                 break;
462                         }
463                 }
464                 if (all_unlinked) {
465                         glDeleteFramebuffers(1, &fbo_it->second.fbo_num);
466                         check_error();
467                         fbo_formats.erase(fbo_it);
468                         fbo_freelist[context].erase(freelist_it++);
469                 } else {
470                         freelist_it++;
471                 }
472         }
473 }
474
475 void ResourcePool::shrink_fbo_freelist(void *context, size_t max_length)
476 {
477         list<FBOFormatIterator> &freelist = fbo_freelist[context];
478         while (freelist.size() > max_length) {
479                 FBOFormatIterator free_fbo_it = freelist.back();
480                 glDeleteFramebuffers(1, &free_fbo_it->second.fbo_num);
481                 check_error();
482                 fbo_formats.erase(free_fbo_it);
483                 freelist.pop_back();
484         }
485 }
486
487 size_t ResourcePool::estimate_texture_size(const Texture2D &texture_format)
488 {
489         size_t bytes_per_pixel;
490
491         switch (texture_format.internal_format) {
492         case GL_RGBA32F_ARB:
493                 bytes_per_pixel = 16;
494                 break;
495         case GL_RGBA16F_ARB:
496                 bytes_per_pixel = 8;
497                 break;
498         case GL_RGB32F_ARB:
499                 bytes_per_pixel = 12;
500                 break;
501         case GL_RGB16F_ARB:
502                 bytes_per_pixel = 6;
503                 break;
504         case GL_RGBA8:
505         case GL_SRGB8_ALPHA8:
506                 bytes_per_pixel = 4;
507                 break;
508         case GL_RGB8:
509         case GL_SRGB8:
510                 bytes_per_pixel = 3;
511                 break;
512         case GL_RG32F:
513                 bytes_per_pixel = 8;
514                 break;
515         case GL_RG16F:
516                 bytes_per_pixel = 4;
517                 break;
518         case GL_R32F:
519                 bytes_per_pixel = 4;
520                 break;
521         case GL_R16F:
522                 bytes_per_pixel = 2;
523                 break;
524         case GL_RG8:
525                 bytes_per_pixel = 2;
526                 break;
527         case GL_R8:
528                 bytes_per_pixel = 1;
529                 break;
530         case GL_RGB565:
531                 bytes_per_pixel = 2;
532                 break;
533         default:
534                 // TODO: Add more here as needed.
535                 assert(false);
536         }
537
538         return texture_format.width * texture_format.height * bytes_per_pixel;
539 }
540
541 }  // namespace movit