]> git.sesse.net Git - mlt/blob - src/modules/opengl/filter_glsl_manager.cpp
Add back automatic cleanup of OpenGL fences.
[mlt] / src / modules / opengl / filter_glsl_manager.cpp
1 /*
2  * filter_glsl_manager.cpp
3  * Copyright (C) 2011-2012 Christophe Thommeret <hftom@free.fr>
4  * Copyright (C) 2013 Dan Dennedy <dan@dennedy.org>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19  */
20
21 #include <stdlib.h>
22 #include <string>
23 #include "filter_glsl_manager.h"
24 #include <movit/init.h>
25 #include <movit/util.h>
26 #include <movit/effect_chain.h>
27 #include "mlt_movit_input.h"
28 #include "mlt_flip_effect.h"
29 #include <mlt++/MltEvent.h>
30 #include <mlt++/MltProducer.h>
31
32 extern "C" {
33 #include <framework/mlt_factory.h>
34 }
35
36 #if defined(__DARWIN__)
37 #include <OpenGL/OpenGL.h>
38 #elif defined(WIN32)
39 #include <wingdi.h>
40 #else
41 #include <GL/glx.h>
42 #endif
43
44 void deleteManager(GlslManager *p)
45 {
46         delete p;
47 }
48
49 GlslManager::GlslManager()
50         : Mlt::Filter( mlt_filter_new() )
51         , pbo(0)
52         , initEvent(0)
53         , closeEvent(0)
54         , prev_sync(NULL)
55 {
56         mlt_filter filter = get_filter();
57         if ( filter ) {
58                 // Set the mlt_filter child in case we choose to override virtual functions.
59                 filter->child = this;
60                 mlt_properties_set_data(mlt_global_properties(), "glslManager", this, 0,
61                         (mlt_destructor) deleteManager, NULL);
62
63                 mlt_events_register( get_properties(), "init glsl", NULL );
64                 mlt_events_register( get_properties(), "close glsl", NULL );
65                 initEvent = listen("init glsl", this, (mlt_listener) GlslManager::onInit);
66                 closeEvent = listen("close glsl", this, (mlt_listener) GlslManager::onClose);
67         }
68 }
69
70 GlslManager::~GlslManager()
71 {
72         mlt_log_debug(get_service(), "%s\n", __FUNCTION__);
73         cleanupContext();
74 // XXX If there is still a frame holding a reference to a texture after this
75 // destructor is called, then it will crash in release_texture().
76 //      while (texture_list.peek_back())
77 //              delete (glsl_texture) texture_list.pop_back();
78         delete initEvent;
79         delete closeEvent;
80         if (prev_sync != NULL) {
81                 glDeleteSync( prev_sync );
82         }
83         while (syncs_to_delete.count() > 0) {
84                 GLsync sync = (GLsync) syncs_to_delete.pop_front();
85                 glDeleteSync( sync );
86         }
87 }
88
89 GlslManager* GlslManager::get_instance()
90 {
91         return (GlslManager*) mlt_properties_get_data(mlt_global_properties(), "glslManager", 0);
92 }
93
94 glsl_fbo GlslManager::get_fbo(int width, int height)
95 {
96 #if defined(__DARWIN__)
97         CGLContextObj context = CGLGetCurrentContext();
98 #elif defined(WIN32)
99         HGLRC context = wglGetCurrentContext();
100 #else
101         GLXContext context = glXGetCurrentContext();
102 #endif
103
104         lock();
105         for (int i = 0; i < fbo_list.count(); ++i) {
106                 glsl_fbo fbo = (glsl_fbo) fbo_list.peek(i);
107                 if (!fbo->used && (fbo->width == width) && (fbo->height == height) && (fbo->context == context)) {
108                         fbo->used = 1;
109                         unlock();
110                         return fbo;
111                 }
112         }
113         unlock();
114
115         GLuint fb = 0;
116         glGenFramebuffers(1, &fb);
117         if (!fb)
118                 return NULL;
119
120         glsl_fbo fbo = new glsl_fbo_s;
121         if (!fbo) {
122                 glDeleteFramebuffers(1, &fb);
123                 return NULL;
124         }
125         fbo->fbo = fb;
126         fbo->width = width;
127         fbo->height = height;
128         fbo->used = 1;
129         fbo->context = context;
130         lock();
131         fbo_list.push_back(fbo);
132         unlock();
133         return fbo;
134 }
135
136 void GlslManager::release_fbo(glsl_fbo fbo)
137 {
138         fbo->used = 0;
139 }
140
141 glsl_texture GlslManager::get_texture(int width, int height, GLint internal_format)
142 {
143         lock();
144         for (int i = 0; i < texture_list.count(); ++i) {
145                 glsl_texture tex = (glsl_texture) texture_list.peek(i);
146                 if (!tex->used && (tex->width == width) && (tex->height == height) && (tex->internal_format == internal_format)) {
147                         glBindTexture(GL_TEXTURE_2D, tex->texture);
148                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
149                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
150                         glBindTexture( GL_TEXTURE_2D, 0);
151                         tex->used = 1;
152                         unlock();
153                         return tex;
154                 }
155         }
156
157         // Recycle a glsl_texture with deleted glTexture.
158         glsl_texture gtex = 0;
159         for (int i = 0; i < texture_list.count(); ++i) {
160                 glsl_texture tex = (glsl_texture) texture_list.peek(i);
161                 if (!tex->used && !tex->width && !tex->height) {
162                         gtex = tex;
163                         break;
164                 }
165         }
166         unlock();
167
168         GLuint tex = 0;
169         glGenTextures(1, &tex);
170         if (!tex) {
171                 glDeleteTextures(1, &tex);
172                 return NULL;
173         }
174
175         if (!gtex) {
176                 gtex = new glsl_texture_s;
177                 if (!gtex)
178                         return NULL;
179         }
180
181         glBindTexture( GL_TEXTURE_2D, tex );
182         glTexImage2D( GL_TEXTURE_2D, 0, internal_format, width, height, 0, internal_format, GL_UNSIGNED_BYTE, NULL );
183     glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
184     glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
185     glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
186     glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
187     glBindTexture( GL_TEXTURE_2D, 0 );
188
189         gtex->texture = tex;
190         gtex->width = width;
191         gtex->height = height;
192         gtex->internal_format = internal_format;
193         gtex->used = 1;
194         lock();
195         texture_list.push_back(gtex);
196         unlock();
197         return gtex;
198 }
199
200 void GlslManager::release_texture(glsl_texture texture)
201 {
202         texture->used = 0;
203 }
204
205 void GlslManager::delete_sync(GLsync sync)
206 {
207         // We do not know which thread we are called from, and we can only
208         // delete this if we are in one with a valid OpenGL context.
209         // Thus, store it for later deletion in render_frame_texture().
210         GlslManager* g = GlslManager::get_instance();
211         g->lock();
212         g->syncs_to_delete.push_back(sync);
213         g->unlock();
214 }
215
216 glsl_pbo GlslManager::get_pbo(int size)
217 {
218         lock();
219         if (!pbo) {
220                 GLuint pb = 0;
221                 glGenBuffers(1, &pb);
222                 if (!pb) {
223                         unlock();
224                         return NULL;
225                 }
226
227                 pbo = new glsl_pbo_s;
228                 if (!pbo) {
229                         glDeleteBuffers(1, &pb);
230                         unlock();
231                         return NULL;
232                 }
233                 pbo->pbo = pb;
234                 pbo->size = 0;
235         }
236         if (size > pbo->size) {
237                 glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, pbo->pbo);
238                 glBufferData(GL_PIXEL_UNPACK_BUFFER_ARB, size, NULL, GL_STREAM_DRAW);
239                 glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
240                 pbo->size = size;
241         }
242         unlock();
243         return pbo;
244 }
245
246 void GlslManager::cleanupContext()
247 {
248         lock();
249         while (fbo_list.peek_back()) {
250                 glsl_fbo fbo = (glsl_fbo) fbo_list.pop_back();
251                 glDeleteFramebuffers(1, &fbo->fbo);
252                 delete fbo;
253         }
254         for (int i = 0; i < texture_list.count(); ++i) {
255                 glsl_texture texture = (glsl_texture) texture_list.peek(i);
256                 glDeleteTextures(1, &texture->texture);
257                 texture->used = 0;
258                 texture->width = 0;
259                 texture->height = 0;
260         }
261         if (pbo) {
262                 glDeleteBuffers(1, &pbo->pbo);
263                 delete pbo;
264                 pbo = 0;
265         }
266         unlock();
267 }
268
269 void GlslManager::onInit( mlt_properties owner, GlslManager* filter )
270 {
271         mlt_log_debug( filter->get_service(), "%s\n", __FUNCTION__ );
272 #ifdef WIN32
273         std::string path = std::string(mlt_environment("MLT_APPDIR")).append("\\share\\movit");
274 #elif defined(__DARWIN__) && defined(RELOCATABLE)
275         std::string path = std::string(mlt_environment("MLT_APPDIR")).append("/share/movit");
276 #else
277         std::string path = std::string(getenv("MLT_MOVIT_PATH") ? getenv("MLT_MOVIT_PATH") : SHADERDIR);
278 #endif
279         ::init_movit( path, mlt_log_get_level() == MLT_LOG_DEBUG? MOVIT_DEBUG_ON : MOVIT_DEBUG_OFF );
280         filter->set( "glsl_supported", movit_initialized );
281 }
282
283 void GlslManager::onClose( mlt_properties owner, GlslManager *filter )
284 {
285         filter->cleanupContext();
286 }
287
288 void GlslManager::onServiceChanged( mlt_properties owner, mlt_service aservice )
289 {
290         Mlt::Service service( aservice );
291         service.lock();
292         service.set( "movit chain", NULL, 0 );
293         service.set( "movit input", NULL, 0 );
294         // Destroy the effect list.
295         GlslManager::get_instance()->set( service.get( "_unique_id" ), NULL, 0 );
296         service.unlock();
297 }
298
299 void GlslManager::onPropertyChanged( mlt_properties owner, mlt_service service, const char* property )
300 {
301         if ( property && std::string( property ) == "disable" )
302                 onServiceChanged( owner, service );
303 }
304
305 extern "C" {
306
307 mlt_filter filter_glsl_manager_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
308 {
309         GlslManager* g = GlslManager::get_instance();
310         if (g)
311                 g->inc_ref();
312         else
313                 g = new GlslManager();
314         return g->get_filter();
315 }
316
317 } // extern "C"
318
319 Mlt::Properties GlslManager::effect_list( Mlt::Service& service )
320 {
321         char *unique_id =  service.get( "_unique_id" );
322         mlt_properties properties = (mlt_properties) get_data( unique_id );
323         if ( !properties ) {
324                 properties = mlt_properties_new();
325                 set( unique_id, properties, 0, (mlt_destructor) mlt_properties_close );
326         }
327         Mlt::Properties p( properties );
328         return p;
329 }
330
331 static void deleteChain( EffectChain* chain )
332 {
333         delete chain;
334 }
335
336 bool GlslManager::init_chain( mlt_service aservice )
337 {
338         bool error = true;
339         Mlt::Service service( aservice );
340         EffectChain* chain = (EffectChain*) service.get_data( "movit chain" );
341         if ( !chain ) {
342                 mlt_profile profile = mlt_service_profile( aservice );
343                 Input* input = new MltInput( profile->width, profile->height );
344                 chain = new EffectChain( profile->display_aspect_num, profile->display_aspect_den );
345                 chain->add_input( input );
346                 service.set( "movit chain", chain, 0, (mlt_destructor) deleteChain );
347                 service.set( "movit input", input, 0 );
348                 service.set( "_movit finalized", 0 );
349                 service.listen( "service-changed", aservice, (mlt_listener) GlslManager::onServiceChanged );
350                 service.listen( "property-changed", aservice, (mlt_listener) GlslManager::onPropertyChanged );
351                 error = false;
352         }
353         return error;
354 }
355
356 EffectChain* GlslManager::get_chain( mlt_service service )
357 {
358         return (EffectChain*) mlt_properties_get_data( MLT_SERVICE_PROPERTIES(service), "movit chain", NULL );
359 }
360
361 MltInput *GlslManager::get_input( mlt_service service )
362 {
363         return (MltInput*) mlt_properties_get_data( MLT_SERVICE_PROPERTIES(service), "movit input", NULL );
364 }
365
366 void GlslManager::reset_finalized( mlt_service service )
367 {
368         mlt_properties_set_int( MLT_SERVICE_PROPERTIES(service), "_movit finalized", 0 );
369 }
370
371 Effect* GlslManager::get_effect( mlt_service service, mlt_frame frame )
372 {
373         Mlt::Producer producer( mlt_producer_cut_parent( mlt_frame_get_original_producer( frame ) ) );
374         char *unique_id = mlt_properties_get( MLT_SERVICE_PROPERTIES(service), "_unique_id" );
375         return (Effect*) GlslManager::get_instance()->effect_list( producer ).get_data( unique_id );
376 }
377
378 Effect* GlslManager::add_effect( mlt_service service, mlt_frame frame, Effect* effect )
379 {
380         Mlt::Producer producer( mlt_producer_cut_parent( mlt_frame_get_original_producer( frame ) ) );
381         EffectChain* chain = (EffectChain*) producer.get_data( "movit chain" );
382         chain->add_effect( effect );
383         char *unique_id = mlt_properties_get( MLT_SERVICE_PROPERTIES(service), "_unique_id" );
384         GlslManager::get_instance()->effect_list( producer ).set( unique_id, effect, 0 );
385         return effect;
386 }
387
388 Effect* GlslManager::add_effect( mlt_service service, mlt_frame frame, Effect* effect, Effect* input_b )
389 {
390         Mlt::Producer producer( mlt_producer_cut_parent( mlt_frame_get_original_producer( frame ) ) );
391         EffectChain* chain = (EffectChain*) producer.get_data( "movit chain" );
392         chain->add_effect( effect, chain->last_added_effect(),
393                 input_b? input_b : chain->last_added_effect() );
394         char *unique_id = mlt_properties_get( MLT_SERVICE_PROPERTIES(service), "_unique_id" );
395         GlslManager::get_instance()->effect_list( producer ).set( unique_id, effect, 0 );
396         return effect;
397 }
398
399 void GlslManager::render_fbo( mlt_service service, void* chain, GLuint fbo, int width, int height )
400 {
401         EffectChain* effect_chain = (EffectChain*) chain;
402         mlt_properties properties = MLT_SERVICE_PROPERTIES( service );
403         if ( !mlt_properties_get_int( properties, "_movit finalized" ) ) {
404                 mlt_properties_set_int( properties, "_movit finalized", 1 );
405                 effect_chain->add_effect( new Mlt::VerticalFlip() );
406                 effect_chain->finalize();
407         }
408         effect_chain->render_to_fbo( fbo, width, height );
409 }
410
411 int GlslManager::render_frame_texture(mlt_service service, mlt_frame frame, int width, int height, uint8_t **image)
412 {
413         EffectChain* chain = get_chain( service );
414         if (!chain) return 1;
415         glsl_fbo fbo = get_fbo( width, height );
416         if (!fbo) return 1;
417         glsl_texture texture = get_texture( width, height, GL_RGBA );
418         if (!texture) {
419                 release_fbo( fbo );
420                 return 1;
421         }
422
423         glBindFramebuffer( GL_FRAMEBUFFER, fbo->fbo );
424         check_error();
425         glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture->texture, 0 );
426         check_error();
427         glBindFramebuffer( GL_FRAMEBUFFER, 0 );
428         check_error();
429
430         lock();
431         while (syncs_to_delete.count() > 0) {
432                 GLsync sync = (GLsync) syncs_to_delete.pop_front();
433                 glDeleteSync( sync );
434         }
435         unlock();
436
437         // Make sure we never have more than one frame pending at any time.
438         // This ensures we do not swamp the GPU with so much work
439         // that we cannot actually display the frames we generate.
440         if (prev_sync != NULL) {
441                 glFlush();
442                 glClientWaitSync( prev_sync, 0, GL_TIMEOUT_IGNORED );
443                 glDeleteSync( prev_sync );
444         }
445         render_fbo( service, chain, fbo->fbo, width, height );
446         prev_sync = glFenceSync( GL_SYNC_GPU_COMMANDS_COMPLETE, 0 );
447         GLsync sync = glFenceSync( GL_SYNC_GPU_COMMANDS_COMPLETE, 0 );
448
449         check_error();
450         glBindFramebuffer( GL_FRAMEBUFFER, 0 );
451         check_error();
452         release_fbo( fbo );
453
454         *image = (uint8_t*) &texture->texture;
455         mlt_frame_set_image( frame, *image, 0, NULL );
456         mlt_properties_set_data( MLT_FRAME_PROPERTIES(frame), "movit.convert.texture", texture, 0,
457                 (mlt_destructor) GlslManager::release_texture, NULL );
458         mlt_properties_set_data( MLT_FRAME_PROPERTIES(frame), "movit.convert.fence", sync, 0,
459                 (mlt_destructor) GlslManager::delete_sync, NULL );
460
461         return 0;
462 }
463
464 int GlslManager::render_frame_rgba(mlt_service service, mlt_frame frame, int width, int height, uint8_t **image)
465 {
466         EffectChain* chain = get_chain( service );
467         if (!chain) return 1;
468         glsl_fbo fbo = get_fbo( width, height );
469         if (!fbo) return 1;
470         glsl_texture texture = get_texture( width, height, GL_RGBA );
471         if (!texture) {
472                 release_fbo( fbo );
473                 return 1;
474         }
475
476         // Use a PBO to hold the data we read back with glReadPixels().
477         // (Intel/DRI goes into a slow path if we don't read to PBO.)
478         int img_size = width * height * 4;
479         glsl_pbo pbo = get_pbo( img_size );
480         if (!pbo) {
481                 release_fbo( fbo );
482                 release_texture(texture);
483                 return 1;
484         }
485
486         // Set the FBO
487         check_error();
488         glBindFramebuffer( GL_FRAMEBUFFER, fbo->fbo );
489         check_error();
490         glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture->texture, 0 );
491         check_error();
492         glBindFramebuffer( GL_FRAMEBUFFER, 0 );
493         check_error();
494
495         render_fbo( service, chain, fbo->fbo, width, height );
496
497         // Read FBO into PBO
498         glBindFramebuffer( GL_FRAMEBUFFER, fbo->fbo );
499         check_error();
500         glBindBuffer( GL_PIXEL_PACK_BUFFER_ARB, pbo->pbo );
501         check_error();
502         glBufferData( GL_PIXEL_PACK_BUFFER_ARB, img_size, NULL, GL_STREAM_READ );
503         check_error();
504         glReadPixels( 0, 0, width, height, GL_BGRA, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0) );
505         check_error();
506
507         // Copy from PBO
508         uint8_t* buf = (uint8_t*) glMapBuffer( GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY );
509         check_error();
510         *image = (uint8_t*) mlt_pool_alloc( img_size );
511         mlt_frame_set_image( frame, *image, img_size, mlt_pool_release );
512         memcpy( *image, buf, img_size );
513
514         // Convert BGRA to RGBA
515         register uint8_t *p = *image;
516         register int n = width * height + 1;
517         while ( --n ) {
518                 uint8_t b = p[0];
519                 *p = p[2]; p += 2;
520                 *p = b; p += 2;
521         }
522
523         // Release PBO and FBO
524         glUnmapBuffer( GL_PIXEL_PACK_BUFFER_ARB );
525         check_error();
526         glBindBuffer( GL_PIXEL_PACK_BUFFER_ARB, 0 );
527         check_error();
528         glBindFramebuffer( GL_FRAMEBUFFER, 0 );
529         check_error();
530         glBindTexture( GL_TEXTURE_2D, 0 );
531         check_error();
532         mlt_properties_set_data( MLT_FRAME_PROPERTIES(frame), "movit.convert.texture", texture, 0,
533                 (mlt_destructor) GlslManager::release_texture, NULL);
534         release_fbo( fbo );
535
536         return 0;
537 }
538
539 void GlslManager::lock_service( mlt_frame frame )
540 {
541         Mlt::Producer producer( mlt_producer_cut_parent( mlt_frame_get_original_producer( frame ) ) );
542         producer.lock();
543 }
544
545 void GlslManager::unlock_service( mlt_frame frame )
546 {
547         Mlt::Producer producer( mlt_producer_cut_parent( mlt_frame_get_original_producer( frame ) ) );
548         producer.unlock();
549 }