]> git.sesse.net Git - mlt/blob - src/modules/opengl/filter_glsl_manager.cpp
9b01337301f5636717dc18637278c3a56caf6f45
[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 <movit/resource_pool.h>
28 #include "mlt_movit_input.h"
29 #include "mlt_flip_effect.h"
30 #include <mlt++/MltEvent.h>
31 #include <mlt++/MltProducer.h>
32
33 extern "C" {
34 #include <framework/mlt_factory.h>
35 }
36
37 #if defined(__DARWIN__)
38 #include <OpenGL/OpenGL.h>
39 #elif defined(WIN32)
40 #include <wingdi.h>
41 #else
42 #include <GL/glx.h>
43 #endif
44
45 void dec_ref_and_delete(GlslManager *p)
46 {
47         if (p->dec_ref() == 0) {
48                 delete p;
49         }
50 }
51
52 GlslManager::GlslManager()
53         : Mlt::Filter( mlt_filter_new() )
54         , resource_pool(new ResourcePool())
55         , pbo(0)
56         , initEvent(0)
57         , closeEvent(0)
58         , prev_sync(NULL)
59 {
60         mlt_filter filter = get_filter();
61         if ( filter ) {
62                 // Set the mlt_filter child in case we choose to override virtual functions.
63                 filter->child = this;
64                 add_ref(mlt_global_properties());
65
66                 mlt_events_register( get_properties(), "init glsl", NULL );
67                 mlt_events_register( get_properties(), "close glsl", NULL );
68                 initEvent = listen("init glsl", this, (mlt_listener) GlslManager::onInit);
69                 closeEvent = listen("close glsl", this, (mlt_listener) GlslManager::onClose);
70         }
71 }
72
73 GlslManager::~GlslManager()
74 {
75         mlt_log_debug(get_service(), "%s\n", __FUNCTION__);
76         cleanupContext();
77 // XXX If there is still a frame holding a reference to a texture after this
78 // destructor is called, then it will crash in release_texture().
79 //      while (texture_list.peek_back())
80 //              delete (glsl_texture) texture_list.pop_back();
81         delete initEvent;
82         delete closeEvent;
83         if (prev_sync != NULL) {
84                 glDeleteSync( prev_sync );
85         }
86         while (syncs_to_delete.count() > 0) {
87                 GLsync sync = (GLsync) syncs_to_delete.pop_front();
88                 glDeleteSync( sync );
89         }
90         delete resource_pool;
91 }
92
93 void GlslManager::add_ref(mlt_properties properties)
94 {
95         inc_ref();
96         mlt_properties_set_data(properties, "glslManager", this, 0,
97             (mlt_destructor) dec_ref_and_delete, NULL);
98 }
99
100 GlslManager* GlslManager::get_instance()
101 {
102         return (GlslManager*) mlt_properties_get_data(mlt_global_properties(), "glslManager", 0);
103 }
104
105 glsl_texture GlslManager::get_texture(int width, int height, GLint internal_format)
106 {
107         lock();
108         for (int i = 0; i < texture_list.count(); ++i) {
109                 glsl_texture tex = (glsl_texture) texture_list.peek(i);
110                 if (!tex->used && (tex->width == width) && (tex->height == height) && (tex->internal_format == internal_format)) {
111                         glBindTexture(GL_TEXTURE_2D, tex->texture);
112                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
113                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
114                         glBindTexture( GL_TEXTURE_2D, 0);
115                         tex->used = 1;
116                         unlock();
117                         return tex;
118                 }
119         }
120
121         // Recycle a glsl_texture with deleted glTexture.
122         glsl_texture gtex = 0;
123         for (int i = 0; i < texture_list.count(); ++i) {
124                 glsl_texture tex = (glsl_texture) texture_list.peek(i);
125                 if (!tex->used && !tex->width && !tex->height) {
126                         gtex = tex;
127                         break;
128                 }
129         }
130         unlock();
131
132         GLuint tex = 0;
133         glGenTextures(1, &tex);
134         if (!tex) {
135                 glDeleteTextures(1, &tex);
136                 return NULL;
137         }
138
139         if (!gtex) {
140                 gtex = new glsl_texture_s;
141                 if (!gtex)
142                         return NULL;
143         }
144
145         glBindTexture( GL_TEXTURE_2D, tex );
146         glTexImage2D( GL_TEXTURE_2D, 0, internal_format, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL );
147     glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
148     glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
149     glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
150     glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
151     glBindTexture( GL_TEXTURE_2D, 0 );
152
153         gtex->texture = tex;
154         gtex->width = width;
155         gtex->height = height;
156         gtex->internal_format = internal_format;
157         gtex->used = 1;
158         lock();
159         texture_list.push_back(gtex);
160         unlock();
161         return gtex;
162 }
163
164 void GlslManager::release_texture(glsl_texture texture)
165 {
166         texture->used = 0;
167 }
168
169 void GlslManager::delete_sync(GLsync sync)
170 {
171         // We do not know which thread we are called from, and we can only
172         // delete this if we are in one with a valid OpenGL context.
173         // Thus, store it for later deletion in render_frame_texture().
174         GlslManager* g = GlslManager::get_instance();
175         g->lock();
176         g->syncs_to_delete.push_back(sync);
177         g->unlock();
178 }
179
180 glsl_pbo GlslManager::get_pbo(int size)
181 {
182         lock();
183         if (!pbo) {
184                 GLuint pb = 0;
185                 glGenBuffers(1, &pb);
186                 if (!pb) {
187                         unlock();
188                         return NULL;
189                 }
190
191                 pbo = new glsl_pbo_s;
192                 if (!pbo) {
193                         glDeleteBuffers(1, &pb);
194                         unlock();
195                         return NULL;
196                 }
197                 pbo->pbo = pb;
198                 pbo->size = 0;
199         }
200         if (size > pbo->size) {
201                 glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, pbo->pbo);
202                 glBufferData(GL_PIXEL_UNPACK_BUFFER_ARB, size, NULL, GL_STREAM_DRAW);
203                 glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
204                 pbo->size = size;
205         }
206         unlock();
207         return pbo;
208 }
209
210 void GlslManager::cleanupContext()
211 {
212         lock();
213         for (int i = 0; i < texture_list.count(); ++i) {
214                 glsl_texture texture = (glsl_texture) texture_list.peek(i);
215                 glDeleteTextures(1, &texture->texture);
216                 texture->used = 0;
217                 texture->width = 0;
218                 texture->height = 0;
219         }
220         if (pbo) {
221                 glDeleteBuffers(1, &pbo->pbo);
222                 delete pbo;
223                 pbo = 0;
224         }
225         unlock();
226 }
227
228 void GlslManager::onInit( mlt_properties owner, GlslManager* filter )
229 {
230         mlt_log_debug( filter->get_service(), "%s\n", __FUNCTION__ );
231 #ifdef WIN32
232         std::string path = std::string(mlt_environment("MLT_APPDIR")).append("\\share\\movit");
233 #elif defined(__DARWIN__) && defined(RELOCATABLE)
234         std::string path = std::string(mlt_environment("MLT_APPDIR")).append("/share/movit");
235 #else
236         std::string path = std::string(getenv("MLT_MOVIT_PATH") ? getenv("MLT_MOVIT_PATH") : SHADERDIR);
237 #endif
238         ::init_movit( path, mlt_log_get_level() == MLT_LOG_DEBUG? MOVIT_DEBUG_ON : MOVIT_DEBUG_OFF );
239         filter->set( "glsl_supported", movit_initialized );
240 }
241
242 void GlslManager::onClose( mlt_properties owner, GlslManager *filter )
243 {
244         filter->cleanupContext();
245 }
246
247 void GlslManager::onServiceChanged( mlt_properties owner, mlt_service aservice )
248 {
249         Mlt::Service service( aservice );
250         service.lock();
251         service.set( "movit chain", NULL, 0 );
252         service.unlock();
253 }
254
255 void GlslManager::onPropertyChanged( mlt_properties owner, mlt_service service, const char* property )
256 {
257         if ( property && std::string( property ) == "disable" )
258                 onServiceChanged( owner, service );
259 }
260
261 extern "C" {
262
263 mlt_filter filter_glsl_manager_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
264 {
265         GlslManager* g = GlslManager::get_instance();
266         if (g)
267                 g->inc_ref();
268         else
269                 g = new GlslManager();
270         return g->get_filter();
271 }
272
273 } // extern "C"
274
275 static void deleteChain( GlslChain* chain )
276 {
277         // The Input* is owned by the EffectChain, but the MltInput* is not.
278         // Thus, we have to delete it here.
279         for (std::map<mlt_producer, MltInput*>::iterator input_it = chain->inputs.begin();
280              input_it != chain->inputs.end();
281              ++input_it) {
282                 delete input_it->second;
283         }
284         delete chain->effect_chain;
285         delete chain;
286 }
287         
288 void* GlslManager::get_frame_specific_data( mlt_service service, mlt_frame frame, const char *key, int *length )
289 {
290         const char *unique_id = mlt_properties_get( MLT_SERVICE_PROPERTIES(service), "_unique_id" );
291         char buf[256];
292         snprintf( buf, sizeof(buf), "%s_%s", key, unique_id );
293         return mlt_properties_get_data( MLT_FRAME_PROPERTIES(frame), buf, length );
294 }
295
296 int GlslManager::set_frame_specific_data( mlt_service service, mlt_frame frame, const char *key, void *value, int length, mlt_destructor destroy, mlt_serialiser serialise )
297 {
298         const char *unique_id = mlt_properties_get( MLT_SERVICE_PROPERTIES(service), "_unique_id" );
299         char buf[256];
300         snprintf( buf, sizeof(buf), "%s_%s", key, unique_id );
301         return mlt_properties_set_data( MLT_FRAME_PROPERTIES(frame), buf, value, length, destroy, serialise );
302 }
303
304 void GlslManager::set_chain( mlt_service service, GlslChain* chain )
305 {
306         mlt_properties_set_data( MLT_SERVICE_PROPERTIES(service), "_movit chain", chain, 0, (mlt_destructor) deleteChain, NULL );
307 }
308
309 GlslChain* GlslManager::get_chain( mlt_service service )
310 {
311         return (GlslChain*) mlt_properties_get_data( MLT_SERVICE_PROPERTIES(service), "_movit chain", NULL );
312 }
313         
314 Effect* GlslManager::get_effect( mlt_service service, mlt_frame frame )
315 {
316         return (Effect*) get_frame_specific_data( service, frame, "_movit effect", NULL );
317 }
318
319 Effect* GlslManager::set_effect( mlt_service service, mlt_frame frame, Effect* effect )
320 {
321         set_frame_specific_data( service, frame, "_movit effect", effect, 0, NULL, NULL );
322         return effect;
323 }
324
325 MltInput* GlslManager::get_input( mlt_producer producer, mlt_frame frame )
326 {
327         return (MltInput*) get_frame_specific_data( MLT_PRODUCER_SERVICE(producer), frame, "_movit input", NULL );
328 }
329
330 MltInput* GlslManager::set_input( mlt_producer producer, mlt_frame frame, MltInput* input )
331 {
332         set_frame_specific_data( MLT_PRODUCER_SERVICE(producer), frame, "_movit input", input, 0, NULL, NULL );
333         return input;
334 }
335
336 uint8_t* GlslManager::get_input_pixel_pointer( mlt_producer producer, mlt_frame frame )
337 {
338         return (uint8_t*) get_frame_specific_data( MLT_PRODUCER_SERVICE(producer), frame, "_movit input pp", NULL );
339 }
340
341 uint8_t* GlslManager::set_input_pixel_pointer( mlt_producer producer, mlt_frame frame, uint8_t* image )
342 {
343         set_frame_specific_data( MLT_PRODUCER_SERVICE(producer), frame, "_movit input pp", image, 0, NULL, NULL );
344         return image;
345 }
346
347 mlt_service GlslManager::get_effect_input( mlt_service service, mlt_frame frame )
348 {
349         return (mlt_service) get_frame_specific_data( service, frame, "_movit effect input", NULL );
350 }
351
352 void GlslManager::set_effect_input( mlt_service service, mlt_frame frame, mlt_service input_service )
353 {
354         set_frame_specific_data( service, frame, "_movit effect input", input_service, 0, NULL, NULL );
355 }
356
357 void GlslManager::get_effect_secondary_input( mlt_service service, mlt_frame frame, mlt_service *input_service, mlt_frame *input_frame)
358 {
359         *input_service = (mlt_service) get_frame_specific_data( service, frame, "_movit effect secondary input", NULL );
360         *input_frame = (mlt_frame) get_frame_specific_data( service, frame, "_movit effect secondary input frame", NULL );
361 }
362
363 void GlslManager::set_effect_secondary_input( mlt_service service, mlt_frame frame, mlt_service input_service, mlt_frame input_frame )
364 {
365         set_frame_specific_data( service, frame, "_movit effect secondary input", input_service, 0, NULL, NULL );
366         set_frame_specific_data( service, frame, "_movit effect secondary input frame", input_frame, 0, NULL, NULL );
367 }
368
369 int GlslManager::render_frame_texture(EffectChain *chain, mlt_frame frame, int width, int height, uint8_t **image)
370 {
371         glsl_texture texture = get_texture( width, height, GL_RGBA8 );
372         if (!texture) {
373                 return 1;
374         }
375
376         GLuint fbo;
377         glGenFramebuffers( 1, &fbo );
378         check_error();
379         glBindFramebuffer( GL_FRAMEBUFFER, fbo );
380         check_error();
381         glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture->texture, 0 );
382         check_error();
383         glBindFramebuffer( GL_FRAMEBUFFER, 0 );
384         check_error();
385
386         lock();
387         while (syncs_to_delete.count() > 0) {
388                 GLsync sync = (GLsync) syncs_to_delete.pop_front();
389                 glDeleteSync( sync );
390         }
391         unlock();
392
393         // Make sure we never have more than one frame pending at any time.
394         // This ensures we do not swamp the GPU with so much work
395         // that we cannot actually display the frames we generate.
396         if (prev_sync != NULL) {
397                 glFlush();
398                 glClientWaitSync( prev_sync, 0, GL_TIMEOUT_IGNORED );
399                 glDeleteSync( prev_sync );
400         }
401         chain->render_to_fbo( fbo, width, height );
402         prev_sync = glFenceSync( GL_SYNC_GPU_COMMANDS_COMPLETE, 0 );
403         GLsync sync = glFenceSync( GL_SYNC_GPU_COMMANDS_COMPLETE, 0 );
404
405         check_error();
406         glBindFramebuffer( GL_FRAMEBUFFER, 0 );
407         check_error();
408         glDeleteFramebuffers( 1, &fbo );
409         check_error();
410
411         *image = (uint8_t*) &texture->texture;
412         mlt_frame_set_image( frame, *image, 0, NULL );
413         mlt_properties_set_data( MLT_FRAME_PROPERTIES(frame), "movit.convert.texture", texture, 0,
414                 (mlt_destructor) GlslManager::release_texture, NULL );
415         mlt_properties_set_data( MLT_FRAME_PROPERTIES(frame), "movit.convert.fence", sync, 0,
416                 (mlt_destructor) GlslManager::delete_sync, NULL );
417
418         return 0;
419 }
420
421 int GlslManager::render_frame_rgba(EffectChain *chain, mlt_frame frame, int width, int height, uint8_t **image)
422 {
423         glsl_texture texture = get_texture( width, height, GL_RGBA8 );
424         if (!texture) {
425                 return 1;
426         }
427
428         // Use a PBO to hold the data we read back with glReadPixels().
429         // (Intel/DRI goes into a slow path if we don't read to PBO.)
430         int img_size = width * height * 4;
431         glsl_pbo pbo = get_pbo( img_size );
432         if (!pbo) {
433                 release_texture(texture);
434                 return 1;
435         }
436
437         // Set the FBO
438         GLuint fbo;
439         glGenFramebuffers( 1, &fbo );
440         check_error();
441         glBindFramebuffer( GL_FRAMEBUFFER, fbo );
442         check_error();
443         glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture->texture, 0 );
444         check_error();
445         glBindFramebuffer( GL_FRAMEBUFFER, 0 );
446         check_error();
447
448         chain->render_to_fbo( fbo, width, height );
449
450         // Read FBO into PBO
451         glBindFramebuffer( GL_FRAMEBUFFER, fbo );
452         check_error();
453         glBindBuffer( GL_PIXEL_PACK_BUFFER_ARB, pbo->pbo );
454         check_error();
455         glBufferData( GL_PIXEL_PACK_BUFFER_ARB, img_size, NULL, GL_STREAM_READ );
456         check_error();
457         glReadPixels( 0, 0, width, height, GL_BGRA, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0) );
458         check_error();
459
460         // Copy from PBO
461         uint8_t* buf = (uint8_t*) glMapBuffer( GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY );
462         check_error();
463         *image = (uint8_t*) mlt_pool_alloc( img_size );
464         mlt_frame_set_image( frame, *image, img_size, mlt_pool_release );
465         memcpy( *image, buf, img_size );
466
467         // Convert BGRA to RGBA
468         register uint8_t *p = *image;
469         register int n = width * height + 1;
470         while ( --n ) {
471                 uint8_t b = p[0];
472                 *p = p[2]; p += 2;
473                 *p = b; p += 2;
474         }
475
476         // Release PBO and FBO
477         glUnmapBuffer( GL_PIXEL_PACK_BUFFER_ARB );
478         check_error();
479         glBindBuffer( GL_PIXEL_PACK_BUFFER_ARB, 0 );
480         check_error();
481         glBindFramebuffer( GL_FRAMEBUFFER, 0 );
482         check_error();
483         glBindTexture( GL_TEXTURE_2D, 0 );
484         check_error();
485         mlt_properties_set_data( MLT_FRAME_PROPERTIES(frame), "movit.convert.texture", texture, 0,
486                 (mlt_destructor) GlslManager::release_texture, NULL);
487         glDeleteFramebuffers( 1, &fbo );
488         check_error();
489
490         return 0;
491 }
492
493 void GlslManager::lock_service( mlt_frame frame )
494 {
495         Mlt::Producer producer( mlt_producer_cut_parent( mlt_frame_get_original_producer( frame ) ) );
496         producer.lock();
497 }
498
499 void GlslManager::unlock_service( mlt_frame frame )
500 {
501         Mlt::Producer producer( mlt_producer_cut_parent( mlt_frame_get_original_producer( frame ) ) );
502         producer.unlock();
503 }