2 Copyright (C) 2012 Paul Davis
3 Based on code by Paul Davis, Torben Hohn as part of FST
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 /******************************************************************/
22 /** VSTFX - An engine based on FST for handling linuxVST plugins **/
23 /******************************************************************/
33 #include <glibmm/timer.h>
35 #include "ardour/linux_vst_support.h"
53 static pthread_mutex_t plugin_mutex;
55 static VSTState * vstfx_first = NULL;
57 const char magic[] = "VSTFX Plugin State v002";
59 static volatile int gui_quit = 0;
61 /*This will be our connection to X*/
63 static Display* LXVST_XDisplay = NULL;
65 /*The thread handle for the GUI event loop*/
67 static pthread_t LXVST_gui_event_thread;
69 /*Util functions to get the value of a property attached to an XWindow*/
71 static bool LXVST_xerror;
73 int TempErrorHandler(Display *display, XErrorEvent *e)
82 int getXWindowProperty(Window window, Atom atom)
87 unsigned long userCount;
92 /*Use our own Xerror handler while we're in here - in an
93 attempt to stop the brain dead default Xerror behaviour of
94 qutting the entire application because of e.g. an invalid
97 XErrorHandler olderrorhandler = XSetErrorHandler(TempErrorHandler);
99 XGetWindowProperty( LXVST_XDisplay, //The display
102 0, //Offset into the data
103 1, //Number of 32Bit chunks of data
104 false, //false = don't delete the property
105 AnyPropertyType, //Required property type mask
106 &userType, //Actual type returned
107 &userSize, //Actual format returned
108 &userCount, //Actual number of items stored in the returned data
109 &bytes, //Number of bytes remaining if a partial read
110 &data); //The actual data read
112 if(LXVST_xerror == false && userCount == 1)
113 result = *(int*)data;
115 XSetErrorHandler(olderrorhandler);
117 /*Hopefully this will return zero if the property is not set*/
126 /********************************************************************/
127 /* This is untested - have no 64Bit plugins which use this */
128 /* system of passing an eventProc address */
129 /********************************************************************/
131 long getXWindowProperty(Window window, Atom atom)
136 unsigned long userCount;
139 LXVST_xerror = false;
141 /*Use our own Xerror handler while we're in here - in an
142 attempt to stop the brain dead default Xerror behaviour of
143 qutting the entire application because of e.g. an invalid
146 XErrorHandler olderrorhandler = XSetErrorHandler(TempErrorHandler);
148 XGetWindowProperty( LXVST_XDisplay,
161 if(LXVST_xerror == false && userCount == 1)
162 result = *(long*)data;
164 XSetErrorHandler(olderrorhandler);
166 /*Hopefully this will return zero if the property is not set*/
173 /*The event handler - called from within the main GUI thread to
174 dispatch events to any VST UIs which have callbacks stuck to them*/
177 dispatch_x_events (XEvent* event, VSTState* vstfx)
179 /*Handle some of the Events we might be interested in*/
183 /*Configure event - when the window is resized or first drawn*/
185 case ConfigureNotify:
187 Window window = event->xconfigure.event;
189 int width = event->xconfigure.width;
190 int height = event->xconfigure.height;
192 /*If we get a config notify on the parent window XID then we need to see
193 if the size has been changed - some plugins re-size their UI window e.g.
194 when opening a preset manager (you might think that should be spawned as a new window...) */
196 /*if the size has changed, we flag this so that in lxvst_pluginui.cc we can make the
197 change to the GTK parent window in ardour, from its UI thread*/
199 if (window == (Window) (vstfx->linux_window)) {
200 if (width != vstfx->width || height!=vstfx->height) {
201 vstfx->width = width;
202 vstfx->height = height;
203 vstfx->want_resize = 1;
205 /*QUIRK : Loomer plugins not only resize the UI but throw it into some random
206 position at the same time. We need to re-position the window at the origin of
209 if (vstfx->linux_plugin_ui_window) {
210 XMoveWindow (LXVST_XDisplay, vstfx->linux_plugin_ui_window, 0, 0);
219 /*Reparent Notify - when the plugin UI is reparented into
220 our Host Window we will get an event here... probably... */
224 Window ParentWindow = event->xreparent.parent;
226 /*If the ParentWindow matches the window for the vstfx instance then
227 the Child window must be the XID of the pluginUI window created by the
228 plugin, so we need to see if it has a callback stuck to it, and if so
229 set that up in the vstfx */
231 /***********************************************************/
232 /* 64Bit --- This mechanism is not 64Bit compatible at the */
234 /***********************************************************/
236 if (ParentWindow == (Window) (vstfx->linux_window)) {
238 Window PluginUIWindowID = event->xreparent.window;
240 vstfx->linux_plugin_ui_window = PluginUIWindowID;
242 int result = getXWindowProperty(PluginUIWindowID, XInternAtom(LXVST_XDisplay, "_XEventProc", false));
245 vstfx->eventProc = NULL;
247 vstfx->eventProc = (void (*) (void* event))result;
251 long result = getXWindowProperty(PluginUIWindowID, XInternAtom(LXVST_XDisplay, "_XEventProc", false));
254 vstfx->eventProc = NULL;
256 vstfx->eventProc = (void (*) (void* event))result;
264 Window window = event->xany.window;
265 Atom message_type = event->xclient.message_type;
267 /*The only client message we are interested in is to signal
268 that the plugin parent window is now valid and can be passed
269 to effEditOpen when the editor is launched*/
271 if (window == (Window) (vstfx->linux_window)) {
272 char* message = XGetAtomName(LXVST_XDisplay, message_type);
274 if (strcmp(message,"LaunchEditor") == 0) {
275 if (event->xclient.data.l[0] == 0x0FEEDBAC) {
276 vstfx_launch_editor (vstfx);
289 /* Some VSTs built with toolkits e.g. JUCE will manager their own UI
290 autonomously in the plugin, running the UI in its own thread, so once
291 we have created a parent window for the plugin, its UI takes care of
294 /*Other types register a callback as an Xwindow property on the plugin
295 UI window after they create it. If that is the case, we need to call it
296 here, passing the XEvent into it*/
298 if (vstfx->eventProc == NULL) {
302 vstfx->eventProc((void*)event);
305 /** This is the main gui event loop for the plugin, we also need to pass
306 any Xevents to all the UI callbacks plugins 'may' have registered on their
307 windows, that is if they don't manage their own UIs **/
309 void* gui_event_loop (void* ptr)
312 int LXVST_sched_timer_interval = 40; //ms, 25fps
314 uint64_t clock1, clock2;
316 clock1 = g_get_monotonic_time();
317 /*The 'Forever' loop - runs the plugin UIs etc - based on the FST gui event loop*/
321 /* handle window creation requests, destroy requests,
322 and run idle callbacks */
324 /*Look at the XEvent queue - if there are any XEvents we need to handle them,
325 including passing them to all the plugin (eventProcs) we are currently managing*/
327 bool may_sleep = true;
331 /*See if there are any events in the queue*/
333 int num_events = XPending(LXVST_XDisplay);
335 if (num_events > 0) {
336 // keep dispatching events as fast as possible
340 /*process them if there are any*/
344 XNextEvent(LXVST_XDisplay, &event);
346 /*Call dispatch events, with the event, for each plugin in the linked list*/
348 for (vstfx = vstfx_first; vstfx; vstfx = vstfx->next)
350 pthread_mutex_lock(&vstfx->lock);
352 dispatch_x_events(&event, vstfx);
354 pthread_mutex_unlock(&vstfx->lock);
361 /*We don't want to use all the CPU.. */
365 /*See if its time for us to do a scheduled event pass on all the plugins*/
367 clock2 = g_get_monotonic_time();
368 const int64_t elapsed_time_ms = (clock2 - clock1) / 1000;
370 if((LXVST_sched_timer_interval != 0) && elapsed_time_ms >= LXVST_sched_timer_interval)
372 //printf("elapsed %d ms ^= %.2f Hz\n", elapsed_time_ms, 1000.0/(double)elapsed_time_ms); // DEBUG
373 pthread_mutex_lock (&plugin_mutex);
376 /*Parse through the linked list of plugins*/
378 for (vstfx = vstfx_first; vstfx; vstfx = vstfx->next)
380 pthread_mutex_lock (&vstfx->lock);
382 /*Window scheduled for destruction*/
384 if (vstfx->destroy) {
385 if (vstfx->linux_window) {
386 vstfx->plugin->dispatcher (vstfx->plugin, effEditClose, 0, 0, NULL, 0.0);
388 XDestroyWindow (LXVST_XDisplay, vstfx->linux_window);
389 /* FIXME - probably safe to assume we never have an XID of 0 but not explicitly true */
390 vstfx->linux_window = 0;
391 vstfx->destroy = FALSE;
394 vstfx_event_loop_remove_plugin (vstfx);
395 vstfx->been_activated = FALSE;
396 pthread_cond_signal (&vstfx->window_status_change);
397 pthread_mutex_unlock (&vstfx->lock);
402 /*Window does not yet exist - scheduled for creation*/
404 /* FIXME - probably safe to assume 0 is not a valid XID but not explicitly true */
405 if (vstfx->linux_window == 0) {
406 if (vstfx_create_editor (vstfx)) {
407 vstfx_error ("** ERROR ** VSTFX : Cannot create editor for plugin %s", vstfx->handle->name);
408 vstfx_event_loop_remove_plugin (vstfx);
409 pthread_cond_signal (&vstfx->window_status_change);
410 pthread_mutex_unlock (&vstfx->lock);
413 /* condition/unlock: it was signalled & unlocked in fst_create_editor() */
417 vststate_maybe_set_program (vstfx);
418 vstfx->want_program = -1;
419 vstfx->want_chunk = 0;
421 /*scheduled call to dispatcher*/
423 if (vstfx->dispatcher_wantcall) {
424 vstfx->dispatcher_retval = vstfx->plugin->dispatcher (
426 vstfx->dispatcher_opcode,
427 vstfx->dispatcher_index,
428 vstfx->dispatcher_val,
429 vstfx->dispatcher_ptr,
430 vstfx->dispatcher_opt
433 vstfx->dispatcher_wantcall = 0;
434 pthread_cond_signal (&vstfx->plugin_dispatcher_called);
437 /*Call the editor Idle function in the plugin*/
439 vstfx->plugin->dispatcher (vstfx->plugin, effEditIdle, 0, 0, NULL, 0);
442 vstfx->plugin->dispatcher (vstfx->plugin, 53, 0, 0, NULL, 0);
444 pthread_mutex_unlock (&vstfx->lock);
446 pthread_mutex_unlock (&plugin_mutex);
448 clock1 = g_get_monotonic_time();
451 if (!gui_quit && may_sleep && elapsed_time_ms + 1 < LXVST_sched_timer_interval) {
452 Glib::usleep(1000 * (LXVST_sched_timer_interval - elapsed_time_ms - 1));
456 /*Drop out to here if we set gui_quit to 1 */
461 /*The VSTFX Init function - this needs to be called before the VSTFX engine
462 can be accessed, it gets the UI thread running, opens a connection to X etc
463 normally started in globals.cc*/
465 int vstfx_init (void* ptr)
467 assert (gui_quit == 0);
468 pthread_mutex_init (&plugin_mutex, NULL);
470 int thread_create_result;
472 pthread_attr_t thread_attributes;
474 /*Init the attribs to defaults*/
476 pthread_attr_init(&thread_attributes);
478 /*Make sure the thread is joinable - this should be the default anyway -
479 so we can join to it on vstfx_exit*/
481 pthread_attr_setdetachstate(&thread_attributes, PTHREAD_CREATE_JOINABLE);
484 /*This is where we need to open a connection to X, and start the GUI thread*/
486 /*Open our connection to X - all linuxVST plugin UIs handled by the LXVST engine
487 will talk to X down this connection - X cannot handle multi-threaded access via
490 if(LXVST_XDisplay==NULL)
491 LXVST_XDisplay = XOpenDisplay(NULL); //We might be able to make this open a specific screen etc
493 /*Drop out and report the error if we fail to connect to X */
495 if(LXVST_XDisplay==NULL)
497 vstfx_error ("** ERROR ** VSTFX: Failed opening connection to X");
502 /*We have a connection to X - so start the gui event loop*/
504 /*Create the thread - use default attrs for now, don't think we need anything special*/
506 thread_create_result = pthread_create(&LXVST_gui_event_thread, &thread_attributes, gui_event_loop, NULL);
508 if(thread_create_result!=0)
510 /*There was a problem starting the GUI event thread*/
512 vstfx_error ("** ERROR ** VSTFX: Failed starting GUI event thread");
514 XCloseDisplay(LXVST_XDisplay);
523 /*The vstfx Quit function*/
532 /*We need to pthread_join the gui_thread here so
533 we know when it has stopped*/
535 // BEWARE: some Plugin GUIs can crash if the thread local storage is free()d
536 // after the shared library containing the destructor is already dl-closed.
537 // (e.g u-he LXVST GUI, crash in __nptl_deallocate_tsd) :(
538 pthread_join(LXVST_gui_event_thread, NULL);
539 pthread_mutex_destroy (&plugin_mutex);
542 /*Adds a new plugin (VSTFX) instance to the linked list*/
544 int vstfx_run_editor (VSTState* vstfx)
546 pthread_mutex_lock (&plugin_mutex);
548 /* Add the new VSTFX instance to the linked list */
550 if (vstfx_first == NULL) {
553 VSTState* p = vstfx_first;
560 /* Mark the new end of the list */
565 pthread_mutex_unlock (&plugin_mutex);
567 /* wait for the plugin editor window to be created (or not) */
569 pthread_mutex_lock (&vstfx->lock);
571 if (!vstfx->linux_window) {
572 pthread_cond_wait (&vstfx->window_status_change, &vstfx->lock);
575 pthread_mutex_unlock (&vstfx->lock);
577 if (!vstfx->linux_window) {
585 /*Creates an editor for the plugin - normally called from within the gui event loop
586 after run_editor has added the plugin (editor) to the linked list*/
588 int vstfx_create_editor (VSTState* vstfx)
590 Window parent_window;
595 /* Note: vstfx->lock is held while this function is called */
597 if (!(vstfx->plugin->flags & effFlagsHasEditor))
599 vstfx_error ("** ERROR ** VSTFX: Plugin \"%s\" has no editor", vstfx->handle->name);
604 /*Create an XWindow for the plugin to inhabit*/
606 parent_window = XCreateSimpleWindow (
608 DefaultRootWindow(LXVST_XDisplay),
618 /*Select the events we are interested in receiving - we need Substructure notify so that
619 if the plugin resizes its window - e.g. Loomer Manifold then we get a message*/
621 XSelectInput(LXVST_XDisplay,
623 SubstructureNotifyMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | ExposureMask);
625 vstfx->linux_window = parent_window;
627 vstfx->xid = parent_window; //vstfx->xid will be referenced to connect to GTK UI in ardour later
629 /*Because the plugin may be operating on a different Display* to us, and therefore
630 the two event queues can be asynchronous, although we have created the window on
631 our display, we can't guarantee it exists in the server yet, which will
632 cause BadWindow crashes if the plugin tries to use it.
634 It would be nice to use CreateNotify events here, but they don't get
635 through on all window managers, so instead we pass a client message
636 into out queue, after the XCreateWindow. When this message pops out
637 in our event handler, it will trigger the second stage of plugin
638 Editor instantiation, and by then the Window should be valid...*/
640 XClientMessageEvent event;
642 /*Create an atom to identify our message (only if it doesn't already exist)*/
644 Atom WindowActiveAtom = XInternAtom(LXVST_XDisplay, "LaunchEditor", false);
646 event.type = ClientMessage;
647 event.send_event = true;
648 event.window = parent_window;
649 event.message_type = WindowActiveAtom;
651 event.format = 32; //Data format
652 event.data.l[0] = 0x0FEEDBAC; //Something we can recognize later
654 /*Push the event into the queue on our Display*/
656 XSendEvent(LXVST_XDisplay, parent_window, FALSE, NoEventMask, (XEvent*)&event);
662 vstfx_launch_editor (VSTState* vstfx)
664 /*This is the second stage of launching the editor (see vstfx_create editor)
665 we get called here in response to receiving the ClientMessage on our Window,
666 therefore it's about as safe (as can be) to assume that the Window we created
667 is now valid in the XServer and can be passed to the plugin in effEditOpen
668 without generating BadWindow errors when the plugin reparents itself into our
671 if(vstfx->been_activated)
674 Window parent_window;
675 struct ERect* er = NULL;
680 parent_window = vstfx->linux_window;
682 /*Open the editor - Bah! we have to pass the int windowID as a void pointer - yuck
683 it gets cast back to an int as the parent window XID in the plugin - and we have to pass the
684 Display* as a long */
686 /**************************************************************/
687 /* 64Bit --- parent window is an int passed as a void* so */
688 /* that should be ok for 64Bit machines */
690 /* Display is passed in as a long - ok on arch's where sizeof */
693 /* Most linux VST plugins open a connection to X on their own */
694 /* Display anyway so it may not matter */
696 /* linuxDSP VSTs don't use the host Display* at all */
697 /**************************************************************/
699 vstfx->plugin->dispatcher (vstfx->plugin, effEditOpen, 0, (long)LXVST_XDisplay, (void*)(parent_window), 0 );
701 /*QUIRK - some plugins need a slight delay after opening the editor before you can
702 ask the window size or they might return zero - specifically discoDSP */
704 Glib::usleep(100000);
706 /*Now we can find out how big the parent window should be (and try) to resize it*/
708 vstfx->plugin->dispatcher (vstfx->plugin, effEditGetRect, 0, 0, &er, 0 );
711 // Don't crash is plugin does not implement effEditGetRect
712 // it'll result in 1x1 px window but that's not our problem :)
713 x_size = er->right - er->left;
714 y_size = er->bottom - er->top;
717 vstfx->width = x_size;
718 vstfx->height = y_size;
720 XResizeWindow(LXVST_XDisplay, parent_window, x_size, y_size);
722 XFlush (LXVST_XDisplay);
724 /*Not sure if we need to map the window or if the plugin will do it for us
725 it should be ok because XReparentWindow generates a Map event*/
727 /*mark the editor as activated - mainly so that vstfx_get_XID
728 will know it is valid*/
730 vstfx->been_activated = TRUE;
732 pthread_cond_signal (&vstfx->window_status_change);
736 /** Destroy the editor window */
738 vstfx_destroy_editor (VSTState* vstfx)
740 pthread_mutex_lock (&vstfx->lock);
741 if (vstfx->linux_window) {
742 vstfx->destroy = TRUE;
743 pthread_cond_wait (&vstfx->window_status_change, &vstfx->lock);
745 pthread_mutex_unlock (&vstfx->lock);
748 /** Remove a vstfx instance from the linked list parsed by the
752 vstfx_event_loop_remove_plugin (VSTState* vstfx)
754 /* This only ever gets called from within our GUI thread
755 so we don't need to lock here - if we did there would be
762 for (p = vstfx_first, prev = NULL; p; prev = p, p = p->next) {
765 prev->next = p->next;
771 // if this function is called, there must be
772 // at least one plugin in the linked list
775 if (vstfx_first == vstfx) {
776 vstfx_first = vstfx_first->next;